/**
 * Admin UI Smoke Tests
 *
 * Basic rendering tests for all admin pages to ensure they don't crash.
 * These are intentionally lightweight - full interaction testing is done in dedicated test files.
 */

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

// Mock window.location before imports (needed by useAdminFilters)
beforeEach(() => {
  Object.defineProperty(window, 'location', {
    value: { search: '', pathname: '/admin', href: 'http://localhost/admin' },
    writable: true,
    configurable: true,
  });
});

// Mock Inertia
vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    usePage: vi.fn(() => ({
      url: '/admin',
      props: {
        auth: { user: { id: 1, name: 'Admin', email: 'admin@test.com', is_admin: true } },
        features: {
          billing: true,
          socialAuth: true,
          emailVerification: true,
          apiTokens: true,
          userSettings: true,
          notifications: true,
          onboarding: false,
          apiDocs: false,
          twoFactor: true,
          webhooks: true,
          admin: true,
        },
      },
    })),
    Link: ({ children, href }: { children: React.ReactNode; href: string }) => (
      <a href={href}>{children}</a>
    ),
    router: {
      visit: vi.fn(),
      get: vi.fn(),
      post: vi.fn(),
      patch: vi.fn(),
      delete: vi.fn(),
      on: vi.fn(() => vi.fn()), // Returns cleanup function
    },
  };
});

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

// Mock CountUp
vi.mock('@/Components/ui/count-up', () => ({
  CountUp: ({ end }: { end: number }) => <span>{end}</span>,
}));

// Mock Recharts
vi.mock('recharts', () => ({
  ResponsiveContainer: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  AreaChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="area-chart">{children}</div>
  ),
  BarChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="bar-chart">{children}</div>
  ),
  PieChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="pie-chart">{children}</div>
  ),
  LineChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="line-chart">{children}</div>
  ),
  Area: () => null,
  Bar: () => null,
  Pie: () => null,
  Line: () => null,
  Cell: () => null,
  XAxis: () => null,
  YAxis: () => null,
  CartesianGrid: () => null,
  Tooltip: () => null,
  Legend: () => null,
}));

describe('Admin Navigation Config', () => {
  it('contains all required admin page hrefs', async () => {
    const { adminNavigationGroups } = await import('@/config/admin-navigation');
    const allHrefs = adminNavigationGroups.flatMap((g) => g.items.map((i) => i.href));

    const requiredHrefs = [
      '/admin/metrics',
      '/admin/impact-reports',
      '/admin/lifecycle',
      '/admin/dlq',
      '/admin/breach-incidents',
      '/admin/dsar',
      '/admin/circuit-breaker',
    ];

    for (const href of requiredHrefs) {
      expect(allHrefs).toContain(href);
    }
  });

  it('contains breach incidents and DSAR request items in admin navigation', async () => {
    const { adminNavigationGroups } = await import('@/config/admin-navigation');
    const allItems = adminNavigationGroups.flatMap((g) => g.items);
    const allHrefs = allItems.map((i) => i.href);

    expect(allHrefs).toContain('/admin/breach-incidents');
    expect(allHrefs).toContain('/admin/dsar');
  });
});

describe('Admin Accessibility Tests', () => {
  it('Users Index has a level-1 heading (landmark hierarchy)', async () => {
    const UsersIndex = (await import('./Users/Index')).default;

    render(
      <UsersIndex
        users={{
          data: [],
          current_page: 1,
          per_page: 15,
          total: 0,
          last_page: 1,
          from: 0,
          to: 0,
          links: [],
        }}
        filters={{}}
      />,
    );

    expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument();
  });

  it('Audit Logs Index has accessible filter controls with labels', async () => {
    const AuditLogsIndex = (await import('./AuditLogs/Index')).default;

    render(
      <AuditLogsIndex
        logs={{
          data: [],
          current_page: 1,
          per_page: 50,
          total: 0,
          last_page: 1,
          from: 0,
          to: 0,
          links: [],
        }}
        eventTypes={[]}
        filters={{}}
        impersonation_count={0}
        adminUsers={[]}
      />,
    );

    // Filter toggles must be reachable by role with an accessible name (not just visual)
    const switches = screen.getAllByRole('switch');
    expect(switches.length).toBeGreaterThan(0);
    // Every switch must have an accessible name
    switches.forEach((sw) => {
      expect(sw).toHaveAccessibleName();
    });
  });

  it('Sites Index has a level-1 heading and accessible link for each site name', async () => {
    const SitesIndex = (await import('./Sites/Index')).default;

    render(
      <SitesIndex
        sites={{
          data: [
            {
              id: 1,
              name: 'Test Site',
              domain: 'example.com',
              user_id: 2,
              user_name: 'Test User',
              user_email: 'test@example.com',
              health_score: '72.50',
              health_status: 'Needs Attention',
              last_analysis_at: '2026-01-15T10:00:00Z',
              has_gsc: true,
              has_wp: false,
              created_at: '2026-01-01T00:00:00Z',
            },
          ],
          current_page: 1,
          per_page: 25,
          total: 1,
          last_page: 1,
          from: 1,
          to: 1,
          links: [],
        }}
        filters={{}}
        stats={{
          total_sites: 1,
          avg_health_score: 72.5,
          both_connections_pct: 0,
          critical_count: 0,
        }}
      />,
    );

    expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument();
  });

  it('Config page has accessible feature flag switches with labels', async () => {
    const Config = (await import('./Config')).default;

    render(
      <Config
        feature_flags={[
          { key: 'billing', enabled: true, env_var: 'FEATURE_BILLING' },
          { key: 'admin', enabled: true, env_var: 'FEATURE_ADMIN' },
        ]}
        warnings={[]}
        environment={{ app_env: 'testing', timezone: 'UTC' }}
      />,
    );

    // The config page should have a visible heading
    expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument();
    // Feature flags are rendered in a list — verify at least one env var label is visible
    expect(screen.getByText('FEATURE_BILLING')).toBeInTheDocument();
  });

  it('AdminLayout renders ImpersonationBanner alert when impersonating', async () => {
    const { usePage } = await import('@inertiajs/react');
    vi.mocked(usePage).mockReturnValueOnce({
      url: '/admin',
      props: {
        auth: {
          user: { id: 1, name: 'Test User', email: 'user@test.com', is_admin: false },
          impersonating: {
            admin_name: 'Super Admin',
            remaining_seconds: 1500,
          },
        },
        features: {
          billing: true,
          socialAuth: false,
          emailVerification: false,
          apiTokens: false,
          userSettings: false,
          notifications: false,
          onboarding: false,
          apiDocs: false,
          twoFactor: false,
          webhooks: false,
          admin: true,
        },
      },
    } as unknown as ReturnType<typeof usePage>);

    const { ImpersonationBanner } = await import('@/Components/admin/ImpersonationBanner');

    render(<ImpersonationBanner />);

    // Banner must have role="alert" so screen readers announce it
    expect(screen.getByRole('alert')).toBeInTheDocument();
    expect(screen.getByText(/stop impersonating/i)).toBeInTheDocument();
  });
});

describe('Admin UI Smoke Tests', () => {
  describe('Users Pages', () => {
    it('renders Users Index page', async () => {
      const UsersIndex = (await import('./Users/Index')).default;

      render(
        <UsersIndex
          users={{
            data: [
              {
                id: 1,
                name: 'Test User',
                email: 'test@example.com',
                email_verified_at: '2026-01-01',
                is_admin: false,
                created_at: '2026-01-01',
                deleted_at: null,
                last_login_at: null,
                tokens_count: 0,
                lead_score: null,
                lead_score_tier: null,
                pql_qualified_at: null,
              },
            ],
            current_page: 1,
            per_page: 15,
            total: 1,
            last_page: 1,
            from: 1,
            to: 1,
            links: [],
          }}
          filters={{}}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Users', level: 1 })).toBeInTheDocument();
    });

    it('renders Users Show page', async () => {
      const UsersShow = (await import('./Users/Show')).default;

      render(
        <UsersShow
          user={{
            id: 1,
            name: 'Test User',
            email: 'test@example.com',
            email_verified_at: '2026-01-01',
            is_admin: false,
            created_at: '2026-01-01',
            deleted_at: null,
            last_login_at: null,
            has_password: true,
            two_factor_enabled: false,
            signup_source: 'direct',
            tokens_count: 0,
            lead_score: null,
            lead_score_tier: null,
            pql_qualified_at: null,
          }}
          recent_audit_logs={[]}
          subscription={null}
          sites_usage={{
            totals: { sites: 0, drafts: 0, applied_recommendations: 0 },
            sites: [],
          }}
          limit_overrides={{}}
          limit_defaults={{ max_sites_per_user: 5 }}
          branding={null}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Test User', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Sites Pages', () => {
    it('renders Sites Index page', async () => {
      const SitesIndex = (await import('./Sites/Index')).default;

      render(
        <SitesIndex
          sites={{
            data: [
              {
                id: 1,
                name: 'Test Site',
                domain: 'example.com',
                user_id: 2,
                user_name: 'Test User',
                user_email: 'test@example.com',
                health_score: '72.50',
                health_status: 'Needs Attention',
                last_analysis_at: '2026-01-15T10:00:00Z',
                has_gsc: true,
                has_wp: false,
                created_at: '2026-01-01T00:00:00Z',
              },
            ],
            current_page: 1,
            per_page: 25,
            total: 1,
            last_page: 1,
            from: 1,
            to: 1,
            links: [],
          }}
          filters={{}}
          stats={{
            total_sites: 1,
            avg_health_score: 72.5,
            both_connections_pct: 0,
            critical_count: 0,
          }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Sites', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Audit Logs Pages', () => {
    it('renders Audit Logs Index page', async () => {
      const AuditLogsIndex = (await import('./AuditLogs/Index')).default;

      render(
        <AuditLogsIndex
          logs={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          eventTypes={['auth.login', 'auth.logout']}
          filters={{}}
          impersonation_count={0}
          adminUsers={[]}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Audit Logs', level: 1 })).toBeInTheDocument();
    });

    it('renders Audit Logs Show page', async () => {
      const AuditLogsShow = (await import('./AuditLogs/Show')).default;

      render(
        <AuditLogsShow
          auditLog={{
            id: 1,
            event: 'auth.login',
            user_id: 1,
            user_name: 'Test User',
            user_email: 'test@example.com',
            ip: '192.168.1.1',
            user_agent: 'Mozilla/5.0',
            metadata: {},
            created_at: '2026-02-13T10:00:00Z',
          }}
          impersonation_session={null}
        />,
      );

      expect(screen.getByText('auth.login')).toBeInTheDocument();
    });
  });

  describe('Billing Pages', () => {
    it('renders Billing Dashboard page', async () => {
      const BillingDashboard = (await import('./Billing/Dashboard')).default;

      render(
        <BillingDashboard
          stats={{
            active_subscriptions: 8,
            trialing: 1,
            past_due: 1,
            canceled: 2,
            total_ever: 10,
            mrr: 8000,
            churn_rate: 0,
            trial_conversion_rate: 0,
            ltv: 0,
          }}
          tier_distribution={[]}
          status_breakdown={[]}
          growth_chart={[]}
          trial_stats={{ active_trials: 0, expiring_soon: 0 }}
          tier_usage={[
            {
              tier: 'free',
              user_count: 5,
              avg_sites: 1.2,
              avg_analyses_30d: 0.4,
              avg_drafts_30d: 0.1,
              avg_applied_recommendations_30d: 0,
              pct_gsc_connected: 20,
              pct_wp_connected: 10,
            },
            {
              tier: 'pro',
              user_count: 3,
              avg_sites: 2.5,
              avg_analyses_30d: 3.1,
              avg_drafts_30d: 2.0,
              avg_applied_recommendations_30d: 1.5,
              pct_gsc_connected: 100,
              pct_wp_connected: 66.7,
            },
            {
              tier: 'team',
              user_count: 1,
              avg_sites: 4.0,
              avg_analyses_30d: 5.0,
              avg_drafts_30d: 4.2,
              avg_applied_recommendations_30d: 3.0,
              pct_gsc_connected: 100,
              pct_wp_connected: 100,
            },
            {
              tier: 'enterprise',
              user_count: 0,
              avg_sites: 0,
              avg_analyses_30d: 0,
              avg_drafts_30d: 0,
              avg_applied_recommendations_30d: 0,
              pct_gsc_connected: 0,
              pct_wp_connected: 0,
            },
          ]}
          churn_breakdown={{ voluntary: 2, involuntary: 1, unknown: 0 }}
          checkout_funnel={{
            checkout_started: 10,
            checkout_completed: 7,
            checkout_abandoned: 3,
            conversion_rate: 70,
          }}
          ltv_by_tier={{}}
          recent_events={[]}
        />,
      );

      expect(screen.getByText('Billing Overview')).toBeInTheDocument();
    });

    it('renders Billing Subscriptions page', async () => {
      const BillingSubscriptions = (await import('./Billing/Subscriptions')).default;

      render(
        <BillingSubscriptions
          subscriptions={{
            data: [],
            current_page: 1,
            per_page: 25,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          filters={{}}
          statuses={['active', 'canceled']}
          tiers={['free', 'pro', 'team']}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Subscriptions', level: 1 })).toBeInTheDocument();
    });

    it('renders Billing Show page', async () => {
      const BillingShow = (await import('./Billing/Show')).default;

      render(
        <BillingShow
          subscription={{
            id: 1,
            user_id: 1,
            user_name: 'Test User',
            user_email: 'test@example.com',
            stripe_id: 'sub_test123',
            stripe_status: 'active',
            tier: 'pro',
            quantity: 1,
            trial_ends_at: null,
            ends_at: null,
            created_at: '2026-01-01',
          }}
          items={[]}
          audit_logs={[]}
          available_plans={[]}
        />,
      );

      expect(screen.getByText('sub_test123')).toBeInTheDocument();
    });
  });

  describe('Config & System Pages', () => {
    it('renders Config page', async () => {
      const Config = (await import('./Config')).default;

      render(
        <Config
          feature_flags={[
            { key: 'billing', enabled: true, env_var: 'FEATURE_BILLING' },
            { key: 'admin', enabled: true, env_var: 'FEATURE_ADMIN' },
          ]}
          warnings={[]}
          environment={{ app_env: 'testing', timezone: 'UTC' }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Configuration', level: 1 })).toBeInTheDocument();
    });

    it('renders System page', async () => {
      const System = (await import('./System')).default;

      render(
        <System
          system={{
            php_version: '8.3.0',
            laravel_version: '12.0.0',
            node_version: '20.0.0',
            server: {
              os: 'Linux',
              server_software: 'nginx',
            },
            database: {
              driver: 'mysql',
              version: '8.0',
            },
            queue: {
              driver: 'redis',
              pending_jobs: 0,
              failed_jobs: 0,
            },
            packages: [],
          }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'System Info', level: 1 })).toBeInTheDocument();
    });

    it('renders Health page', async () => {
      const Health = (await import('./Health')).default;

      render(
        <Health
          health={{
            status: 'healthy',
            timestamp: '2026-02-13T10:00:00Z',
            checks: {
              database: {
                status: 'healthy',
                message: 'Connection successful',
                response_time_ms: 5,
              },
              cache: { status: 'healthy', message: 'Redis responding', response_time_ms: 2 },
            },
          }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Health Status', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Feature Dashboards', () => {
    it('renders Notifications Dashboard', async () => {
      const NotificationsDashboard = (await import('./Notifications/Dashboard')).default;

      render(
        <NotificationsDashboard
          stats={{
            total_sent: 100,
            unread: 25,
            read: 75,
            read_rate: 75,
            sent_last_7d: 50,
            by_type: [
              { type: 'info', count: 50 },
              { type: 'success', count: 50 },
            ],
          }}
          volume_chart={[]}
          recent_notifications={[]}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Notifications', level: 1 })).toBeInTheDocument();
    });

    it('renders Social Auth Dashboard', async () => {
      const SocialAuthDashboard = (await import('./SocialAuth/Dashboard')).default;

      render(
        <SocialAuthDashboard
          stats={{
            total_linked: 50,
            users_with_social: 40,
            by_provider: { google: 30, github: 20 },
            expired_tokens: 0,
          }}
          linked_accounts={[]}
        />,
      );

      expect(screen.getByText('Social Authentication')).toBeInTheDocument();
    });

    it('renders Tokens Dashboard', async () => {
      const TokensDashboard = (await import('./Tokens/Dashboard')).default;

      render(
        <TokensDashboard
          stats={{
            total_tokens: 25,
            users_with_tokens: 15,
            recently_used: 10,
            expired_tokens: 5,
            never_used: 3,
          }}
          most_active={[]}
        />,
      );

      expect(screen.getByRole('heading', { name: 'API Tokens', level: 1 })).toBeInTheDocument();
    });

    it('renders TwoFactor Dashboard', async () => {
      const TwoFactorDashboard = (await import('./TwoFactor/Dashboard')).default;

      render(
        <TwoFactorDashboard
          users_with_2fa={[]}
          stats={{
            total_users: 100,
            two_factor_enabled: 40,
            adoption_rate: 40,
            without_two_factor: 60,
          }}
        />,
      );

      expect(screen.getByText('Two-Factor Authentication')).toBeInTheDocument();
    });

    it('renders Webhooks Dashboard', async () => {
      const WebhooksDashboard = (await import('./Webhooks/Dashboard')).default;

      render(
        <WebhooksDashboard
          stats={{
            total_endpoints: 15,
            active_endpoints: 12,
            total_deliveries: 1000,
            successful_deliveries: 950,
            failed_deliveries: 50,
            pending_deliveries: 0,
            failure_rate: 5,
            total_incoming: 300,
            incoming_by_provider: { github: 100, stripe: 200 },
          }}
          delivery_chart={[]}
          recent_failures={[]}
        />,
      );

      expect(screen.getByText('Webhooks Overview')).toBeInTheDocument();
    });
  });

  describe('Limit Policies Pages', () => {
    it('renders Limit Policies Index page', async () => {
      const LimitPoliciesIndex = (await import('./LimitPolicies/Index')).default;

      render(
        <LimitPoliciesIndex
          policies={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          limit_keys={['max_sites_per_user', 'max_drafts_per_month']}
          filters={{}}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Limit Policies', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Findings Pages', () => {
    it('renders Findings Index page', async () => {
      const FindingsIndex = (await import('./Findings/Index')).default;

      render(
        <FindingsIndex
          findings={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          filters={{}}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Findings', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Freshness Recommendations Pages', () => {
    it('renders Freshness Recommendations Index page', async () => {
      const FreshnessIndex = (await import('./FreshnessRecommendations/Index')).default;

      render(
        <FreshnessIndex
          recommendations={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          filters={{}}
          stats={{ total: 0, pending: 0 }}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Freshness Recommendations', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Opportunity Feedback Pages', () => {
    it('renders Opportunity Feedback Index page', async () => {
      const OpportunityFeedbackIndex = (await import('./OpportunityFeedback/Index')).default;

      render(
        <OpportunityFeedbackIndex
          feedback={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          filters={{}}
          feedback_types={['helpful', 'not_helpful']}
          opportunity_types={['striking_distance', 'ctr_gap']}
          stats={{ total: 0, resolved: 0 }}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Opportunity Feedback', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Recommendation ROI Snapshots Pages', () => {
    it('renders Recommendation ROI Snapshots Index page', async () => {
      const RoiSnapshotsIndex = (await import('./RecommendationRoiSnapshots/Index')).default;

      render(
        <RoiSnapshotsIndex
          snapshots={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          filters={{}}
          stats={{ total: 0, significant: 0 }}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Recommendation ROI Snapshots', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Webhook Deliveries Pages', () => {
    it('renders Webhook Deliveries Index page', async () => {
      const WebhookDeliveriesIndex = (await import('./WebhookDeliveries/Index')).default;

      render(
        <WebhookDeliveriesIndex
          deliveries={{
            data: [],
            current_page: 1,
            per_page: 50,
            total: 0,
            last_page: 1,
            from: 0,
            to: 0,
            links: [],
          }}
          filters={{}}
          event_types={['site.analyzed', 'recommendation.applied']}
          stats={{ total: 0, delivered: 0, failed: 0 }}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Webhook Deliveries', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Recommendations Pages', () => {
    it('renders Recommendations Index page', async () => {
      const RecommendationsIndex = (await import('./Recommendations/Index')).default;

      render(
        <RecommendationsIndex
          recommendations={{
            data: [],
            current_page: 1,
            last_page: 1,
            from: null,
            to: null,
            total: 0,
          }}
          filters={{}}
          stats={{ total: 0, pending: 0, applied: 0, avg_impact_score: 0 }}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Recommendations', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Founder Dashboard', () => {
    it('renders Founder Dashboard page', async () => {
      const FounderDashboard = (await import('./FounderDashboard')).default;

      render(
        <FounderDashboard
          stats={{
            signups_today: 3,
            dau: 42,
            wau: 120,
            mau: 400,
            total_sites: 85,
            analyses_today: 12,
            analyses_week: 55,
            analyses_month: 210,
            drafts_today: 5,
            drafts_week: 22,
            drafts_month: 90,
            published_today: 2,
            published_week: 10,
            published_month: 35,
            active_subscriptions: 18,
            mrr_estimate: 45000,
            billing_enabled: true,
            queue_pending: 4,
            queue_failed_24h: 0,
            activation_rate: 62,
          }}
          top_users={[]}
          funnel={{ stages: [], activation_rate: 62 }}
          cancellation_reasons={[]}
          north_star={{
            weekly_active_recommenders: 20,
            active_sites: 55,
            total_weekly_runs: 80,
            baseline: 15,
            target: 50,
            trend: [],
          }}
          cohort_matrix={[]}
          time_to_value={{
            median_hours: 24,
            p75_hours: 72,
            p95_hours: 168,
            sample_size: 100,
            goal_hours: 48,
          }}
          engagement_trend={[]}
          conversion_funnel={{
            pricing_viewed: 50,
            upgrade_clicked: 20,
            subscription_started: 10,
            cancellation_initiated: 2,
          }}
          monthly_churn={[]}
          nps={{ score: 42, total: 80, promoters: 45, passives: 25, detractors: 10, by_type: {} }}
          serp_adoption={{ users_with_key: 12, keywords_analyzed_7d: 88 }}
          acquisition_by_source={[]}
          activation_funnel={{
            steps: [
              { label: 'Signup', count: 100, rate: 100.0 },
              { label: 'First Analysis', count: 60, rate: 60.0 },
              { label: 'First Draft', count: 40, rate: 40.0 },
              { label: 'First Publish', count: 20, rate: 20.0 },
            ],
          }}
          onboarding_funnel={{
            stages: [
              { name: 'Signup', users: 100, rate: 100.0 },
              { name: 'Site Added', users: 80, rate: 80.0 },
              { name: 'GSC Connected', users: 60, rate: 60.0 },
              { name: 'WP Connected', users: 40, rate: 40.0 },
            ],
            completion_rate: 40.0,
          }}
          recommendation_lifecycle={{ stage_counts: {}, total: 0, applied_rate: 0.0 }}
          data_quality={{
            score: null,
            total_events_7d: 0,
            validation_failures_7d: 0,
            computed_at: null,
          }}
          metric_errors={[]}
          funnel_period={90}
          posthog_configured={false}
          last_refreshed_at="2026-03-24T00:00:00Z"
          cache_ttl_seconds={300}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Founder Dashboard', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Sites Show Page', () => {
    it('renders Sites Show page with site name as heading', async () => {
      const SitesShow = (await import('./Sites/Show')).default;

      render(
        <SitesShow
          site={{
            id: 1,
            name: 'Acme Blog',
            domain: 'acme.com',
            user_id: 2,
            health_score: '88.00',
            health_status: 'Healthy',
            created_at: '2026-01-01T00:00:00Z',
            deleted_at: null,
            user: { id: 2, name: 'Alice', email: 'alice@acme.com' },
          }}
          analysis_runs={[]}
          connections={{ gsc: null, wp: null }}
          recent_recommendations={[]}
          wp_posts={[]}
          stats={{
            recommendation_count: 0,
            draft_count: 0,
            wp_post_count: 0,
            analysis_run_count: 0,
          }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Acme Blog', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Operations Page', () => {
    it('renders Operations Dashboard page', async () => {
      const OperationsIndex = (await import('./Operations/Index')).default;

      render(
        <OperationsIndex
          active_jobs={{ analysis_runs: 0, ai_jobs: 0, batch_jobs: 0 }}
          queue_health={{
            pending: 0,
            failed_24h: 0,
            failed_1h: 0,
            oldest_pending_minutes: null,
            by_queue: [],
          }}
          stuck_jobs={[]}
          recent_failures={[]}
          byok_health={{
            total: 0,
            valid: 0,
            invalid: 0,
            never_validated: 0,
            rate_limited: 0,
            quota_exceeded: 0,
            consecutive_failures_3plus: 0,
          }}
          connection_health={{
            gsc: { total: 0, unhealthy: 0 },
            wp: { total: 0, unhealthy: 0 },
          }}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'Operations Dashboard', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('Analysis Runs Pages', () => {
    it('renders Analysis Runs Index page', async () => {
      const AnalysisRunsIndex = (await import('./AnalysisRuns/Index')).default;

      render(
        <AnalysisRunsIndex
          runs={{
            data: [],
            current_page: 1,
            last_page: 1,
            from: null,
            to: null,
            total: 0,
          }}
          filters={{}}
          stats={{ total: 0, completed: 0, failed: 0, processing: 0 }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Analysis Runs', level: 1 })).toBeInTheDocument();
    });
  });

  describe('Content Briefs Admin Pages', () => {
    it('renders Content Briefs Index page', async () => {
      const ContentBriefsIndex = (await import('./ContentBriefs/Index')).default;

      render(
        <ContentBriefsIndex
          briefs={{
            data: [],
            current_page: 1,
            last_page: 1,
            from: null,
            to: null,
            total: 0,
          }}
          filters={{ status: '' }}
          stats={{ total: 0, completed: 0, pending: 0, failed: 0 }}
        />,
      );

      expect(screen.getByRole('heading', { name: 'Content Briefs', level: 1 })).toBeInTheDocument();
    });
  });

  describe('GSC Connections Pages', () => {
    it('renders GSC Connections Index page', async () => {
      const GscConnectionsIndex = (await import('./GscConnections/Index')).default;

      render(
        <GscConnectionsIndex
          connections={{
            data: [],
            current_page: 1,
            last_page: 1,
            per_page: 25,
            from: null,
            to: null,
            total: 0,
            links: [],
          }}
          stats={{ total: 0, synced: 0, syncing: 0, failed: 0, token_expired: 0 }}
          filters={{}}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'GSC Connections', level: 1 }),
      ).toBeInTheDocument();
    });
  });

  describe('GSC Metrics Pages', () => {
    it('renders GSC Metrics Index page', async () => {
      const GscMetricsIndex = (await import('./GscMetrics/Index')).default;

      render(
        <GscMetricsIndex
          metrics={{
            data: [],
            current_page: 1,
            last_page: 1,
            per_page: 50,
            from: null,
            to: null,
            total: 0,
            links: [],
          }}
          stats={{ total_rows: 0, sites_with_data: 0, date_min: null, date_max: null }}
          filters={{}}
        />,
      );

      expect(
        screen.getByRole('heading', { name: 'GSC Page Metrics', level: 1 }),
      ).toBeInTheDocument();
    });
  });
});
