import {
  AlertTriangle,
  BarChart3,
  Bell,
  CheckCircle2,
  FileText,
  GitMerge,
  Key,
  Layers,
  LayoutGrid,
  RefreshCw,
  Rocket,
  Sparkles,
  Target,
  Clock,
  Flame,
  X,
} from 'lucide-react';

import { useEffect, useState } from 'react';

import { Head, Link, usePage } from '@inertiajs/react';

import { UpgradePrompt } from '@/Components/billing/UpgradePrompt';
import ConnectionHealthPanel, {
  ServiceHealth,
} from '@/Components/CircuitBreaker/ConnectionHealthPanel';
import { BannerStack, type BannerEntry } from '@/Components/Dashboard/BannerStack';
import GettingStartedView from '@/Components/Dashboard/GettingStartedView';
import IntegrationStatusCard from '@/Components/Dashboard/IntegrationStatusCard';
import RecommendationFunnel from '@/Components/Dashboard/RecommendationFunnel';
import SetupProgressCard from '@/Components/Dashboard/SetupProgressCard';
import SetupProgressPill from '@/Components/Dashboard/SetupProgressPill';
import HealthScoreBreakdown from '@/Components/HealthScore/HealthScoreBreakdown';
import HealthScoreCard from '@/Components/HealthScore/HealthScoreCard';
import PageHeader from '@/Components/layout/PageHeader';
import ContextualHelp from '@/Components/Shared/ContextualHelp';
import { Alert, AlertDescription, AlertTitle } from '@/Components/ui/alert';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent, trackProductEvent } from '@/lib/analytics';
import {
  DASHBOARD_VIEWED,
  DashboardViewedProps,
  ONBOARDING_RESUME_CLICKED,
} from '@/lib/event-catalog';
import { formatRelativeTime, truncateUrl, formatNumber } from '@/lib/format';
import { PageProps } from '@/types';

interface FunnelMetrics {
  generated: number;
  approved: number;
  applied: number;
}

interface TopDecliningPage {
  id: number;
  page_url: string;
  delta_percent: number;
  delta_absolute: number;
}

interface DashboardMetrics {
  total_clicks_28d: number;
  pending_recommendations: number;
  drafts_generated_month: number;
  top_declining_pages: { data: TopDecliningPage[] };
  latest_analysis_at: string | null;
}

interface GscExpiringConnection {
  site_id: number;
  site_name: string;
  expires_at: string;
  days_until_expiry: number;
}

interface ContentIntelligence {
  cannibalization_count: number;
  topic_cluster_count: number;
  freshness_count: number;
  keyword_opportunity_count: number;
}

interface UserActivity {
  analyses_this_week: number;
  recommendations_total: number;
  recommendations_applied: number;
  recommendations_pending: number;
}

interface DashboardPageProps extends PageProps {
  funnel_metrics: FunnelMetrics;
  dashboard_metrics: DashboardMetrics;
  health_score: {
    score: number | null;
    previous_score: number | null;
    status: string;
    trend: string;
    calculated_at: string | null;
    components: {
      traffic_trend: number | null;
      content_quality: number | null;
      recommendation_completion: number | null;
      roi_performance: number | null;
      connection_health: number | null;
    };
  };
  wizard_completed?: boolean;
  onboarding_feature_enabled?: boolean;
  is_activated?: boolean;
  has_reviewed_recommendation?: boolean;
  setup_dismissed?: boolean;
  force_show_next_step?: string | null;
  gsc_connected_no_run?: boolean;
  step2_banner_dismissed?: boolean;
  gsc_syncing?: boolean;
  first_site?: {
    id: number;
    name: string;
    domain: string;
  };
  gsc_expiring_connections?: GscExpiringConnection[];
  service_health?: ServiceHealth[];
  content_intelligence: ContentIntelligence;
  activity?: UserActivity;
  streak?: { weeks: number; last_updated: string | null };
  streak_milestone_notification?: { id: string; weeks: number } | null;
}

export default function Dashboard({
  funnel_metrics: funnelMetrics,
  dashboard_metrics: dashboardMetrics,
  health_score: healthScore,
  wizard_completed: wizardCompleted = true,
  onboarding_feature_enabled: onboardingFeatureEnabled = true,
  is_activated: isActivated = true,
  has_reviewed_recommendation: hasReviewedRecommendation = false,
  setup_dismissed: setupDismissed = false,
  force_show_next_step: forceShowNextStep = null,
  gsc_connected_no_run: gscConnectedNoRun = false,
  step2_banner_dismissed: step2BannerDismissedProp = false,
  gsc_syncing: gscSyncing = false,
  first_site: firstSite,
  sites,
  gsc_expiring_connections = [],
  service_health: serviceHealth = [],
  content_intelligence: contentIntelligence,
  activity,
  streak,
  streak_milestone_notification: streakMilestoneNotification = null,
}: DashboardPageProps) {
  const { auth, has_serp_key, limits, plan } = usePage<PageProps>().props;
  const topDeclining = dashboardMetrics?.top_declining_pages?.data ?? [];
  const currentSite = sites?.find((s) => s.id === firstSite?.id);

  const [onboardingBannerDismissed, setOnboardingBannerDismissed] = useState(() => {
    try {
      return localStorage.getItem(`onboarding_banner_dismissed_${auth.user?.id}`) === '1';
    } catch {
      return false;
    }
  });

  const dismissOnboardingBanner = () => {
    try {
      localStorage.setItem(`onboarding_banner_dismissed_${auth.user?.id}`, '1');
    } catch {
      // ignore storage errors
    }
    setOnboardingBannerDismissed(true);
  };

  const [streakMilestoneDismissed, setStreakMilestoneDismissed] = useState(() => {
    if (!streakMilestoneNotification) return true;
    try {
      return (
        localStorage.getItem(`streak_milestone_dismissed_${streakMilestoneNotification.id}`) === '1'
      );
    } catch {
      return false;
    }
  });

  const dismissStreakMilestoneBanner = () => {
    if (streakMilestoneNotification) {
      try {
        localStorage.setItem(`streak_milestone_dismissed_${streakMilestoneNotification.id}`, '1');
      } catch {
        // ignore storage errors
      }
    }
    setStreakMilestoneDismissed(true);
  };

  // ACT-004: Step-2 banner dismissal — server-side for cross-device persistence
  const [step2BannerDismissed, setStep2BannerDismissed] = useState(step2BannerDismissedProp);

  const dismissStep2Banner = () => {
    setStep2BannerDismissed(true);
    fetch('/api/settings', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN':
          (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ??
          '',
      },
      body: JSON.stringify({ key: 'onboarding_step2_banner_dismissed', value: 'true' }),
    }).catch(() => {
      // Server persistence is best-effort; local state update is the primary guard
    });
  };

  useEffect(() => {
    trackProductEvent<DashboardViewedProps>(DASHBOARD_VIEWED, {
      site_id: String(firstSite?.id ?? '0'),
      site_count: sites?.length ?? 0,
      plan_tier: plan ?? 'free',
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ACT-006: Keep setup card visible until user has reviewed at least one recommendation
  const showSetupCard = (!isActivated || !hasReviewedRecommendation) && currentSite;
  const showIntegrationStatus =
    currentSite && (!currentSite.ai_available || !has_serp_key || !currentSite.has_wp);

  const intelligenceCards = contentIntelligence
    ? [
        {
          key: 'cannibalization',
          label: 'Cannibalization Issues',
          description: 'Competing pages for the same keywords',
          count: contentIntelligence.cannibalization_count,
          icon: GitMerge,
          href: firstSite ? route('cannibalization.index', firstSite.id) : '#',
          emptyLabel: 'competing pages',
        },
        {
          key: 'clusters',
          label: 'Topic Clusters',
          description: 'Grouped content by semantic topic',
          count: contentIntelligence.topic_cluster_count,
          icon: Layers,
          href: firstSite ? route('topic-clusters.index', firstSite.id) : '#',
          emptyLabel: 'topic clusters',
        },
        {
          key: 'freshness',
          label: 'Content Freshness',
          description: 'Pages needing a refresh or update',
          count: contentIntelligence.freshness_count,
          icon: RefreshCw,
          href: firstSite ? route('freshness.index', firstSite.id) : '#',
          emptyLabel: 'freshness issues',
        },
        {
          key: 'opportunities',
          label: 'Keyword Opportunities',
          description: 'Queries ready to climb the rankings',
          count: contentIntelligence.keyword_opportunity_count,
          icon: Target,
          href: firstSite ? route('opportunity-map.index', firstSite.id) : '#',
          emptyLabel: 'keyword opportunities',
        },
      ]
    : [];

  // M4: Priority-stacked banner notifications. The dashboard previously rendered up
  // to six independent dismissible banners as siblings — connection issues could be
  // pushed off-screen by lower-priority nudges. BannerStack renders the top N (default 2)
  // by priority and collapses the rest into a "n more notifications" affordance.
  // Priority ladder (highest → lowest): connection > billing > setup > nudge.
  const banners: BannerEntry[] = [];

  // CRO-003: GSC sync-in-progress (connection) — shown while the first GSC sync is running.
  if (gscSyncing && firstSite) {
    banners.push({
      key: 'gsc-syncing',
      priority: 'connection',
      render: () => (
        <Alert className="mb-8 border-primary/40 bg-primary/5 sticky top-0 z-10">
          <Rocket className="h-5 w-5 text-primary" />
          <AlertTitle className="text-base font-semibold">Your GSC data is syncing</AlertTitle>
          <AlertDescription className="mt-1 flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4">
            <span className="text-muted-foreground text-sm">
              We&apos;ll notify you when it&apos;s ready to analyze. Feel free to explore in the
              meantime.
            </span>
            {typeof Notification !== 'undefined' && Notification.permission === 'default' && (
              <button
                type="button"
                onClick={() => Notification.requestPermission()}
                className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-primary/40 bg-background px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring transition-colors"
              >
                <Bell className="h-3.5 w-3.5" aria-hidden="true" />
                Notify me when ready
              </button>
            )}
          </AlertDescription>
        </Alert>
      ),
    });
  }

  // GSC connection expiry warnings (connection) — one banner slot for the whole list so
  // multiple expiring connections stay grouped under one notification entry.
  if (gsc_expiring_connections && gsc_expiring_connections.length > 0) {
    banners.push({
      key: 'gsc-expiring',
      priority: 'connection',
      render: () => (
        <div className="mb-8 space-y-2">
          {gsc_expiring_connections.map((connection) => (
            <Alert key={connection.site_id} className="border-warning/30 bg-warning/5">
              <AlertTriangle className="h-5 w-5 text-warning" />
              <AlertTitle className="text-sm font-semibold">
                Google Search Console Connection Expires Soon
              </AlertTitle>
              <AlertDescription className="text-sm mt-1">
                Your GSC connection for <strong>{connection.site_name}</strong> expires in{' '}
                {connection.days_until_expiry} day{connection.days_until_expiry !== 1 ? 's' : ''}.
                Re-authenticate to avoid data gaps.
                {firstSite && (
                  <Button asChild size="sm" variant="outline" className="ml-3 mt-2 inline-flex">
                    <Link href={route('onboarding.index', connection.site_id)}>Reconnect GSC</Link>
                  </Button>
                )}
              </AlertDescription>
            </Alert>
          ))}
        </div>
      ),
    });
  }

  // ACT-008: Resume Onboarding (setup) — shown for users who haven't completed the wizard.
  if (
    onboardingFeatureEnabled &&
    !wizardCompleted &&
    !gscConnectedNoRun &&
    firstSite &&
    !onboardingBannerDismissed
  ) {
    banners.push({
      key: 'onboarding-resume',
      priority: 'setup',
      render: () => (
        <Alert className="mb-8 border-primary/60 bg-primary/10 relative">
          <Rocket className="h-6 w-6 text-primary" />
          <AlertTitle className="text-xl font-bold">Your SEO data is waiting</AlertTitle>
          <AlertDescription className="mt-2">
            <p className="mb-3 text-muted-foreground">
              Finish setup to see which pages are losing traffic, where you're close to ranking, and
              get AI-written fixes ready to publish — in minutes.
            </p>
            <Button asChild>
              <Link href={`/sites/${firstSite.id}/onboarding`}>Resume Onboarding</Link>
            </Button>
          </AlertDescription>
          <button
            onClick={dismissOnboardingBanner}
            className="absolute top-3 right-3 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
            aria-label="Dismiss onboarding banner"
          >
            <X className="h-4 w-4" />
          </button>
        </Alert>
      ),
    });
  }

  // CRO-004: Step-2 banner (setup) — GSC connected but no analysis yet.
  if (gscConnectedNoRun && firstSite && !step2BannerDismissed) {
    banners.push({
      key: 'step-2-banner',
      priority: 'setup',
      render: () => (
        <Alert className="mb-8 border-primary/50 bg-primary/5 relative">
          <Rocket className="h-5 w-5 text-primary" />
          <AlertTitle className="text-lg font-semibold">
            Step 2 of 3 — Run Your First Analysis
          </AlertTitle>
          <AlertDescription className="mt-2">
            <p className="mb-3 text-muted-foreground">
              Your Google Search Console is connected. Run your first analysis to surface SEO
              opportunities and get actionable recommendations.
            </p>
            <Button asChild>
              <Link
                href={`/sites/${firstSite.id}/onboarding`}
                onClick={() =>
                  trackEvent(ONBOARDING_RESUME_CLICKED, {
                    site_id: String(firstSite.id),
                    step: '2',
                    step_name: 'analysis',
                    source: 'dashboard_banner',
                  })
                }
              >
                Continue Setup
              </Link>
            </Button>
          </AlertDescription>
          <button
            onClick={dismissStep2Banner}
            className="absolute top-3 right-3 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
            aria-label="Dismiss step 2 banner"
          >
            <X className="h-4 w-4" />
          </button>
        </Alert>
      ),
    });
  }

  // ACT-008: Post-wizard pre-activation (setup) — wizard done but no analysis.
  if (wizardCompleted && !isActivated && !gscConnectedNoRun && firstSite) {
    banners.push({
      key: 'post-wizard-pre-activation',
      priority: 'setup',
      render: () => (
        <Alert className="mb-8 border-primary/50 bg-primary/5">
          <Rocket className="h-5 w-5 text-primary" />
          <AlertTitle className="text-lg font-semibold">Run Your First Analysis</AlertTitle>
          <AlertDescription className="mt-2">
            <p className="mb-3 text-muted-foreground">
              Your setup is complete. Run your first analysis to surface SEO opportunities and get
              actionable recommendations for your site.
            </p>
            <Button asChild>
              <Link href={route('analyze.index', firstSite.id)}>Run Analysis Now</Link>
            </Button>
          </AlertDescription>
        </Alert>
      ),
    });
  }

  // RET-005: Streak milestone (nudge) — celebrate 4/8/12/26/52-week streaks.
  if (streakMilestoneNotification && !streakMilestoneDismissed) {
    // Inertia SSR renders pages without a `window` global; guard before reading hostname.
    const shareHostname = typeof window !== 'undefined' ? window.location.hostname : 'my site';
    banners.push({
      key: `streak-milestone-${streakMilestoneNotification.id}`,
      priority: 'nudge',
      render: () => (
        <Alert className="mb-8 border-orange-500/30 bg-orange-500/5 relative">
          <Flame className="h-5 w-5 text-orange-500" />
          <AlertTitle className="text-lg font-semibold">
            🎉 {streakMilestoneNotification.weeks}-Week SEO Streak!
          </AlertTitle>
          <AlertDescription className="mt-2">
            <p className="mb-3 text-muted-foreground">
              You&apos;ve maintained a <strong>{streakMilestoneNotification.weeks}-week</strong>{' '}
              analysis streak. Consistent SEO analysis is the fastest path to better rankings!
            </p>
            <a
              href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(`I just hit a ${streakMilestoneNotification.weeks}-week SEO streak with ${shareHostname}! 🔥 Consistent analysis = better rankings.`)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 rounded-md bg-orange-500 px-3 py-1.5 text-sm font-medium text-white hover:bg-orange-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring transition-colors"
            >
              Share on X / Twitter
            </a>
          </AlertDescription>
          <button
            onClick={dismissStreakMilestoneBanner}
            className="absolute top-3 right-3 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
            aria-label="Dismiss streak milestone"
          >
            <X className="h-4 w-4" />
          </button>
        </Alert>
      ),
    });
  }

  // ACT-006: Results ready (nudge) — first analysis complete, recs await review.
  if (
    isActivated &&
    !hasReviewedRecommendation &&
    firstSite &&
    dashboardMetrics?.pending_recommendations > 0
  ) {
    banners.push({
      key: 'results-ready',
      priority: 'nudge',
      render: () => (
        <Alert className="mb-8 border-success/50 bg-success/5">
          <Sparkles className="h-5 w-5 text-success" />
          <AlertTitle className="text-lg font-semibold">Your Results Are Ready</AlertTitle>
          <AlertDescription className="mt-2">
            <p className="mb-3 text-muted-foreground">
              Your first analysis found {dashboardMetrics.pending_recommendations} recommendation
              {dashboardMetrics.pending_recommendations !== 1 ? 's' : ''}. Review them to start
              improving your traffic.
            </p>
            <Button asChild>
              <Link
                href={route('recommendations.index', firstSite.id) + '?lifecycle_status=pending'}
              >
                Review Recommendations
              </Link>
            </Button>
          </AlertDescription>
        </Alert>
      ),
    });
  }

  return (
    <DashboardLayout>
      <Head title="Dashboard" />

      <PageHeader
        title="Dashboard"
        subtitle={
          sites && sites.length > 1
            ? `Aggregated metrics across ${sites.length} sites`
            : 'Your SEO performance overview'
        }
        actions={
          (setupDismissed && !isActivated && currentSite) || (streak && streak.weeks > 0) ? (
            <>
              {/* ACT-006: Persistent progress anchor — visible after checklist dismiss until activation */}
              {setupDismissed && !isActivated && currentSite && (
                <SetupProgressPill site={currentSite} />
              )}
              {streak && streak.weeks > 0 && (
                <div className="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 shadow-sm">
                  <Flame
                    className={`h-5 w-5 ${streak.weeks >= 4 ? 'text-orange-500' : 'text-muted-foreground'}`}
                    aria-hidden="true"
                  />
                  <div className="text-right">
                    <p className="text-lg font-bold leading-none">{streak.weeks}</p>
                    <p className="text-xs text-muted-foreground">
                      week{streak.weeks !== 1 ? 's' : ''} streak
                    </p>
                  </div>
                </div>
              )}
            </>
          ) : undefined
        }
      />

      <div className="container py-8">
        {/* M4: Priority-stacked notifications (see `banners` array above). */}
        <BannerStack banners={banners} />

        {/* ACT-006/007: Progressive disclosure — GettingStartedView for non-activated users */}
        {showSetupCard && !setupDismissed && (
          <div className="mb-8">
            <GettingStartedView userName={auth.user?.name ?? ''} site={currentSite} />
          </div>
        )}
        {showSetupCard && setupDismissed && (
          <div className="mb-8">
            <SetupProgressCard site={currentSite} dismissed={setupDismissed} />
          </div>
        )}

        {/* ACT-005: Non-dismissable safety net — user dismissed all guidance but isn't activated yet */}
        {forceShowNextStep && firstSite && (
          <Alert className="mb-6 border-primary/40 bg-primary/5">
            <Rocket className="h-4 w-4 text-primary" />
            <AlertDescription className="flex items-center gap-1.5 text-sm">
              <span className="font-medium">Next step:</span>{' '}
              <Link
                href={
                  forceShowNextStep === 'connect_gsc'
                    ? route('onboarding.index', firstSite.id)
                    : route('analyze.index', firstSite.id)
                }
                className="underline underline-offset-2"
              >
                {forceShowNextStep === 'connect_gsc'
                  ? 'Connect Google Search Console'
                  : 'Run your first analysis'}
              </Link>
            </AlertDescription>
          </Alert>
        )}

        {/* Upgrade prompts — only shown post-activation, when user has experienced value */}
        {isActivated && limits && (
          <div className="mb-6 space-y-3">
            {limits.sites_used_count >= limits.max_sites_per_user * 0.8 && (
              <UpgradePrompt
                limitType="sites"
                currentUsage={limits.sites_used_count}
                maxUsage={limits.max_sites_per_user}
                proLimit={limits.pro_sites}
              />
            )}
            {limits.max_drafts_per_month !== null && (
              <UpgradePrompt
                limitType="drafts"
                currentUsage={limits.drafts_used_this_month}
                maxUsage={limits.max_drafts_per_month}
                proLimit={limits.pro_drafts_per_month}
              />
            )}
          </div>
        )}

        {/* Integration Status Card — shown when at least one integration is missing */}
        {showIntegrationStatus && currentSite && (
          <div className="mb-8">
            <IntegrationStatusCard
              aiAvailable={currentSite.ai_available ?? false}
              hasSerpKey={has_serp_key}
              hasWp={currentSite.has_wp}
              siteId={currentSite.id}
            />
          </div>
        )}

        {/* Portfolio Dashboard Link */}
        {sites && sites.length >= 2 && (
          <Card className="mb-8 border-info/30 bg-info/5">
            <CardHeader className="pb-3">
              <div className="flex items-center gap-2">
                <LayoutGrid className="h-5 w-5 text-info" />
                <CardTitle className="text-lg">Multi-Site Portfolio</CardTitle>
              </div>
              <CardDescription>
                View aggregate metrics and compare performance across all {sites.length} sites
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button asChild variant="default" size="sm">
                <Link href="/portfolio">View Portfolio Dashboard</Link>
              </Button>
            </CardContent>
          </Card>
        )}

        {/* SEO Metrics Grid */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-8">
          {/* Total Clicks 28d */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium flex items-center gap-1.5">
                Total Clicks (28d)
                <ContextualHelp>
                  The total number of times users clicked on your pages from Google search results
                  in the last 28 days.
                </ContextualHelp>
              </CardTitle>
              <BarChart3 className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {dashboardMetrics ? (
                <>
                  <div className="text-2xl font-bold">
                    {formatNumber(dashboardMetrics.total_clicks_28d)}
                  </div>
                  <p className="text-xs text-muted-foreground">Across all sites</p>
                </>
              ) : !isActivated && firstSite ? (
                <p className="text-xs text-primary mt-1">
                  <Link href={route('onboarding.index', firstSite.id)} className="hover:underline">
                    Connect GSC to see clicks →
                  </Link>
                </p>
              ) : (
                <div className="text-2xl font-bold text-muted-foreground">—</div>
              )}
            </CardContent>
          </Card>

          {/* Pending Recommendations */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium flex items-center gap-1.5">
                Pending Recommendations
                <ContextualHelp>
                  SEO improvements waiting for your review. Each recommendation suggests a specific
                  action to improve traffic.
                </ContextualHelp>
              </CardTitle>
              <Sparkles className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {dashboardMetrics ? (
                <>
                  <div className="text-2xl font-bold">
                    {dashboardMetrics.pending_recommendations > 0 && firstSite ? (
                      <Link
                        href={
                          route('recommendations.index', firstSite.id) + '?lifecycle_status=pending'
                        }
                        className="hover:text-primary transition-colors"
                      >
                        {dashboardMetrics.pending_recommendations}
                      </Link>
                    ) : !isActivated && firstSite ? (
                      <span className="text-sm font-medium text-primary">
                        <Link
                          href={route('analyze.index', firstSite.id)}
                          className="hover:underline"
                        >
                          Run analysis to get recommendations →
                        </Link>
                      </span>
                    ) : (
                      dashboardMetrics.pending_recommendations
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">Awaiting review</p>
                </>
              ) : (
                <div className="text-2xl font-bold text-muted-foreground">—</div>
              )}
            </CardContent>
          </Card>

          {/* Drafts Generated */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Drafts Generated</CardTitle>
              <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {dashboardMetrics ? (
                <>
                  <div className="text-2xl font-bold">
                    {dashboardMetrics.drafts_generated_month > 0 || isActivated ? (
                      dashboardMetrics.drafts_generated_month
                    ) : firstSite ? (
                      <span className="text-sm font-medium text-primary">
                        <Link href={route('settings.ai')} className="hover:underline">
                          Add OpenAI key to generate drafts →
                        </Link>
                      </span>
                    ) : (
                      dashboardMetrics.drafts_generated_month
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">This month</p>
                </>
              ) : (
                <div className="text-2xl font-bold text-muted-foreground">—</div>
              )}
            </CardContent>
          </Card>

          {/* Last Analyzed */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Last Analyzed</CardTitle>
              <Clock className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              {dashboardMetrics?.latest_analysis_at ? (
                <>
                  <div className="text-2xl font-bold">
                    {formatRelativeTime(dashboardMetrics.latest_analysis_at)}
                  </div>
                  <p className="text-xs text-muted-foreground">Most recent analysis</p>
                </>
              ) : (
                <>
                  <div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
                    <BarChart3 className="h-3.5 w-3.5" />
                    No analysis yet
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    {firstSite ? (
                      <>
                        <Link
                          href={route('analyze.index', firstSite.id)}
                          className="text-primary hover:underline"
                        >
                          Run your first analysis →
                        </Link>
                        <span className="block mt-0.5 text-muted-foreground/80">
                          Compares two time periods to find traffic changes.
                        </span>
                      </>
                    ) : (
                      'Add a site to get started'
                    )}
                  </p>
                </>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Site Health */}
        {(healthScore || (serviceHealth && serviceHealth.length > 0)) && (
          <section aria-labelledby="site-health-heading" className="mb-2">
            <h2
              id="site-health-heading"
              className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3"
            >
              Site Health
            </h2>

            {/* Health Score */}
            {healthScore && (
              <div className="mb-8">
                <HealthScoreCard
                  score={healthScore.score}
                  previousScore={healthScore.previous_score}
                  calculatedAt={healthScore.calculated_at}
                  siteId={firstSite?.id}
                />
              </div>
            )}

            {/* Health Score Breakdown */}
            {healthScore && healthScore.score !== null && (
              <div className="mb-8">
                <HealthScoreBreakdown
                  trafficTrendScore={healthScore.components.traffic_trend}
                  contentQualityScore={healthScore.components.content_quality}
                  recommendationCompletionScore={healthScore.components.recommendation_completion}
                  roiPerformanceScore={healthScore.components.roi_performance}
                  connectionHealthScore={healthScore.components.connection_health}
                />
              </div>
            )}

            {/* Connection Health Panel */}
            {serviceHealth && serviceHealth.length > 0 && (
              <div className="mb-8">
                <ConnectionHealthPanel services={serviceHealth} />
              </div>
            )}
          </section>
        )}

        {/* Content Pipeline */}
        <section aria-labelledby="content-pipeline-heading" className="mb-2">
          <h2
            id="content-pipeline-heading"
            className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3"
          >
            Content Pipeline
          </h2>

          {/* Recommendation Funnel */}
          <div className="mb-8">
            <RecommendationFunnel metrics={funnelMetrics} siteId={firstSite?.id} />
          </div>

          {/* Content Intelligence */}
          {firstSite && intelligenceCards.length > 0 && (
            <div className="mb-8">
              <div className="mb-3">
                <p className="text-sm text-muted-foreground">
                  Advanced SEO insights for {firstSite.name}
                </p>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                {intelligenceCards.map(
                  ({ key, label, description, count, icon: Icon, href, emptyLabel }) => (
                    <Card
                      key={key}
                      className="transition-all duration-200 hover:shadow-md hover:shadow-primary/10 hover:border-primary/30"
                    >
                      <CardContent className="pt-5">
                        {count > 0 ? (
                          <div className="flex items-start justify-between gap-3">
                            <div className="flex items-start gap-3">
                              <div className="rounded-md bg-primary/10 p-2 shrink-0">
                                <Icon className="h-4 w-4 text-primary" aria-hidden="true" />
                              </div>
                              <div>
                                <p className="text-2xl font-bold leading-none">{count}</p>
                                <p className="text-sm font-medium mt-1">{label}</p>
                                <p className="text-xs text-muted-foreground mt-0.5">
                                  {description}
                                </p>
                              </div>
                            </div>
                            <Link
                              href={href}
                              className="text-xs text-primary hover:underline shrink-0 mt-1 focus-visible:ring-2 focus-visible:ring-ring rounded"
                              aria-label={`View ${label} details`}
                            >
                              View Details →
                            </Link>
                          </div>
                        ) : (
                          <div className="flex items-start gap-3">
                            <div className="rounded-md bg-muted p-2 shrink-0">
                              <Icon className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
                            </div>
                            <div>
                              <p className="text-sm font-medium text-muted-foreground">{label}</p>
                              <p className="text-xs text-muted-foreground mt-0.5">
                                Run analysis to discover {emptyLabel}
                              </p>
                              <Link
                                href={route('analyze.index', firstSite.id)}
                                className="text-xs text-primary hover:underline mt-1.5 inline-block focus-visible:ring-2 focus-visible:ring-ring rounded"
                              >
                                Analyze Now →
                              </Link>
                            </div>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  ),
                )}
              </div>
            </div>
          )}
        </section>

        {/* Your Activity */}
        {activity && (
          <section aria-labelledby="activity-heading" className="mb-8">
            <h2
              id="activity-heading"
              className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3"
            >
              Your Activity
            </h2>
            <div className="grid gap-4 md:grid-cols-4">
              <Card>
                <CardContent className="pt-5">
                  <div className="flex items-start justify-between">
                    <div>
                      <p className="text-2xl font-bold">{activity.analyses_this_week}</p>
                      <p className="text-sm text-muted-foreground">Analyses this week</p>
                    </div>
                    <div className="rounded-md bg-primary/10 p-2 shrink-0">
                      <BarChart3 className="h-4 w-4 text-primary" aria-hidden="true" />
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-5">
                  <div className="flex items-start justify-between">
                    <div>
                      <p className="text-2xl font-bold">{activity.recommendations_pending}</p>
                      <p className="text-sm text-muted-foreground">Pending review</p>
                    </div>
                    <div className="rounded-md bg-amber-500/10 p-2 shrink-0">
                      <Sparkles className="h-4 w-4 text-amber-500" aria-hidden="true" />
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-5">
                  <div className="flex items-start justify-between">
                    <div>
                      <p className="text-2xl font-bold">{activity.recommendations_applied}</p>
                      <p className="text-sm text-muted-foreground">Applied</p>
                    </div>
                    <div className="rounded-md bg-emerald-500/10 p-2 shrink-0">
                      <CheckCircle2 className="h-4 w-4 text-emerald-500" aria-hidden="true" />
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-5">
                  <div className="flex items-start justify-between">
                    <div>
                      <p className="text-2xl font-bold">
                        {activity.recommendations_total > 0
                          ? `${Math.round((activity.recommendations_applied / activity.recommendations_total) * 100)}%`
                          : '—'}
                      </p>
                      <p className="text-sm text-muted-foreground">Completion rate</p>
                    </div>
                    <div className="rounded-md bg-accent p-2 shrink-0">
                      <Target className="h-4 w-4 text-accent-foreground" aria-hidden="true" />
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </section>
        )}

        {/* Quick Actions */}
        <section aria-labelledby="quick-actions-heading" className="mb-2">
          <h2
            id="quick-actions-heading"
            className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3"
          >
            Quick Actions
          </h2>

          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
            {/* Top Declining Pages */}
            <Card className="col-span-7 md:col-span-1 lg:col-span-4">
              <CardHeader>
                <CardTitle>Top Declining Pages</CardTitle>
                <CardDescription>
                  Pages with the largest traffic drops in your latest analysis
                </CardDescription>
              </CardHeader>
              <CardContent>
                {topDeclining.length > 0 ? (
                  <div className="space-y-2">
                    {topDeclining.map((page) => (
                      <div
                        key={page.id}
                        className="flex items-center justify-between text-sm py-1 border-b border-border last:border-0"
                      >
                        <span
                          className="text-muted-foreground truncate max-w-[60%]"
                          title={page.page_url}
                        >
                          {truncateUrl(page.page_url)}
                        </span>
                        <span className="text-red-600 dark:text-red-400 font-medium shrink-0">
                          {page.delta_percent >= 0 ? '+' : ''}
                          {page.delta_percent.toFixed(1)}%
                        </span>
                      </div>
                    ))}
                    {firstSite && (
                      <Button variant="outline" size="sm" className="mt-3 w-full" asChild>
                        <Link href={route('analyze.index', firstSite.id)}>View Full Analysis</Link>
                      </Button>
                    )}
                  </div>
                ) : (
                  <EmptyState
                    icon={BarChart3}
                    title="No decline data yet"
                    description="Once you run an analysis, this shows your highest-priority pages — the ones losing the most traffic."
                    size="sm"
                    animated={false}
                    action={
                      firstSite ? (
                        <Button size="sm" variant="outline" asChild>
                          <Link href={route('analyze.index', firstSite.id)}>Run Analysis</Link>
                        </Button>
                      ) : undefined
                    }
                  />
                )}
              </CardContent>
            </Card>

            {/* Quick Actions */}
            <Card className="col-span-7 md:col-span-1 lg:col-span-3">
              <CardHeader>
                <CardTitle>Quick Actions</CardTitle>
                <CardDescription>
                  {sites && sites.length > 1
                    ? `Actions for ${firstSite?.name ?? 'your site'}`
                    : 'Common tasks to improve your SEO'}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {firstSite ? (
                  <div className="space-y-3">
                    {sites && sites.length > 1 && (
                      <p className="text-xs text-muted-foreground mb-1">
                        Use the{' '}
                        <Link href="/portfolio" className="text-primary hover:underline">
                          Portfolio Dashboard
                        </Link>{' '}
                        to compare across sites, or select a site from the switcher above.
                      </p>
                    )}
                    <Button variant="outline" size="sm" className="w-full justify-start" asChild>
                      <Link href={route('analyze.index', firstSite.id)}>
                        <BarChart3 className="mr-2 h-4 w-4" aria-hidden="true" />
                        Run New Analysis
                      </Link>
                    </Button>
                    <Button variant="outline" size="sm" className="w-full justify-start" asChild>
                      <Link
                        href={
                          route('recommendations.index', firstSite.id) + '?lifecycle_status=pending'
                        }
                      >
                        <Sparkles className="mr-2 h-4 w-4" aria-hidden="true" />
                        Review Pending ({dashboardMetrics?.pending_recommendations ?? 0})
                      </Link>
                    </Button>
                    <Button variant="outline" size="sm" className="w-full justify-start" asChild>
                      <Link href={route('content-inventory.index', firstSite.id)}>
                        <FileText className="mr-2 h-4 w-4" aria-hidden="true" />
                        Content Inventory
                      </Link>
                    </Button>
                    {!has_serp_key && (
                      <Button variant="outline" size="sm" className="w-full justify-start" asChild>
                        <Link href={route('settings.serp')}>
                          <Key className="mr-2 h-4 w-4" aria-hidden="true" />
                          Set Up SERP Analysis
                        </Link>
                      </Button>
                    )}
                  </div>
                ) : (
                  <EmptyState
                    icon={Rocket}
                    title="No site yet"
                    description="Add your first site to see quick actions."
                    size="sm"
                    animated={false}
                    action={
                      <Button size="sm" variant="outline" asChild>
                        <Link href={route('sites.create')}>Add Site</Link>
                      </Button>
                    }
                  />
                )}
              </CardContent>
            </Card>
          </div>
        </section>
      </div>
    </DashboardLayout>
  );
}
