// @vitest-environment jsdom

import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { QuestionnaireCard } from '../QuestionnaireCard';
import type { Questionnaire } from '../types';

(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;

const QUESTIONNAIRE: Questionnaire = {
  title: 'Prepare the release',
  questions: [
    {
      id: 'environment',
      header: 'Destinations',
      prompt: 'Where should the release go?',
      mode: 'single_choice',
      required: true,
      options: [{ id: 'staging', label: 'Staging' }],
    },
    {
      id: 'strategy',
      header: 'Rollout',
      prompt: 'How should the release roll out?',
      mode: 'single_choice',
      required: false,
      options: [{ id: 'canary', label: 'Canary' }],
    },
    {
      id: 'context',
      header: 'Context',
      prompt: 'What should the agent verify?',
      mode: 'text',
      required: true,
      options: [],
    },
  ],
};

describe('QuestionnaireCard stepper accessibility', () => {
  const roots: Root[] = [];
  const containers: HTMLElement[] = [];

  afterEach(() => {
    act(() => roots.splice(0).forEach((root) => root.unmount()));
    containers.splice(0).forEach((container) => container.remove());
  });

  it('renders a matching tabpanel target for every step trigger', () => {
    const container = document.createElement('div');
    document.body.append(container);
    containers.push(container);
    const root = createRoot(container);
    roots.push(root);

    act(() => {
      root.render(
        <QuestionnaireCard
          questionnaire={QUESTIONNAIRE}
          draft={{ selectedIds: {}, other: {} }}
          status="pending"
          onSelect={vi.fn()}
          onOtherChange={vi.fn()}
          onSubmit={vi.fn()}
          onDecline={vi.fn()}
        />,
      );
    });

    const triggers = Array.from(container.querySelectorAll<HTMLElement>('[role="tab"]'));
    expect(triggers).toHaveLength(QUESTIONNAIRE.questions.length);

    for (const trigger of triggers) {
      const targetId = trigger.getAttribute('aria-controls');
      expect(targetId).toBeTruthy();
      const target = targetId ? document.getElementById(targetId) : null;
      expect(target?.getAttribute('role')).toBe('tabpanel');
      expect(target?.getAttribute('aria-labelledby')).toBe(trigger.id);
    }

    const firstTargetId = triggers[0]?.getAttribute('aria-controls');
    const lastTargetId = triggers.at(-1)?.getAttribute('aria-controls');
    expect(firstTargetId ? document.getElementById(firstTargetId)?.hidden : true).toBe(false);
    expect(lastTargetId ? document.getElementById(lastTargetId)?.hidden : false).toBe(true);

    act(() => {
      triggers.at(-1)?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
    });

    expect(firstTargetId ? document.getElementById(firstTargetId)?.hidden : false).toBe(true);
    expect(lastTargetId ? document.getElementById(lastTargetId)?.hidden : true).toBe(false);
  });
});
