"use client";

import { useEffect, useState, useCallback } from "react";
import { CheckCircle, Circle, Loader2, AlertTriangle, ArrowLeft, RefreshCw, ChevronDown, ChevronUp, Info } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useViewMode } from "@/components/audit/dashboard/useViewMode";
import type { SeoSection } from "@/lib/audit/types";
import { AiSearchPerformancePanel } from "@/components/audit/ai-search-performance-panel";
import {
  AuditHero, ScoreBreakdown, ExecutiveSummaryCard, KeyFindingsSection,
  PriorityActionsSection, QuickWinsGrid, MethodologySection, ScoreProjection, AuditTOC,
  CompetitiveLandscapeSection, BacklinkProfileSection, AIConversionGapChart,
  OrganicSearchSection, ImplementationAppendixSection, LockedFirstPartyTeaser,
  SignalCenterSection, BilingualContentSection, CompetitorDeepDiveSection,
  ThirdVsFirstPartyComparison, SchemaOpportunityForecastSection,
  StrategicRoadmapSection, IndustryBenchmarkSection, PageStrategicPassSection,
  AiEnginePersonalitySection, AiSourceAttributionComparisonSection, BehavioralActionBridgeSection, EeatAuditSection, AiSnippetEligibilitySection,
  MultiTouchAiPathSection, ExecutiveBriefSection, ViewModeToggle, RevenueAttributionSection,
  PredictiveConversionScoringSection,
  ConversionHeatMapSection,
  AiSearchVerificationSection,
  LostOpportunityCalculatorSection,
  LiveVisualAnnotationsSection,
  CompetitorVisualComparisonSection,
  BrandAuthorityScoreSection,
  SnippetCaptureStrategySection,
  VoiceSearchEligibilitySection,
  MobileFirstAuditSection,
  PageSpeedInsightsDeepDiveSection,
} from "@/components/audit/dashboard";

// ─── Types ────────────────────────────────────────────────────────────────────

interface TierCompleted {
  tier: number;
  label: string;
  completedAt: string;
}

interface AuditStatus {
  status: string;
  auditMode: string;
  progressStep: number;
  progressLabel: string | null;
  progressDetail: string | null;
  siteTagDetected: boolean | null;
  elapsedSeconds: number;
}

interface AuditRecord {
  id: string;
  brandId?: string | null;
  status: "queued" | "running" | "completed" | "failed";
  requestedBrandName?: string;
  requestedWebsite?: string;
  currentTier: number;
  totalTiers: number;
  currentTierLabel?: string;
  tiersCompleted?: TierCompleted[];
  estimatedSecondsRemaining?: number;
  seoSection?: SeoSection;
  userFacingError?: string;
  errorReason?: string | null;
  errorDetail?: string | null;
  degradedMode?: boolean | null;
  createdAt: string;
  completedAt?: string;
  startedAt?: string;
}

// ─── Progress UI ──────────────────────────────────────────────────────────────

const STEP_LABELS = [
  "Initializing audit",
  "Checking Site Tag",
  "Crawling site",
  "Loading first-party data",
  "Running analysis",
  "Finalizing recommendations",
  "Complete",
];

function StepIcon({ s }: { s: "done" | "active" | "pending" }) {
  if (s === "done") return <CheckCircle className="w-4 h-4 text-green-500 shrink-0" />;
  if (s === "active") return <Loader2 className="w-4 h-4 text-blue-500 shrink-0 animate-spin" />;
  return <Circle className="w-4 h-4 text-slate-300 shrink-0" />;
}

function fmtElapsed(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return s > 0 ? `${m}m ${s}s` : `${m}m`;
}

const MODE_CHIP: Record<string, string> = {
  auto: "Auto",
  "first-party": "First-party",
  "third-party": "Third-party",
};

function ProgressCard({ audit }: { audit: AuditRecord }) {
  const auditId = audit.id;
  const [liveStatus, setLiveStatus] = useState<AuditStatus | null>(null);

  useEffect(() => {
    let stopped = false;

    async function poll() {
      try {
        const res = await fetch(`/api/admin/audits/${auditId}/status`);
        if (!res.ok || stopped) return;
        const data = (await res.json()) as AuditStatus;
        setLiveStatus(data);
        if (data.status === "completed" || data.status === "failed") stopped = true;
      } catch {
        // silently retry
      }
    }

    poll();
    const interval = setInterval(poll, 2000);
    return () => { stopped = true; clearInterval(interval); };
  }, [auditId]);

  const step = liveStatus?.progressStep ?? 0;
  const label = liveStatus?.progressLabel ?? null;
  const detail = liveStatus?.progressDetail ?? null;
  const elapsed = liveStatus?.elapsedSeconds ?? 0;
  const mode = liveStatus?.auditMode ?? "auto";
  const tagDetected = liveStatus?.siteTagDetected;

  return (
    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm max-w-lg mx-auto p-8">
      <div className="text-center mb-8">
        <div className="inline-flex items-center justify-center w-12 h-12 bg-blue-50 rounded-full mb-3">
          <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
        </div>
        <h2 className="text-lg font-semibold text-slate-900">meSEO Audit in Progress</h2>
        <p className="text-sm text-slate-500 mt-1">
          {audit.requestedBrandName ?? audit.requestedWebsite ?? "Your site"} is being analyzed
        </p>

        <div className="flex items-center justify-center gap-2 mt-3 flex-wrap">
          <span className="text-[11px] font-medium text-slate-500 bg-slate-100 px-2 py-0.5 rounded-full">
            {MODE_CHIP[mode] ?? "Auto"}
          </span>
          {tagDetected === true && (
            <span className="text-[11px] font-medium text-emerald-700 bg-emerald-50 border border-emerald-200 px-2 py-0.5 rounded-full">
              Site Tag detected
            </span>
          )}
          {tagDetected === false && (
            <span className="text-[11px] font-medium text-slate-500 bg-slate-50 border border-slate-200 px-2 py-0.5 rounded-full">
              No Site Tag
            </span>
          )}
        </div>
      </div>

      <div className="space-y-2 mb-6">
        {STEP_LABELS.map((stepLabel, i) => {
          const stepNum = i + 1;
          const isDone = step > stepNum;
          const isActive = step === stepNum;
          const s = isDone ? "done" : isActive ? "active" : "pending";

          return (
            <div key={stepNum}>
              <div
                className={`flex items-center gap-3 px-3 py-2 rounded-lg transition-colors ${
                  isActive ? "bg-blue-50" : isDone ? "bg-green-50/50" : ""
                }`}
              >
                <StepIcon s={s} />
                <span
                  className={`text-sm flex-1 ${
                    isDone
                      ? "text-slate-400 line-through"
                      : isActive
                      ? "text-blue-800 font-medium"
                      : "text-slate-400"
                  }`}
                >
                  {isActive && label ? label : stepLabel}
                </span>
              </div>
              {isActive && detail && (
                <p className="text-[11px] text-slate-400 font-mono pl-10 pr-3 -mt-0.5 truncate" title={detail}>
                  {detail}
                </p>
              )}
            </div>
          );
        })}
      </div>

      <div className="text-center text-xs text-slate-400">
        Step {Math.max(step, 1)} of {STEP_LABELS.length}
        {elapsed > 0 && <> &nbsp;·&nbsp; {fmtElapsed(elapsed)} elapsed</>}
      </div>
    </div>
  );
}

// ─── Inline retry link ────────────────────────────────────────────────────────

function RetryLink({ auditId }: { auditId: string }) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);
  async function retry() {
    setBusy(true);
    try {
      const res = await fetch(`/api/admin/audits/${auditId}/retry`, { method: "POST" });
      if (!res.ok) { setBusy(false); return; }
      const data = (await res.json()) as { newAuditId?: string };
      if (data.newAuditId) router.push(`/admin/audits/${data.newAuditId}`);
    } catch { setBusy(false); }
  }
  return (
    <button onClick={retry} disabled={busy} className="underline font-medium hover:no-underline disabled:opacity-60">
      {busy ? "Starting…" : "Retry full audit →"}
    </button>
  );
}

// ─── Error messages ───────────────────────────────────────────────────────────

const CRAWL_ERROR_MESSAGES: Record<string, { title: string; body: string }> = {
  crawl_blocked: {
    title: "Site is blocking automated access",
    body: "Cloudflare or similar bot protection is preventing the crawl. To audit this site install the meSEO Site Tag — 1st-party audits bypass external crawling entirely.",
  },
  crawl_timeout: {
    title: "Site took too long to respond",
    body: "The site didn't finish loading within the crawl budget. Try again in a few minutes or check whether the site is currently experiencing performance issues.",
  },
  site_unreachable: {
    title: "Could not reach the site",
    body: "DNS lookup or connection failed. Verify the URL is correct and the site is online.",
  },
  js_required: {
    title: "Site requires JavaScript to render",
    body: "External crawling cannot see the full page content. Install the meSEO Site Tag for a complete 1st-party audit that doesn't depend on a headless crawl.",
  },
  redirect_loop: {
    title: "Redirect chain detected",
    body: "The site has a redirect loop or chain that prevented crawling. Check for SSL ↔ non-SSL or www ↔ non-www redirect conflicts.",
  },
  firecrawl_service_error: {
    title: "Crawler service temporarily unavailable",
    body: "Our external crawler returned an error. This is usually transient — retry in a few minutes.",
  },
  synthesizer_timeout: {
    title: "Analysis engine timed out",
    body: "Our analysis engine took too long to respond. This is usually transient — retry the audit.",
  },
  synthesizer_error: {
    title: "Analysis engine error",
    body: "Our analysis engine encountered an error. Click Retry to try again.",
  },
};

// ─── Failed view ──────────────────────────────────────────────────────────────

function FailedView({ audit }: { audit: AuditRecord }) {
  const router = useRouter();
  const [detailOpen, setDetailOpen] = useState(false);
  const [retrying, setRetrying] = useState(false);

  const specific = audit.errorReason ? CRAWL_ERROR_MESSAGES[audit.errorReason] : null;

  async function handleRetry() {
    setRetrying(true);
    try {
      const res = await fetch(`/api/admin/audits/${audit.id}/retry`, { method: "POST" });
      if (!res.ok) { setRetrying(false); return; }
      const data = (await res.json()) as { newAuditId?: string };
      if (data.newAuditId) router.push(`/admin/audits/${data.newAuditId}`);
    } catch {
      setRetrying(false);
    }
  }

  return (
    <div className="max-w-lg mx-auto bg-white rounded-2xl border border-red-200 p-8">
      <div className="flex items-start gap-3 mb-5">
        <AlertTriangle className="w-6 h-6 text-red-400 shrink-0 mt-0.5" />
        <div>
          <h2 className="text-base font-semibold text-slate-900">
            {specific?.title ?? "Audit Could Not Complete"}
          </h2>
          <p className="text-sm text-slate-500 mt-1.5 leading-relaxed">
            {specific?.body ?? (audit.userFacingError ?? "We encountered an issue completing this audit.")}
          </p>
        </div>
      </div>

      {audit.errorDetail && (
        <div className="mb-5">
          <button
            onClick={() => setDetailOpen((o) => !o)}
            className="flex items-center gap-1.5 text-xs text-slate-400 hover:text-slate-600 transition-colors"
          >
            {detailOpen ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
            {detailOpen ? "Hide" : "Show"} raw error
          </button>
          {detailOpen && (
            <pre className="mt-2 text-[11px] text-slate-500 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 overflow-x-auto whitespace-pre-wrap break-all">
              {audit.errorDetail}
            </pre>
          )}
        </div>
      )}

      {audit.errorReason && (
        <div className="flex items-center gap-1.5 text-[11px] text-slate-400 mb-5">
          <Info className="w-3.5 h-3.5 shrink-0" />
          Error code: <span className="font-mono">{audit.errorReason}</span>
        </div>
      )}

      <div className="flex items-center gap-3">
        <button
          onClick={handleRetry}
          disabled={retrying}
          className="inline-flex items-center gap-2 px-4 py-2 bg-slate-900 text-white text-sm font-medium rounded-lg hover:bg-slate-800 disabled:opacity-60 transition-colors"
        >
          {retrying ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
          Retry Audit
        </button>
        <Link
          href="/admin/audits"
          className="text-sm text-slate-400 hover:text-slate-700 transition-colors"
        >
          Back to audits
        </Link>
      </div>
    </div>
  );
}

// ─── Report view ──────────────────────────────────────────────────────────────

function ReportView({ audit }: { audit: AuditRecord }) {
  const seo = audit.seoSection;
  if (!seo) return null;

  const isFirstPartyAudit = !seo.lockedFirstPartyTeaser;
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { viewMode, setViewMode } = useViewMode(
    isFirstPartyAudit ? "1st" : "3rd",
    !!seo.executiveBrief,
  );

  const auditDate = audit.completedAt
    ? new Date(audit.completedAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })
    : "—";

  const displayTitle = seo.displayName ?? seo.brandEcho?.brandName ?? audit.requestedBrandName ?? audit.requestedWebsite ?? "Audit";
  const hasAiPerformance = !!seo.aiSearchPerformance;
  const hasMethodology = !!(seo.methodology || seo.industryFramework);
  const hasCompetitive = !!(seo.competitiveLandscape);
  const hasBacklinks = !!(seo.backlinkProfile);
  const hasAiConversion = !!(seo.aiConversionAttribution);
  const hasOrganicSearch = !!(seo.organicSearchSummary);
  const hasSignalCenter = !!(seo.signalCenter);
  const hasBilingual = !!(seo.bilingualAudit);
  const hasAiAttribComparison = !!(seo.aiSourceAttributionComparison?.hasFirstPartyData);
  const hasBehavioralBridge = !!(seo.behavioralActionBridge);
  const hasSnippetEligibility = !!(seo.aiSnippetEligibility);
  const hasMultiTouchPath = !!(seo.multiTouchAiPath);
  const hasRevenueAttribution = !!(seo.revenueAttribution?.hasRevenueTracking);
  const hasPredictiveScoring = !!(seo.predictiveConversionScoring);
  const hasConversionHeatMap = !!(seo.conversionHeatMap);
  const hasAiSearchVerification = !!(seo.aiSearchVerification);
  const hasLostOpportunity = !!(seo.lostOpportunityCalculation?.hasCalculation);
  const hasLiveVisualAnnotations = !!(seo.liveVisualAnnotations?.hasAnnotations);
  const hasCompetitorVisualComparison = !!(seo.competitorVisualComparison?.hasComparison);
  const hasBrandAuthorityScore = !!(seo.brandAuthorityScore?.hasScore);
  const hasSnippetCaptureStrategy = !!(seo.snippetCaptureStrategy?.hasStrategy && (seo.snippetCaptureStrategy?.totalReformulationsGenerated ?? 0) > 0);
  const hasVoiceSearch = !!(seo.voiceSearchEligibility?.hasData);
  const hasMobileFirstAudit = !!(seo.mobileFirstAudit?.hasAudit);
  const hasPageSpeedInsights = !!(seo.pageSpeedInsights?.hasInsights);
  const hasCompetitorDeepDive = !!(seo.competitorAnalysis);
  const hasSchemaForecast = !!(seo.schemaOpportunityForecast);
  const hasStrategicRoadmap = !!(seo.strategicRoadmap?.phases?.length);
  const hasIndustryBenchmark = !!(seo.industryBenchmarkComparison);
  const hasPageStrategicPass = !!(seo.pageStrategicPass?.pages?.length);
  const hasPrioritizedFindings = !!(seo.prioritizedFindings?.length);
  const hasTeaser = !!(seo.lockedFirstPartyTeaser);

  const tocItems = [
    { id: "audit-score", label: "Overview" },
    ...(hasAiPerformance ? [{ id: "audit-ai-performance", label: "AI Performance" }] : []),
    ...(hasAiConversion ? [{ id: "audit-ai-conversion", label: "AI Conversion" }] : []),
    ...(hasOrganicSearch ? [{ id: "audit-organic-search", label: "Organic Search" }] : []),
    ...(hasCompetitive ? [{ id: "audit-competitive", label: "Competitive" }] : []),
    ...(hasCompetitorDeepDive ? [{ id: "audit-competitor-deep-dive", label: "Competitive Intelligence" }] : []),
    ...(hasBacklinks ? [{ id: "audit-backlinks", label: "Backlinks" }] : []),
    { id: "audit-ai-engines", label: "AI Engine Profiles" },
    ...(hasSnippetEligibility ? [{ id: "audit-snippet-eligibility", label: "Snippet Eligibility" }] : []),
    ...(hasSnippetCaptureStrategy ? [{ id: "audit-snippet-capture", label: "Snippet Capture Strategy" }] : []),
    ...(hasVoiceSearch ? [{ id: "audit-voice-search-eligibility", label: "Voice Search Eligibility" }] : []),
    { id: "audit-eeat", label: "E-E-A-T Audit" },
    ...(hasBrandAuthorityScore ? [{ id: "audit-brand-authority", label: "Brand Authority" }] : []),
    ...(hasMobileFirstAudit ? [{ id: "audit-mobile-first", label: "Mobile-First Audit" }] : []),
    ...(hasPageSpeedInsights ? [{ id: "audit-page-speed", label: "Page Speed Insights" }] : []),
    ...(hasIndustryBenchmark ? [{ id: "audit-industry-benchmark", label: "Industry Benchmark" }] : []),
    ...(hasSignalCenter ? [{ id: "audit-signal-center", label: "Signal Center" }] : []),
    ...(hasAiAttribComparison ? [{ id: "audit-ai-attribution-comparison", label: "Public vs First-Party" }] : []),
    ...(hasMultiTouchPath ? [{ id: "audit-multi-touch-paths", label: "Multi-Touch Paths" }] : []),
    ...(hasRevenueAttribution ? [{ id: "audit-revenue-attribution", label: "Revenue Attribution" }] : []),
    ...(hasPredictiveScoring ? [{ id: "audit-predictive-conversion-scoring", label: "Predictive Conversion Scoring" }] : []),
    ...(hasConversionHeatMap ? [{ id: "audit-conversion-heat-map", label: "Conversion Heat Map" }] : []),
    ...(hasLiveVisualAnnotations ? [{ id: "audit-visual-analysis", label: "Visual Analysis" }] : []),
    ...(hasAiSearchVerification ? [{ id: "audit-ai-search-verification", label: "AI Search Verification" }] : []),
    ...(hasCompetitorVisualComparison ? [{ id: "audit-competitor-visual-comparison", label: "Competitor Visual Comparison" }] : []),
    ...(hasLostOpportunity ? [{ id: "audit-opportunity-estimate", label: "Opportunity Estimate" }] : []),
    ...(hasBilingual ? [{ id: "audit-bilingual", label: "Multi-Language" }] : []),
    { id: "audit-score-breakdown", label: "Score Breakdown" },
    seo.executiveBrief
      ? { id: "audit-executive-brief", label: "Executive Brief" }
      : { id: "audit-executive-summary", label: "Executive Summary" },
    { id: "audit-key-findings", label: "Key Findings" },
    { id: "audit-priority-actions", label: "Priority Actions" },
    { id: "audit-quick-wins", label: "Quick Wins" },
    ...(hasBehavioralBridge ? [{ id: "audit-behavioral-bridge", label: "Behavioral Action Bridge" }] : []),
    ...(hasPrioritizedFindings ? [{ id: "audit-implementation", label: "Implementation" }] : []),
    ...(hasMethodology ? [{ id: "audit-methodology", label: "Methodology" }] : []),
    ...(hasPageStrategicPass ? [{ id: "audit-page-review", label: "Page-by-Page Review" }] : []),
    ...(hasSchemaForecast ? [{ id: "audit-schema-opportunities", label: "Schema Opportunities" }] : []),
    ...(hasStrategicRoadmap ? [{ id: "audit-roadmap", label: "90-Day Roadmap" }] : []),
    { id: "audit-projection", label: "Score Projection" },
    ...(hasTeaser ? [{ id: "audit-upgrade", label: "Upgrade" }] : []),
  ];

  return (
    <div className="max-w-[1200px] mx-auto">
      <div className="lg:grid lg:gap-8 lg:items-start" style={{ gridTemplateColumns: "190px 1fr" }}>
        {/* Sticky TOC */}
        <aside className="hidden lg:block">
          <div className="sticky top-6">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2 px-3">
              Sections
            </p>
            <AuditTOC items={tocItems} />
          </div>
        </aside>

        {/* Main content */}
        <div className="min-w-0 space-y-6">
          <AuditHero
            brandName={displayTitle}
            website={audit.requestedWebsite}
            auditDate={auditDate}
            score={seo.healthScore}
            pdfUrl={`/api/admin/audits/${audit.id}/pdf`}
            execPdfUrl={seo.executiveBrief ? `/api/admin/audits/${audit.id}/pdf?mode=executive` : undefined}
            siteTagContext={seo.siteTagContext}
            services={seo.brandEcho?.services}
            locations={seo.brandEcho?.locations}
            aiTrend={seo.aiSearchPerformance?.trendVsTrailing90d}
            viewMode={viewMode}
          />

          <ViewModeToggle
            viewMode={viewMode}
            onModeChange={setViewMode}
            hasExecutiveBrief={!!seo.executiveBrief}
            fullSectionCount={tocItems.length}
          />

          {/* ── EXECUTIVE VIEW ── */}
          {viewMode === "executive" && (
            <>
              <ScoreBreakdown
                dimensionScores={seo.dimensionScores}
                scoringBreakdown={seo.scoringBreakdown}
              />
              {seo.executiveBrief
                ? <ExecutiveBriefSection executiveBrief={seo.executiveBrief} />
                : <ExecutiveSummaryCard narrative={seo.narrative} summaryThemes={seo.summaryThemes} industryFramework={seo.industryFramework} />
              }
              {!isFirstPartyAudit && <ThirdVsFirstPartyComparison isFirstParty={false} />}
              {!isFirstPartyAudit && seo.lockedFirstPartyTeaser && (
                <LockedFirstPartyTeaser teaser={seo.lockedFirstPartyTeaser} brandId={audit.brandId} />
              )}
              <div className="bg-slate-50 border border-slate-200 rounded-xl p-5 text-center">
                <p className="text-sm text-slate-600 mb-3">Viewing the strategic overview. The full audit includes all {tocItems.length} sections with implementation code, data tables, and complete analysis.</p>
                <button
                  onClick={() => setViewMode("full")}
                  className="inline-flex items-center gap-2 px-4 py-2 bg-slate-900 text-white text-sm font-medium rounded-lg hover:bg-slate-700 transition-colors"
                >
                  View the Comprehensive Audit ({tocItems.length} sections) →
                </button>
              </div>
            </>
          )}

          {/* ── FULL AUDIT VIEW ── */}
          {viewMode === "full" && seo.aiSearchPerformance && (
            <div id="audit-ai-performance" className="audit-hero-enter">
              <AiSearchPerformancePanel
                data={seo.aiSearchPerformance}
                brandId={audit.brandId}
                siteTagDaysActive={seo.siteTagContext?.daysActive}
              />
            </div>
          )}

          {viewMode === "full" && (
            <>
              {seo.aiConversionAttribution && (
                <div id="audit-ai-conversion">
                  <AIConversionGapChart aiConversionAttribution={seo.aiConversionAttribution} />
                </div>
              )}

              {seo.organicSearchSummary && (
                <div id="audit-organic-search">
                  <OrganicSearchSection organicSearchSummary={seo.organicSearchSummary} />
                </div>
              )}

              {seo.competitiveLandscape && (
                <div id="audit-competitive">
                  <CompetitiveLandscapeSection
                    competitiveLandscape={seo.competitiveLandscape}
                    publicAiVisibility={seo.publicAiVisibility}
                  />
                </div>
              )}

              {seo.competitorAnalysis && (
                <div id="audit-competitor-deep-dive">
                  <CompetitorDeepDiveSection competitorAnalysis={seo.competitorAnalysis} />
                </div>
              )}

              {seo.backlinkProfile && (
                <div id="audit-backlinks">
                  <BacklinkProfileSection backlinkProfile={seo.backlinkProfile} />
                </div>
              )}

              {hasSnippetEligibility && (
                <div id="audit-snippet-eligibility">
                  <AiSnippetEligibilitySection aiSnippetEligibility={seo.aiSnippetEligibility} />
                </div>
              )}

              {hasSnippetCaptureStrategy && (
                <div id="audit-snippet-capture">
                  <SnippetCaptureStrategySection snippetCaptureStrategy={seo.snippetCaptureStrategy} />
                </div>
              )}

              {hasVoiceSearch && (
                <div id="audit-voice-search-eligibility">
                  <VoiceSearchEligibilitySection voiceSearchEligibility={seo.voiceSearchEligibility} />
                </div>
              )}

              <EeatAuditSection eeatAudit={seo.eeatAudit} />

              {hasBrandAuthorityScore && (
                <div id="audit-brand-authority">
                  <BrandAuthorityScoreSection brandAuthorityScore={seo.brandAuthorityScore} />
                </div>
              )}

              {hasMobileFirstAudit && (
                <div id="audit-mobile-first">
                  <MobileFirstAuditSection mobileFirstAudit={seo.mobileFirstAudit} />
                </div>
              )}

              {hasPageSpeedInsights && (
                <div id="audit-page-speed">
                  <PageSpeedInsightsDeepDiveSection pageSpeedInsights={seo.pageSpeedInsights} />
                </div>
              )}

              <AiEnginePersonalitySection aiEnginePersonalityAnalysis={seo.aiEnginePersonalityAnalysis} />

              <IndustryBenchmarkSection industryBenchmarkComparison={seo.industryBenchmarkComparison} />

              {seo.signalCenter && (
                <div id="audit-signal-center">
                  <SignalCenterSection signalCenter={seo.signalCenter} />
                </div>
              )}

              {hasAiAttribComparison && (
                <div id="audit-ai-attribution-comparison">
                  <AiSourceAttributionComparisonSection aiSourceAttributionComparison={seo.aiSourceAttributionComparison} />
                </div>
              )}

              {hasMultiTouchPath && (
                <MultiTouchAiPathSection multiTouchAiPath={seo.multiTouchAiPath} />
              )}

              {hasRevenueAttribution && (
                <RevenueAttributionSection revenueAttribution={seo.revenueAttribution} />
              )}

              {hasPredictiveScoring && (
                <PredictiveConversionScoringSection predictiveConversionScoring={seo.predictiveConversionScoring} />
              )}

              {hasConversionHeatMap && (
                <ConversionHeatMapSection conversionHeatMap={seo.conversionHeatMap} />
              )}

              {hasLiveVisualAnnotations && (
                <LiveVisualAnnotationsSection liveVisualAnnotations={seo.liveVisualAnnotations} />
              )}

              {hasAiSearchVerification && (
                <div id="audit-ai-search-verification">
                  <AiSearchVerificationSection aiSearchVerification={seo.aiSearchVerification} />
                </div>
              )}

              {hasCompetitorVisualComparison && (
                <CompetitorVisualComparisonSection competitorVisualComparison={seo.competitorVisualComparison} />
              )}

              {seo.bilingualAudit && (
                <div id="audit-bilingual">
                  <BilingualContentSection bilingualAudit={seo.bilingualAudit} />
                </div>
              )}

              <ScoreBreakdown
                dimensionScores={seo.dimensionScores}
                scoringBreakdown={seo.scoringBreakdown}
              />

              {seo.executiveBrief
                ? <ExecutiveBriefSection executiveBrief={seo.executiveBrief} />
                : (
                  <ExecutiveSummaryCard
                    narrative={seo.narrative}
                    summaryThemes={seo.summaryThemes}
                    industryFramework={seo.industryFramework}
                  />
                )
              }

              <KeyFindingsSection
                keyFindings={seo.keyFindings}
                prioritizedFindings={seo.prioritizedFindings}
                additionalFindings={seo.additionalFindings}
              />

              <PriorityActionsSection actions={seo.priorityActions} />

              {hasBehavioralBridge && (
                <div id="audit-behavioral-bridge">
                  <BehavioralActionBridgeSection behavioralActionBridge={seo.behavioralActionBridge} />
                </div>
              )}

              {hasLostOpportunity && (
                <LostOpportunityCalculatorSection lostOpportunityCalculation={seo.lostOpportunityCalculation} />
              )}

              <QuickWinsGrid wins={seo.quickWins} />

              {seo.prioritizedFindings && seo.prioritizedFindings.length > 0 && (
                <div id="audit-implementation">
                  <ImplementationAppendixSection
                    prioritizedFindings={seo.prioritizedFindings}
                    priorityActions={seo.priorityActions}
                  />
                </div>
              )}

              {hasMethodology && (
                <MethodologySection
                  methodology={seo.methodology}
                  industryFramework={seo.industryFramework}
                />
              )}

              <PageStrategicPassSection pageStrategicPass={seo.pageStrategicPass} />

              <SchemaOpportunityForecastSection schemaOpportunityForecast={seo.schemaOpportunityForecast} />

              <StrategicRoadmapSection strategicRoadmap={seo.strategicRoadmap} />

              <ThirdVsFirstPartyComparison isFirstParty={isFirstPartyAudit} />

              <ScoreProjection
                score={seo.healthScore}
                actions={seo.priorityActions}
                auditType={seo.lockedFirstPartyTeaser ? "3rd" : "1st"}
              />

              {seo.lockedFirstPartyTeaser && (
                <div id="audit-upgrade">
                  <LockedFirstPartyTeaser
                    teaser={seo.lockedFirstPartyTeaser}
                    brandId={audit.brandId}
                  />
                </div>
              )}
            </>
          )}

          <div className="text-center text-xs text-slate-400 py-6 border-t border-slate-100">
            meSEO Audit Report — Confidential
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function AuditReportPage({ params }: { params: { id: string } }) {
  const { id } = params;
  const [audit, setAudit] = useState<AuditRecord | null>(null);
  const [notFound, setNotFound] = useState(false);

  const fetchAudit = useCallback(async () => {
    try {
      const res = await fetch(`/api/admin/audits/${id}`);
      if (res.status === 404) { setNotFound(true); return; }
      if (!res.ok) return;
      const data = (await res.json()) as { audit: AuditRecord };
      setAudit(data.audit);
    } catch {
      // silently retry
    }
  }, [id]);

  useEffect(() => { fetchAudit(); }, [fetchAudit]);

  useEffect(() => {
    if (!audit || audit.status !== "running") return;
    const interval = setInterval(fetchAudit, 2500);
    return () => clearInterval(interval);
  }, [audit, fetchAudit]);

  if (notFound) {
    return (
      <div className="max-w-lg mx-auto text-center py-20">
        <p className="text-slate-500">Audit not found.</p>
        <Link href="/admin/audits" className="text-sm text-blue-600 underline mt-2 inline-block">Back to audits</Link>
      </div>
    );
  }

  if (!audit) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <Link href="/admin/audits" className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800 transition-colors">
        <ArrowLeft className="w-3.5 h-3.5" /> Back to audits
      </Link>

      {(audit.status === "queued" || audit.status === "running") && <ProgressCard audit={audit} />}
      {audit.status === "completed" && (
        <>
          {audit.degradedMode && (
            <div className="flex items-start gap-3 bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 text-sm text-amber-800 max-w-4xl">
              <Info className="w-4 h-4 shrink-0 mt-0.5 text-amber-500" />
              <span>
                <strong>Partial coverage:</strong> External crawl was unavailable for this audit. Analysis is based on your Site Tag telemetry and external data sources. Technical SEO and content scores reflect limited data.{" "}
                <RetryLink auditId={audit.id} />
              </span>
            </div>
          )}
          <ReportView audit={audit} />
        </>
      )}
      {audit.status === "failed" && <FailedView audit={audit} />}
    </div>
  );
}
