import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    Link: ({ href, children }: { href: string; children: React.ReactNode }) => (
      <a href={href}>{children}</a>
    ),
    usePage: () => ({
      props: {
        auth: { user: { id: 1, name: 'Test User' } },
        features: {},
        flash: {},
      },
    }),
  };
});

vi.mock('./OnboardingWizard', () => ({
  // Index.tsx renames gsc_connection → gscConnection before passing to wizard
  default: (props: Record<string, unknown>) => (
    <div
      data-testid="onboarding-wizard"
      data-has-gsc={String(props.gscConnection !== null && props.gscConnection !== undefined)}
    >
      Onboarding Wizard
    </div>
  ),
}));

vi.mock('@/Layouts/DashboardLayout', () => ({
  default: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="dashboard-layout">{children}</div>
  ),
}));

import OnboardingIndex from './Index';

const baseSite = {
  id: 1,
  name: 'My Site',
  domain: 'example.com',
  is_demo: false,
};

describe('Onboarding/Index', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.stubGlobal('route', (name: string) => `/mocked/${name}`);
  });

  it('renders the onboarding wizard', () => {
    render(<OnboardingIndex site={baseSite} gsc_connection={null} wp_connection={null} />);

    expect(screen.getByTestId('onboarding-wizard')).toBeInTheDocument();
  });

  it('passes gsc_connection prop to wizard', () => {
    const gscConnection = { id: 1, property_url: 'https://example.com', gsc_property_url: 'https://example.com', status: 'synced', sync_status: 'synced', last_synced_at: null };

    render(<OnboardingIndex site={baseSite} gsc_connection={gscConnection} wp_connection={null} />);

    expect(screen.getByTestId('onboarding-wizard')).toHaveAttribute('data-has-gsc', 'true');
  });

  it('passes null gsc_connection when not connected', () => {
    render(<OnboardingIndex site={baseSite} gsc_connection={null} wp_connection={null} />);

    expect(screen.getByTestId('onboarding-wizard')).toHaveAttribute('data-has-gsc', 'false');
  });

  it('has an accessible live region for screen readers', () => {
    render(<OnboardingIndex site={baseSite} gsc_connection={null} wp_connection={null} />);

    // The component renders an sr-only live region for status announcements
    expect(document.querySelector('[aria-live]')).toBeInTheDocument();
  });

  describe('WelcomeBanner (CRO-003)', () => {
    it('shows welcome banner when just_registered=true and no GSC connection', () => {
      render(
        <OnboardingIndex
          site={baseSite}
          gsc_connection={null}
          wp_connection={null}
          just_registered={true}
        />,
      );

      expect(screen.getByRole('region', { name: 'Welcome — next step' })).toBeInTheDocument();
      expect(
        screen.getByText('Connect Google Search Console — takes 30 seconds'),
      ).toBeInTheDocument();
    });

    it('does not show welcome banner when just_registered=false', () => {
      render(
        <OnboardingIndex
          site={baseSite}
          gsc_connection={null}
          wp_connection={null}
          just_registered={false}
        />,
      );

      expect(screen.queryByRole('region', { name: 'Welcome — next step' })).not.toBeInTheDocument();
    });

    it('does not show welcome banner when GSC is already connected', () => {
      const gscConnection = {
        property_url: 'https://example.com',
        status: 'synced',
        last_synced_at: null,
      };

      render(
        <OnboardingIndex
          site={baseSite}
          gsc_connection={gscConnection}
          wp_connection={null}
          just_registered={true}
        />,
      );

      expect(screen.queryByRole('region', { name: 'Welcome — next step' })).not.toBeInTheDocument();
    });

    it('does not show welcome banner by default (just_registered omitted)', () => {
      render(<OnboardingIndex site={baseSite} gsc_connection={null} wp_connection={null} />);

      expect(screen.queryByRole('region', { name: 'Welcome — next step' })).not.toBeInTheDocument();
    });

    it('banner CTA links to GSC connect route', () => {
      render(
        <OnboardingIndex
          site={baseSite}
          gsc_connection={null}
          wp_connection={null}
          just_registered={true}
        />,
      );

      const link = screen.getByRole('link', {
        name: /Connect Google Search Console/,
      });
      expect(link).toHaveAttribute('href', '/mocked/gsc.connect');
    });
  });
});
