import { DemoDialogHost } from '@/components/integrations/DemoDialogHost';
import { demoOpenEventName } from '@/components/integrations/DemoTrigger';
import enHomepage from '@/content/locales/en/homepage.json';
import { act, render, screen } from '@testing-library/react';
import { beforeAll, describe, expect, it } from 'vitest';

function openDemoForm(source: 'hero' | 'pricing') {
  const trigger = document.createElement('button');
  document.body.appendChild(trigger);
  act(() => {
    window.dispatchEvent(
      new CustomEvent(demoOpenEventName, {
        detail: { source, trigger },
      }),
    );
  });
}

describe('DemoDialogHost', () => {
  beforeAll(() => {
    HTMLDialogElement.prototype.showModal ??= function showModal() {
      this.setAttribute('open', '');
    };
    HTMLDialogElement.prototype.close ??= function close() {
      this.removeAttribute('open');
    };
  });

  it('keeps the full fleet selector for regular demo requests', () => {
    render(<DemoDialogHost locale="en" messages={enHomepage.form} enabled />);

    openDemoForm('hero');

    const fleet = screen.getByLabelText(/Approximate fleet size/) as HTMLSelectElement;
    expect(Array.from(fleet.options).map((option) => option.textContent)).toEqual([
      'Select an option',
      '1–25 vehicles',
      '26–75 vehicles',
      '76–150 vehicles',
      '150 or more vehicles',
    ]);
  });

  it('limits the pricing request fleet selector to 150 or more vehicles', () => {
    render(<DemoDialogHost locale="en" messages={enHomepage.form} enabled />);

    openDemoForm('pricing');

    const fleet = screen.getByLabelText(/Approximate fleet size/) as HTMLSelectElement;
    expect(Array.from(fleet.options).map((option) => option.textContent)).toEqual([
      '150 or more vehicles',
    ]);
    expect(fleet.value).toBe('250+');
    expect(screen.getByRole('button', { name: 'Request quote' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Create my account' })).not.toBeInTheDocument();
    expect(screen.getByRole('dialog', { name: 'Request Enterprise quote' })).toBeVisible();
    expect(screen.getByText('Enterprise quote')).toBeInTheDocument();
    expect(screen.getByText(/Share company information only/)).toBeInTheDocument();
    expect(screen.queryByText('Safe local adapter')).not.toBeInTheDocument();
    expect(screen.queryByText(/Non-production mode validates/)).not.toBeInTheDocument();
  });
});
