import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import type { StepHarness } from '../support/StepHarness';
import { createStepHarness } from '../support/StepHarness';
import { IRACING_SELECTORS } from 'core/automation/infrastructure//automation/dom/IRacingSelectors';

describe('Step 6 – admins', () => {
  let harness: StepHarness;

  beforeEach(async () => {
    harness = await createStepHarness();
  });

  afterEach(async () => {
    await harness.dispose();
  });

  it('completes successfully from Set Admins page and leaves selected admins populated', async () => {
    await harness.navigateToFixtureStep(5);
    const page = harness.adapter.getPage();
    expect(page).not.toBeNull();

    const sidebarAdmins = await page!
      .locator(IRACING_SELECTORS.wizard.sidebarLinks.admins)
      .first()
      .innerText();
    expect(sidebarAdmins).toMatch(/Admins/i);

    const adminsContainer = page!
      .locator(IRACING_SELECTORS.wizard.stepContainers.admins)
      .first();
    expect(await adminsContainer.count()).toBeGreaterThan(0);

    const result = await harness.executeStep(6, {
      adminSearch: 'Marc',
    });

    expect(result.success).toBe(true);

    const selectedAdminsText =
      (await page!.textContent(
        '#set-admins tbody[data-testid="admin-display-name-list"]',
      )) ?? '';
    expect(selectedAdminsText.trim()).not.toEqual('');

    const footerText = await page!.textContent('.wizard-footer');
    expect(footerText).toContain('Time Limit');
  });

  it('handles Add Admin drawer state without regression and preserves selected admins list', async () => {
    await harness.navigateToFixtureStep(6);
    const page = harness.adapter.getPage();
    expect(page).not.toBeNull();

    const adminsContainer = page!
      .locator(IRACING_SELECTORS.wizard.stepContainers.admins)
      .first();
    expect(await adminsContainer.count()).toBeGreaterThan(0);

    const header = await page!.textContent('#set-admins .card-header');
    expect(header).toContain('Set Admins');

    const result = await harness.executeStep(6, {
      adminSearch: 'Mintel',
    });

    expect(result.success).toBe(true);

    const selectedAdminsText =
      (await page!.textContent(
        '#set-admins tbody[data-testid="admin-display-name-list"]',
      )) ?? '';
    expect(selectedAdminsText.trim()).not.toEqual('');

    const footerText = await page!.textContent('.wizard-footer');
    expect(footerText).toContain('Time Limit');
  });
});