import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import type { StepHarness } from '../support/StepHarness';
import { createStepHarness } from '../support/StepHarness';

describe('Step 9 – add car', () => {
  let harness: StepHarness;

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

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

  describe('happy path', () => {
    it('adds a real car using the JSON-backed car list on Cars page', async () => {
      await harness.navigateToFixtureStep(8);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

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

      const result = await harness.executeStepWithFixtureMismatch(9, {
        carSearch: 'Acura ARX-06',
      });

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

      const carsTable = page!
        .locator('#select-car-set-cars table.table.table-striped')
        .first();

      expect(await carsTable.count()).toBeGreaterThan(0);

      const acuraCell = carsTable.locator('tbody tr td >> text=Acura ARX-06 GTP');
      expect(await acuraCell.count()).toBeGreaterThan(0);
    });
  });

  describe('state validation', () => {
    it('throws 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(9, {
          carSearch: 'Mazda MX-5',
        });
      }).rejects.toThrow(/Step 9 FAILED validation/i);
    });

    it('detects state mismatch when Cars button is missing', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      await expect(async () => {
        await harness.executeStepWithFixtureMismatch(9, {
          carSearch: 'Porsche 911',
        });
      }).rejects.toThrow(/Step 9 FAILED validation/i);
    });

    it('detects when Track container is present instead of Cars page', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      await expect(async () => {
        await harness.executeStepWithFixtureMismatch(9, {
          carSearch: 'Ferrari 488',
        });
      }).rejects.toThrow(/Step 9 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(9, {
        carSearch: 'Acura ARX-06',
      });

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

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

      const carsTable = page!
        .locator('#select-car-set-cars table.table.table-striped')
        .first();

      expect(await carsTable.count()).toBeGreaterThan(0);

      const acuraCell = carsTable.locator('tbody tr td >> text=Acura ARX-06 GTP');
      expect(await acuraCell.count()).toBeGreaterThan(0);
    });

    it('provides detailed error context in validation failure', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      let errorMessage = '';
      try {
        await harness.executeStepWithFixtureMismatch(9, {
          carSearch: 'BMW M4',
        });
      } catch (error) {
        errorMessage = error instanceof Error ? error.message : String(error);
      }

      expect(errorMessage).toContain('Step 9');
      expect(errorMessage).toMatch(/validation|mismatch|wrong page/i);
    });

    it('validates page state before attempting any Step 9 actions', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      const page = harness.adapter.getPage();
      if (!page) {
        throw new Error('Page not available');
      }

      let carModalOpened = false;
      page.on('framenavigated', () => {
        carModalOpened = true;
      });

      let validationError = false;
      try {
        await harness.executeStepWithFixtureMismatch(9, {
          carSearch: 'Audi R8',
        });
      } catch {
        validationError = true;
      }

      expect(validationError).toBe(true);
      expect(carModalOpened).toBe(false);
    });

    it('checks wizard footer state in Step 9', async () => {
      await harness.navigateToFixtureStep(11);
      await harness.adapter.getPage()?.waitForLoadState('domcontentloaded');

      await expect(async () => {
        await harness.executeStepWithFixtureMismatch(9, {
          carSearch: 'McLaren 720S',
        });
      }).rejects.toThrow();
    });
  });
});