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

import Welcome from './Welcome';

const mockTrackEvent = vi.fn();
vi.mock('@/lib/analytics', () => ({
  trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
}));

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    usePage: vi.fn(() => ({
      props: { app_url: 'https://rankwiz.ai' },
    })),
    Head: ({ children, title }: { children?: React.ReactNode; title: string }) => (
      <>
        <title>{title}</title>
        {children}
      </>
    ),
    Link: ({
      children,
      href,
      className,
      onClick,
    }: {
      children: React.ReactNode;
      href: string;
      method?: string;
      as?: string;
      className?: string;
      onClick?: React.MouseEventHandler<HTMLAnchorElement>;
    }) => (
      <a href={href} className={className} onClick={onClick}>
        {children}
      </a>
    ),
  };
});

// Mock the useTheme hook to avoid needing ThemeProvider
vi.mock('@/Components/theme/use-theme', () => ({
  useTheme: vi.fn(() => ({
    theme: 'system',
    setTheme: vi.fn(),
    resolvedTheme: 'light',
  })),
}));

const defaultMetrics = {
  analyses_run: 1500,
  recommendations_generated: 8200,
  sites_connected: 340,
};

const emptyMetrics = {
  analyses_run: 0,
  recommendations_generated: 0,
  sites_connected: 0,
};

const defaultPricing = {
  free_price: 0,
  free_drafts: 5,
  pro_price: 49,
  pro_drafts: 30,
  team_price: 99,
  team_drafts: 200,
};

describe('Welcome', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockTrackEvent.mockClear();
    vi.stubGlobal(
      'route',
      vi.fn((name: string) => `/${name}`),
    );
    vi.stubEnv('VITE_APP_NAME', 'RankWiz');
  });

  // ============================================
  // Rendering tests
  // ============================================

  describe('rendering', () => {
    it('renders the welcome page with new headline', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getAllByText(/closes the loop between analysis and proof/).length).toBeGreaterThanOrEqual(1);
    });

    it('renders the full hero headline', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getAllByText(/closes the loop between analysis and proof/).length).toBeGreaterThanOrEqual(1);
    });

    it('sets page title to brand headline', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(document.querySelector('title')).toHaveTextContent(
        'WordPress SEO Audit Tool',
      );
    });
  });

  // ============================================
  // Navigation tests
  // ============================================

  describe('navigation', () => {
    it('shows login link when canLogin is true', () => {
      render(
        <Welcome
          can_login={true}
          can_register={false}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const loginLinks = screen.getAllByRole('link', { name: /log in/i });
      expect(loginLinks.length).toBeGreaterThan(0);
    });

    it('hides login link when canLogin is false', () => {
      render(
        <Welcome
          can_login={false}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.queryByRole('link', { name: /log in/i })).not.toBeInTheDocument();
    });

    it('shows register link in nav when canRegister is true', () => {
      render(
        <Welcome
          can_login={false}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const registerLinks = screen.getAllByRole('link', { name: /start free analysis/i });
      expect(registerLinks.length).toBeGreaterThan(0);
    });

    it('hides register links when canRegister is false', () => {
      render(
        <Welcome
          can_login={true}
          can_register={false}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(
        screen.queryByRole('link', { name: /start free analysis/i }),
      ).not.toBeInTheDocument();
    });

    it('shows multiple register CTAs when both are true', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const registerLinks = screen.getAllByRole('link', {
        name: /start free analysis/i,
      });
      expect(registerLinks.length).toBeGreaterThan(0);
    });

    it('hides both login and register links when both are false', () => {
      render(
        <Welcome
          can_login={false}
          can_register={false}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.queryByRole('link', { name: /log in/i })).not.toBeInTheDocument();
      expect(
        screen.queryByRole('link', { name: /start free analysis/i }),
      ).not.toBeInTheDocument();
    });
  });

  // ============================================
  // Hero section tests
  // ============================================

  describe('hero section', () => {
    it('shows outcome-oriented CTA when canRegister is true', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(
        screen.getAllByRole('link', { name: /start free analysis/i }).length,
      ).toBeGreaterThan(0);
    });

    it('hides hero CTA when canRegister is false', () => {
      render(
        <Welcome
          can_login={true}
          can_register={false}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(
        screen.queryByRole('link', { name: /start free analysis/i }),
      ).not.toBeInTheDocument();
    });

    it('renders hero description mentioning GSC', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const gscElements = screen.getAllByText(/Google Search Console/);
      expect(gscElements.length).toBeGreaterThan(0);
    });

    it('shows outcome-oriented secondary CTA linking to free audit', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(
        screen.getAllByRole('link', { name: /see what rankwiz finds on a real site/i }).length,
      ).toBeGreaterThan(0);
    });

    it('includes trust signals (encryption, setup time, no credit card)', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('5-minute setup')).toBeInTheDocument();
      expect(screen.getByText(/AI drafts included free/)).toBeInTheDocument();
      // "No credit card" appears in hero trust signals and final CTA
      const noCcElements = screen.getAllByText(/No credit card/);
      expect(noCcElements.length).toBeGreaterThan(0);
    });

    it('renders competitor comparison table with Surfer SEO', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Surfer SEO')).toBeInTheDocument();
      expect(screen.getByText('Clearscope')).toBeInTheDocument();
      expect(screen.getAllByText('Semrush').length).toBeGreaterThanOrEqual(1);
    });
  });

  // ============================================
  // Social proof bar tests
  // ============================================

  describe('social proof metrics', () => {
    it('renders inline social proof metrics in hero', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // "analyses run" appears in both hero inline stats and social proof section
      expect(screen.getAllByText(/analyses run/).length).toBe(2);
      expect(screen.getByText(/recommendations generated/)).toBeInTheDocument();
    });

    it('formats metrics with exact numbers', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/1,500/)).toBeInTheDocument();
      expect(screen.getByText(/8,200/)).toBeInTheDocument();
    });

    it('hides metrics bar when analyses_run is below threshold', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={emptyMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // HOME-003: metrics bar hidden when real data is sparse — rely on testimonials instead
      expect(screen.queryByText(/analyses run/)).not.toBeInTheDocument();
    });

    it('shows real metrics when analyses_run meets threshold', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={{ analyses_run: 100, recommendations_generated: 400, sites_connected: 20 }}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // "analyses run" appears in both hero inline stats and social proof section
      expect(screen.getAllByText(/analyses run/).length).toBe(2);
      expect(screen.getByText(/100/)).toBeInTheDocument();
    });
  });

  // ============================================
  // Pain → Solution section tests
  // ============================================

  describe('before/after comparison section', () => {
    it('renders the section heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/The old way vs. the RankWiz way/)).toBeInTheDocument();
    });

    it('renders before/after visual mockups', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // Old Way vs RankWiz Way summary cards
      expect(screen.getByText('The Old Way')).toBeInTheDocument();
      expect(screen.getByText('The RankWiz Way')).toBeInTheDocument();
    });
  });

  // ============================================
  // Content intelligence section tests
  // ============================================

  describe('content intelligence section', () => {
    it('renders content intelligence heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/Content intelligence, built in/)).toBeInTheDocument();
    });

    it('renders three intelligence cards', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Cannibalization Detection')).toBeInTheDocument();
      expect(screen.getByText('Topic Clustering')).toBeInTheDocument();
      expect(screen.getByText('Freshness Analysis')).toBeInTheDocument();
    });
  });

  // ============================================
  // Features section tests
  // ============================================

  describe('features section', () => {
    it('renders the features section header', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/From Diagnosis to Fix to Proof/)).toBeInTheDocument();
    });

    it('renders 9 feature cards', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Live GSC Data')).toBeInTheDocument();
      expect(screen.getByText('12 Recommendation Types')).toBeInTheDocument();
      expect(screen.getByText('Keyword Opportunities')).toBeInTheDocument();
      expect(screen.getByText('SERP Content Scoring')).toBeInTheDocument();
      expect(screen.getByText('One-Click WordPress Publish')).toBeInTheDocument();
      expect(screen.getByRole('heading', { name: 'ROI Tracking' })).toBeInTheDocument();
      expect(screen.getByRole('heading', { name: 'Traffic Anomaly Alerts' })).toBeInTheDocument();
      expect(screen.getByText('Shareable Reports')).toBeInTheDocument();
      expect(screen.getByText('Team Collaboration')).toBeInTheDocument();
    });
  });

  // ============================================
  // BYOK section tests
  // ============================================

  describe('AI banner section', () => {
    it('renders the bundled AI heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/AI drafts included on every plan/)).toBeInTheDocument();
    });

    it('renders the competitor comparison table', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Surfer SEO')).toBeInTheDocument();
      expect(screen.getByText('Clearscope')).toBeInTheDocument();
      expect(screen.getAllByText('Semrush').length).toBeGreaterThanOrEqual(1);
    });

    it('renders the pricing callout', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getAllByText('$49').length).toBeGreaterThan(0);
    });

    it('renders competitor prices in comparison table', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // $99 appears in both Surfer price and Team tier — use getAllByText
      expect(screen.getAllByText('$99').length).toBeGreaterThan(0);
      expect(screen.getByText('$170')).toBeInTheDocument();
      expect(screen.getByText('$140')).toBeInTheDocument();
    });
  });

  // ============================================
  // How It Works section tests
  // ============================================

  describe('how it works section', () => {
    it('renders the How It Works heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/Set Up in 5 Minutes/)).toBeInTheDocument();
    });

    it('renders three steps (Connect, Analyze, Fix & Track)', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Connect')).toBeInTheDocument();
      expect(screen.getByText('Analyze')).toBeInTheDocument();
      expect(screen.getByText('Fix & Track')).toBeInTheDocument();
    });

    it('renders step numbers 1-3', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      ['1', '2', '3'].forEach((num) => {
        expect(screen.getAllByText(num).length).toBeGreaterThan(0);
      });
    });
  });

  // ============================================
  // Condensed pricing section tests
  // ============================================

  describe('condensed pricing section', () => {
    it('renders the pricing heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/Start Free. Upgrade When You Need More./)).toBeInTheDocument();
    });

    it('renders three pricing tiers', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('$0')).toBeInTheDocument();
      expect(screen.getAllByText('$49').length).toBeGreaterThan(0);
      // $99 appears in both Team pricing tier and Surfer competitor price
      expect(screen.getAllByText('$99').length).toBeGreaterThan(0);
    });

    it('renders outcome-oriented CTAs', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const analyzeLinks = screen.getAllByRole('link', {
        name: /start free analysis|start free|start.*trial/i,
      });
      expect(analyzeLinks.length).toBeGreaterThan(0);
    });

    it('renders Compare All Plans link', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByRole('link', { name: /compare all plans/i })).toBeInTheDocument();
    });
  });

  // ============================================
  // Final CTA section tests
  // ============================================

  describe('final CTA section', () => {
    it('renders the outcome-oriented final CTA heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/Your GSC Data Is Waiting/)).toBeInTheDocument();
    });

    it('renders the final CTA button when canRegister is true', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const finalCta = screen.getAllByRole('link', { name: /start free analysis/i });
      expect(finalCta.length).toBeGreaterThan(0);
    });
  });

  // ============================================
  // FAQ section tests
  // ============================================

  describe('FAQ section', () => {
    it('renders FAQ heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Frequently Asked Questions')).toBeInTheDocument();
    });

    it('renders FAQ questions', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Is this just another AI writing tool?')).toBeInTheDocument();
      expect(screen.getByText('Do I need an OpenAI API key?')).toBeInTheDocument();
    });

    it('expands FAQ answer on click', async () => {
      const user = userEvent.setup();
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const button = screen.getByText('Is this just another AI writing tool?');
      await user.click(button);

      expect(screen.getByText(/one step in a diagnostic workflow/)).toBeInTheDocument();
    });
  });

  // ============================================
  // Trust & differentiation section tests
  // ============================================

  describe('trust section', () => {
    it('renders trust cards', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Encrypted Credentials')).toBeInTheDocument();
      expect(screen.getByText('Read-Only GSC Access')).toBeInTheDocument();
      expect(screen.getByText('Secure WP Connection')).toBeInTheDocument();
      expect(screen.getByText('Export Anytime')).toBeInTheDocument();
    });

    it('renders trust section heading', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText('Your data stays yours')).toBeInTheDocument();
    });
  });

  // ============================================
  // Footer tests
  // ============================================

  describe('footer', () => {
    it('renders footer with copyright text', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByText(/all rights reserved/i)).toBeInTheDocument();
    });

    it('includes current year in copyright', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const currentYear = new Date().getFullYear().toString();
      const yearElements = screen.getAllByText(new RegExp(currentYear));
      expect(yearElements.length).toBeGreaterThan(0);
    });
  });

  // ============================================
  // Branding tests
  // ============================================

  describe('branding', () => {
    it('renders logo in navigation', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const homeLink = screen
        .getAllByRole('link')
        .find((link) => link.getAttribute('href') === '/');
      expect(homeLink).toBeInTheDocument();
    });
  });

  // ============================================
  // Layout tests
  // ============================================

  describe('layout', () => {
    it('has gradient background', () => {
      const { container } = render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(container.querySelector('.bg-linear-to-b')).toBeInTheDocument();
    });

    it('has proper section structure', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(screen.getByRole('navigation')).toBeInTheDocument();
    });

    it('does not render removed sections', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // Old team section removed
      expect(screen.queryByText(/Solo SEO or 20-Person Agency/)).not.toBeInTheDocument();
      // Old workflow visualization removed
      expect(screen.queryByText(/One Connected Workflow: Detect/)).not.toBeInTheDocument();
    });
  });

  // ============================================
  // Schema / SEO tests
  // ============================================

  describe('schema markup', () => {
    it('includes FAQ schema in head', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      const scripts = document.querySelectorAll('script[type="application/ld+json"]');
      const faqSchema = Array.from(scripts).find((s) => s.textContent?.includes('FAQPage'));
      expect(faqSchema).toBeTruthy();
    });
  });

  // ============================================
  // Analytics / CTA tracking tests
  // ============================================

  describe('analytics tracking', () => {
    it('fires page_viewed event on mount', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(mockTrackEvent).toHaveBeenCalledWith(
        'page_viewed',
        expect.objectContaining({ page: 'homepage' }),
      );
    });

    it('fires cta_clicked with hero location when hero CTA is clicked', async () => {
      const user = userEvent.setup();
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // Hero CTA text matches CTA_LABELS.FREE_ENTRY
      const heroSection = screen.getByRole('main').querySelector('section');
      const heroLink = within(heroSection!).getByRole('link', {
        name: /start free analysis/i,
      });
      mockTrackEvent.mockClear();
      await user.click(heroLink);

      expect(mockTrackEvent).toHaveBeenCalledWith(
        'cta_clicked',
        expect.objectContaining({
          cta_location: 'hero',
          page: 'homepage',
        }),
      );
    });

    it('renders Product Hunt badge in hero', () => {
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      expect(
        screen.getByRole('link', { name: /view rankwiz ai on product hunt/i }),
      ).toBeInTheDocument();
    });

    it('fires cta_clicked event with page homepage for all CTA links', async () => {
      const user = userEvent.setup();
      render(
        <Welcome
          can_login={true}
          can_register={true}
          metrics={defaultMetrics}
          is_product_hunt_referral={false}
          pricing={defaultPricing}
        />,
      );

      // Scope to <main> to exclude nav CTAs (which fire page: 'marketing')
      const main = screen.getByRole('main');
      const ctaLinks = within(main).getAllByRole('link', {
        name: /start free analysis|start free|start.*trial/i,
      });
      for (const link of ctaLinks) {
        mockTrackEvent.mockClear();
        await user.click(link);
        expect(mockTrackEvent).toHaveBeenCalledWith(
          'cta_clicked',
          expect.objectContaining({
            page: 'homepage',
          }),
        );
      }
    });
  });
});
