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 8 – cars', () => {
  let harness: StepHarness;

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

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

  describe('alignment', () => {
    it('executes on Cars page in mock wizard and exposes Add Car UI', async () => {
      await harness.navigateToFixtureStep(8);

      const page = harness.adapter.getPage();
      expect(page).not.toBeNull();

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

      const addCarButton = page!
        .locator(IRACING_SELECTORS.steps.addCarButton)
        .first();
      const addCarText = await addCarButton.innerText();
      expect(addCarText.toLowerCase()).toContain('add a car');

      const result = await harness.executeStepWithFixtureMismatch(8, {});

      expect(result.success).toBe(true);
      expect(result.error).toBeUndefined();
    });
  });

  describe('state validation', () => {
    it('fails validation when executed on Track page instead of Cars page', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      await expect(async () => {
        await harness.executeStepWithFixtureMismatch(8, {});
      }).rejects.toThrow(/Step 8 FAILED validation/i);
    });

    it('fails fast on Step 8 if already past Cars page', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      await expect(async () => {
        await harness.executeStepWithFixtureMismatch(8, {});
      }).rejects.toThrow(/Step 8 FAILED validation/i);
    });

    it('passes validation when on Cars page', async () => {
      await harness.navigateToFixtureStep(8);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      const result = await harness.executeStepWithFixtureMismatch(8, {});

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