"use client";

import { useEffect, useState, useCallback } from "react";
import { useViewMode } from "@/components/audit/dashboard/useViewMode";
import {
  Loader2, AlertTriangle, Lock, ArrowRight, CheckCircle, Circle, Download,
  Globe, FileCode2, Map, FileText, Link, Code2, Sparkles, Search, Eye, Target,
  Zap, CheckCircle2, Image as ImageIcon, Heading1,
} from "lucide-react";
import type { SeoSection } from "@/lib/audit/types";
import {
  AuditHero, ScoreBreakdown, ExecutiveSummaryCard, KeyFindingsSection,
  PriorityActionsSection, QuickWinsGrid, TechnicalHealthSection, ScoreProjection, AuditTOC,
  CompetitiveLandscapeSection, BacklinkProfileSection, ImplementationAppendixSection, EeatAuditSection, AiSnippetEligibilitySection,
  LockedFirstPartyTeaser, SignalCenterSection, BilingualContentSection,
  CompetitorDeepDiveSection, ThirdVsFirstPartyComparison, SchemaOpportunityForecastSection,
  StrategicRoadmapSection, IndustryBenchmarkSection, PageStrategicPassSection,
  AiEnginePersonalitySection, AiSourceAttributionComparisonSection, BehavioralActionBridgeSection,
  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 PublicAuditRecord {
  id: string;
  status: "queued" | "running" | "completed" | "failed";
  requestedWebsite?: string;
  currentTier: number;
  totalTiers: number;
  tiersCompleted?: TierCompleted[];
  estimatedSecondsRemaining?: number;
  seoSection?: SeoSection;
  userFacingError?: string;
  errorReason?: string;
  completedAt?: string;
  rawData?: {
    pagesScanned: number;
    summary: {
      hasSitemap: boolean;
      hasRobotsTxt: boolean;
      mobileFriendly: boolean | null;
      totalPages: number;
    };
    crawlSamples?: Array<{ url: string; issues: string[] }>;
  };
}

// ─── Constants ────────────────────────────────────────────────────────────────

const DEMO_URL = "https://meseoapp.com/book-demo";

const TIER_LABELS = [
  "Initializing audit",
  "Discovering site structure",
  "Analyzing technical SEO",
  "Evaluating content & metadata",
  "Identifying optimization gaps",
  "Generating insights",
  "Finalizing recommendations",
];

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

const ERROR_MESSAGES: Record<string, string> = {
  crawl_blocked: "This site is blocking automated access (likely bot protection). Check the URL is correct and the site is publicly accessible.",
  crawl_timeout: "The site took too long to respond. Please try again in a few minutes.",
  site_unreachable: "Could not reach the site. Verify the URL is correct and the site is online.",
  js_required: "This site requires JavaScript to render. Our public audit handles most sites, but this one may need direct access.",
  redirect_loop: "The site has a redirect chain that prevented crawling. Check for SSL or www redirect conflicts.",
  firecrawl_service_error: "Our crawler is temporarily unavailable. Please try again in a few minutes.",
  synthesizer_timeout: "Our analysis engine took too long to respond. This is usually transient — retry the audit.",
  synthesizer_error: "Our analysis engine encountered an error. Please try again.",
};

// ─── Live Work Feed data ──────────────────────────────────────────────────────

const WORK_ENTRIES = [
  { icon: "Globe", text: "Requesting site structure" },
  { icon: "FileCode2", text: "Checking robots.txt configuration" },
  { icon: "Map", text: "Analyzing XML sitemap" },
  { icon: "FileText", text: "Evaluating meta descriptions" },
  { icon: "Heading1", text: "Scanning H1 heading coverage" },
  { icon: "Link", text: "Detecting broken internal links" },
  { icon: "Image", text: "Auditing image alt text" },
  { icon: "Code2", text: "Detecting schema markup" },
  { icon: "Sparkles", text: "Querying ChatGPT for brand visibility" },
  { icon: "Sparkles", text: "Querying AI assistants for citation patterns" },
  { icon: "Search", text: "Querying search AI for source preferences" },
  { icon: "Eye", text: "Checking AI Overview presence" },
  { icon: "Target", text: "Mapping content gaps to query intent" },
  { icon: "Zap", text: "Synthesizing strategic recommendations" },
  { icon: "CheckCircle2", text: "Finalizing priority action plan" },
];

type WorkIconName = "Globe" | "FileCode2" | "Map" | "FileText" | "Heading1" | "Link" | "Image" | "Code2" | "Sparkles" | "Search" | "Eye" | "Target" | "Zap" | "CheckCircle2";

const WORK_ICON_MAP: Record<WorkIconName, React.ComponentType<{ className?: string }>> = {
  Globe,
  FileCode2,
  Map,
  FileText,
  Heading1,
  Link,
  Image: ImageIcon,
  Code2,
  Sparkles,
  Search,
  Eye,
  Target,
  Zap,
  CheckCircle2,
};

// ─── Tracking helper ──────────────────────────────────────────────────────────

function trackEvent(auditId: string, event: string): void {
  fetch("/api/public-audit/track", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ auditId, event }),
  }).catch(() => {/* non-fatal */});
}

// ─── Live Work Feed (loading left rail) ──────────────────────────────────────

function LiveWorkFeed() {
  const [windowStart, setWindowStart] = useState(0);
  const VISIBLE = 5;

  useEffect(() => {
    const timer = setInterval(() => {
      setWindowStart((prev) => (prev + 1) % WORK_ENTRIES.length);
    }, 3000);
    return () => clearInterval(timer);
  }, []);

  // Build visible slice (wrap around)
  const visible = Array.from({ length: VISIBLE }, (_, i) => {
    const idx = (windowStart + i) % WORK_ENTRIES.length;
    return WORK_ENTRIES[idx];
  });

  // Opacity: bottom entry (index 4) = 1.0, going up: 0.7, 0.5, 0.35, 0.2
  const opacities = [0.2, 0.35, 0.5, 0.7, 1.0];

  return (
    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-4">
      <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-4">
        Live Work Feed
      </p>
      <div className="space-y-2.5">
        {visible.map((entry, i) => {
          const IconComponent = WORK_ICON_MAP[entry.icon as WorkIconName];
          const isNewest = i === VISIBLE - 1;
          return (
            <div
              key={`${windowStart}-${i}`}
              className="flex items-center gap-2.5 transition-opacity duration-700"
              style={{ opacity: opacities[i] }}
            >
              <IconComponent
                className={`w-3.5 h-3.5 shrink-0 ${isNewest ? "text-indigo-500" : "text-slate-400"}`}
              />
              <span
                className={`text-xs ${isNewest ? "text-indigo-700 font-medium" : "text-slate-600"}`}
              >
                {entry.text}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Wait Cards (loading right rail) ─────────────────────────────────────────

const WAIT_CARDS = [
  {
    header: "What you'll see",
    type: "bullets" as const,
    bullets: [
      "Technical SEO score across 50+ factors",
      "AI visibility across 4 major AI engines",
      "Prioritized action plan ranked by impact",
      "Quick wins you can implement today",
    ],
  },
  {
    header: "Did you know?",
    type: "body" as const,
    body: "AI search traffic is growing 40% quarter over quarter for brands that optimize for it. This audit shows where your site stands.",
  },
  {
    header: "Real results",
    type: "body" as const,
    body: "Modern Heart and Vascular increased AI-attributed referrals by 1,084% in 30 days after installing the meSEO Site Tag.",
  },
  {
    header: "After your audit",
    type: "cta" as const,
    body: "Want continuous monitoring? meSEO tracks every AI engine, every citation, every conversion — in real time.",
    ctaLabel: "Book a demo →",
    ctaHref: DEMO_URL,
  },
];

function WaitCards() {
  const [cardIdx, setCardIdx] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCardIdx((prev) => (prev + 1) % WAIT_CARDS.length);
    }, 15000);
    return () => clearInterval(timer);
  }, []);

  const card = WAIT_CARDS[cardIdx];

  return (
    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-4 transition-opacity duration-300">
      <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
        {card.header}
      </p>
      {card.type === "bullets" && (
        <ul className="space-y-2">
          {card.bullets.map((b) => (
            <li key={b} className="flex items-start gap-2">
              <CheckCircle className="w-3.5 h-3.5 text-green-500 shrink-0 mt-0.5" />
              <span className="text-sm text-slate-700">{b}</span>
            </li>
          ))}
        </ul>
      )}
      {(card.type === "body" || card.type === "cta") && (
        <p className="text-sm text-slate-600 leading-relaxed">{card.body}</p>
      )}
      {card.type === "cta" && (
        <a
          href={card.ctaHref}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-4 inline-flex items-center gap-1 bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-semibold px-4 py-2 rounded-lg transition-colors"
        >
          {card.ctaLabel}
        </a>
      )}
    </div>
  );
}

// ─── Progress view ────────────────────────────────────────────────────────────

function TierIcon({ status }: { status: "done" | "active" | "pending" }) {
  if (status === "done") return <CheckCircle className="w-4 h-4 text-green-500 shrink-0" />;
  if (status === "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 ProgressView({ audit }: { audit: PublicAuditRecord }) {
  const done = new Set((audit.tiersCompleted ?? []).map((t) => t.tier));
  return (
    <div className="max-w-[1400px] mx-auto px-4 py-10">
      <div className="lg:grid lg:gap-8" style={{ gridTemplateColumns: "260px 1fr 260px" }}>

        {/* Left rail — live work feed */}
        <aside className="hidden lg:block">
          <div className="sticky top-6">
            <LiveWorkFeed />
          </div>
        </aside>

        {/* Center — original progress card */}
        <div className="max-w-lg mx-auto w-full px-0 lg:px-4 py-6 lg:py-0">
          <div className="bg-white rounded-2xl border border-slate-200 shadow-sm 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">Analyzing your site…</h2>
              <p className="text-sm text-slate-500 mt-1">{audit.requestedWebsite}</p>
            </div>
            <div className="space-y-3 mb-6">
              {TIER_LABELS.map((label, i) => {
                const num = i + 1;
                const isDone = done.has(num);
                const isActive = audit.currentTier === num && !isDone;
                const s = isDone ? "done" : isActive ? "active" : "pending";
                return (
                  <div
                    key={num}
                    className={`flex items-center gap-3 px-3 py-2 rounded-lg ${isActive ? "bg-blue-50" : isDone ? "bg-green-50/50" : ""}`}
                  >
                    <TierIcon status={s} />
                    <span className={`text-sm ${isDone ? "text-slate-400 line-through" : isActive ? "text-blue-800 font-medium" : "text-slate-400"}`}>
                      {label}
                    </span>
                  </div>
                );
              })}
            </div>
            <p className="text-center text-xs text-slate-400">
              This takes 2–4 minutes. This page polls automatically.
            </p>
          </div>
        </div>

        {/* Right rail — wait cards */}
        <aside className="hidden lg:block">
          <div className="sticky top-6">
            <WaitCards />
          </div>
        </aside>

      </div>
    </div>
  );
}


// ─── Locked AI performance panel ──────────────────────────────────────────────
// Real structure with real labels — values are locked, not blurred fake data.

const LOCKED_ENGINES = ["ChatGPT", "Perplexity", "Claude", "Gemini"];

function LockedAiPanel({ auditId }: { auditId: string }) {
  useEffect(() => {
    trackEvent(auditId, "locked_panel_viewed");
  }, [auditId]);

  return (
    <div className="rounded-2xl overflow-hidden shadow-xl bg-gradient-to-br from-slate-900 via-indigo-950 to-slate-900">
      {/* Header — mirrors the real panel */}
      <div className="flex items-center justify-between px-6 pt-6 pb-1">
        <div className="flex items-center gap-2.5">
          <span className="relative flex h-2 w-2 shrink-0">
            <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500/40" />
          </span>
          <span className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/70">
            AI Search Performance
          </span>
        </div>
        <span className="text-[10px] font-medium text-indigo-300/50 border border-indigo-400/20 px-2 py-0.5 rounded-full">
          Patent pending
        </span>
      </div>

      {/* Metrics grid */}
      <div className="grid sm:grid-cols-2 mt-4 border-t border-white/10">
        {/* Left: lock CTA where the hero number would be */}
        <div className="px-6 py-8 border-b sm:border-b-0 sm:border-r border-white/10 bg-white/[0.03] flex flex-col justify-between min-h-[260px] sm:min-h-[300px]">
          <div>
            <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/60 mb-4">
              AI referrals · last 30 days
            </p>
            <div className="flex items-center gap-3 mb-4">
              <Lock className="w-7 h-7 text-indigo-400/50 shrink-0" />
              <p className="text-sm text-indigo-100/70 leading-relaxed">
                Install the meSEO Site Tag to see your real AI referral volume, trend, and engine breakdown.
              </p>
            </div>
          </div>
          <a
            href={DEMO_URL}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 bg-indigo-500 hover:bg-indigo-400 text-white text-sm font-semibold px-5 py-2.5 rounded-lg transition-colors self-start"
          >
            Book a demo <ArrowRight className="w-4 h-4" />
          </a>
        </div>

        {/* Right: engine list with locked indicators */}
        <div className="px-6 py-6 bg-white/[0.02]">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/60 mb-4">
            By engine · 90 days
          </p>
          <div className="space-y-3.5">
            {LOCKED_ENGINES.map((engine) => (
              <div key={engine} className="flex items-center gap-3">
                <span className="text-sm text-indigo-100/30 w-28 shrink-0 font-medium">{engine}</span>
                <div className="flex-1 bg-white/10 rounded-full h-1.5" />
                <Lock className="w-3 h-3 text-indigo-300/25 shrink-0" />
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Pages table skeleton */}
      <div className="border-t border-white/10 px-6 py-5">
        <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/60 mb-4">
          Top landing pages · 30 days
        </p>
        <table className="w-full text-xs min-w-[280px]">
          <thead>
            <tr className="text-indigo-300/45">
              <th className="text-left font-medium pb-2.5 pr-6">Page</th>
              <th className="text-right font-medium pb-2.5 px-3">AI Visits</th>
              <th className="text-right font-medium pb-2.5 pl-3">Conversions</th>
            </tr>
          </thead>
          <tbody>
            {[0, 1, 2].map((i) => (
              <tr key={i} className={i < 2 ? "border-b border-white/5" : ""}>
                <td className="py-2.5 pr-6"><div className="h-2.5 bg-white/10 rounded w-36" /></td>
                <td className="py-2.5 px-3 text-right"><div className="h-2.5 bg-white/10 rounded w-8 ml-auto" /></td>
                <td className="py-2.5 pl-3 text-right"><div className="h-2.5 bg-white/10 rounded w-8 ml-auto" /></td>
              </tr>
            ))}
          </tbody>
        </table>
        <p className="text-[11px] text-indigo-300/35 mt-4 flex items-center gap-1.5">
          <Lock className="w-3 h-3" />
          Connect the meSEO Site Tag to unlock real landing page attribution
        </p>
      </div>
    </div>
  );
}

// ─── Locked behavioral strip ──────────────────────────────────────────────────
// Shows metric labels with lock placeholders — intentional paywall, not broken UI.

const BEHAVIORAL_METRIC_LABELS = ["Bounce Rate", "Avg Session", "Conversions", "Lost Value"];

function LockedBehavioralStrip() {
  return (
    <div className="mt-4 pt-4 border-t border-slate-100">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-x-4 gap-y-3">
        {BEHAVIORAL_METRIC_LABELS.map((label) => (
          <div key={label}>
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">{label}</p>
            <div className="flex items-center gap-1.5">
              <Lock className="w-3 h-3 text-slate-300 shrink-0" />
              <div className="h-4 w-12 bg-slate-100 rounded" />
            </div>
          </div>
        ))}
      </div>
      <p className="text-[11px] text-slate-400 mt-3">
        <a
          href={DEMO_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="text-blue-500 hover:underline font-medium"
        >
          Install Site Tag to unlock behavioral data →
        </a>
      </p>
    </div>
  );
}

// ─── Crawl Samples ────────────────────────────────────────────────────────────

function CrawlSamples({ samples }: { samples: Array<{ url: string; issues: string[] }> }) {
  const visible = samples.slice(0, 4);

  function urlPath(raw: string): string {
    try {
      return new URL(raw).pathname || "/";
    } catch {
      return raw;
    }
  }

  return (
    <div className="bg-slate-50 rounded-2xl border border-slate-200 p-5">
      <h3 className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-4">
        What we examined during this audit
      </h3>
      <div className="space-y-2">
        {visible.map((sample, i) => {
          const path = urlPath(sample.url);
          const issue = sample.issues[0] ?? "";
          const secondIssue = sample.issues[1] ?? "";
          const displayIssue = secondIssue ? `${issue} · ${secondIssue}` : issue;
          return (
            <div key={i} className="flex items-baseline gap-2 py-1.5 border-b border-slate-100 last:border-0">
              <span className="font-mono text-xs text-slate-600 shrink-0 min-w-0 truncate max-w-[200px] sm:max-w-xs">
                {path}
              </span>
              {displayIssue && (
                <>
                  <span className="text-slate-300 text-xs shrink-0">·</span>
                  <span className="text-xs text-slate-500 truncate">{displayIssue}</span>
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Inline conversion cards (mobile only) ───────────────────────────────────

function InlineConversionCardAi({ auditId }: { auditId: string }) {
  return (
    <div className="lg:hidden">
      <div className="rounded-2xl bg-gradient-to-br from-slate-900 via-indigo-950 to-slate-900 p-5">
        <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/70 mb-2">
          AI Search Attribution
        </p>
        <p className="text-sm text-indigo-100/80 leading-relaxed mb-4">
          Connect the meSEO Site Tag to see exactly how many visits you are getting from ChatGPT, Perplexity, Claude, and Gemini — and which pages convert.
        </p>
        <a
          href={DEMO_URL}
          target="_blank"
          rel="noopener noreferrer"
          onClick={() => trackEvent(auditId, "mobile_ai_cta_clicked")}
          className="inline-flex items-center gap-2 bg-indigo-500 hover:bg-indigo-400 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors"
        >
          Book a demo <ArrowRight className="w-4 h-4" />
        </a>
      </div>
    </div>
  );
}

const SITE_TAG_ITEMS = [
  "AI referral attribution by engine",
  "Behavioral signals per page",
  "Conversion tracking",
  "Lost revenue estimates",
  "Continuous monitoring",
];

function InlineConversionCardSiteTag() {
  return (
    <div className="lg:hidden">
      <div className="rounded-2xl border border-slate-200 bg-white p-5">
        <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
          With the meSEO Site Tag
        </p>
        <div className="space-y-2 mb-4">
          {SITE_TAG_ITEMS.map((item) => (
            <div key={item} className="flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-green-500 shrink-0" />
              <span className="text-sm text-slate-700">{item}</span>
            </div>
          ))}
        </div>
        <a
          href={DEMO_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="text-sm text-blue-600 font-medium hover:underline inline-flex items-center gap-1"
        >
          Book a demo <ArrowRight className="w-3.5 h-3.5" />
        </a>
      </div>
    </div>
  );
}

// ─── Right rail cards ─────────────────────────────────────────────────────────

function RailCardAiAttribution() {
  return (
    <div className="rounded-2xl bg-gradient-to-br from-slate-900 via-indigo-950 to-slate-900 p-4">
      <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/70 mb-2">
        AI Search Attribution
      </p>
      <p className="text-sm text-indigo-100/80 leading-relaxed mb-4">
        Connect the meSEO Site Tag to see exactly how many visits you are getting from ChatGPT, Perplexity, Claude, and Gemini — and which pages convert.
      </p>
      <a
        href={DEMO_URL}
        target="_blank"
        rel="noopener noreferrer"
        className="inline-flex items-center gap-2 bg-white text-indigo-900 text-xs font-semibold px-4 py-2 rounded-lg hover:bg-slate-100 transition-colors"
      >
        Book a demo <ArrowRight className="w-3.5 h-3.5" />
      </a>
    </div>
  );
}

function RailCardTestimonial() {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-4">
      <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
        From our clients
      </p>
      <blockquote className="text-sm text-slate-600 italic leading-relaxed mb-3">
        "meSEO helped us identify three years of technical debt in a single audit. We fixed the priority actions and organic traffic improved meaningfully within 60 days."
      </blockquote>
      <p className="text-xs text-slate-400 font-medium">
        — Head of Marketing, B2B SaaS (150 employees)
      </p>
    </div>
  );
}

function RailCardSiteTag() {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-4">
      <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
        With the meSEO Site Tag
      </p>
      <div className="space-y-2 mb-4">
        {SITE_TAG_ITEMS.map((item) => (
          <div key={item} className="flex items-center gap-2">
            <CheckCircle className="w-3.5 h-3.5 text-green-500 shrink-0" />
            <span className="text-xs text-slate-700">{item}</span>
          </div>
        ))}
      </div>
      <a
        href={DEMO_URL}
        target="_blank"
        rel="noopener noreferrer"
        className="text-xs text-blue-600 font-medium hover:underline inline-flex items-center gap-1"
      >
        Book a demo <ArrowRight className="w-3 h-3" />
      </a>
    </div>
  );
}

function RailCardDemo() {
  return (
    <div className="rounded-2xl bg-slate-900 p-4">
      <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">
        Get continuous monitoring
      </p>
      <p className="text-sm text-slate-300 leading-relaxed mb-4">
        Stop auditing quarterly. meSEO monitors your site continuously and surfaces issues the moment they appear.
      </p>
      <a
        href={DEMO_URL}
        target="_blank"
        rel="noopener noreferrer"
        className="inline-flex items-center gap-2 bg-white text-slate-900 text-xs font-semibold px-4 py-2 rounded-lg hover:bg-slate-100 transition-colors"
      >
        Book a demo <ArrowRight className="w-3.5 h-3.5" />
      </a>
    </div>
  );
}

// ─── Completed left rail ──────────────────────────────────────────────────────

function CompletedLeftRail({ auditId }: { auditId: string }) {
  const [copied, setCopied] = useState(false);

  function handleCopy() {
    const url = typeof window !== "undefined" ? window.location.href : "";
    navigator.clipboard.writeText(url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }).catch(() => {/* non-fatal */});
  }

  const encodedUrl = typeof window !== "undefined"
    ? encodeURIComponent(window.location.href)
    : "";
  const linkedInUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`;
  const tweetUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent("Got my free AI search visibility audit from @meSEOapp")}&url=${encodedUrl}`;

  return (
    <div className="space-y-4">
      {/* Share card */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-4">
        <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-3">
          Share your audit
        </p>
        <div className="space-y-2">
          <button
            onClick={handleCopy}
            className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs font-medium bg-slate-900 text-white rounded-lg hover:bg-slate-700 transition-colors"
          >
            {copied ? "Copied!" : "Copy link"}
          </button>
          <a
            href={linkedInUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs font-medium bg-[#0A66C2] text-white rounded-lg hover:opacity-90 transition-opacity"
          >
            Share on LinkedIn
          </a>
          <a
            href={tweetUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs font-medium bg-slate-800 text-white rounded-lg hover:bg-slate-700 transition-colors"
          >
            Share on X
          </a>
        </div>
      </div>

      {/* PDF card */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-4">
        <p className="text-[11px] font-semibold uppercase tracking-widest text-slate-400 mb-1">
          Download PDF
        </p>
        <p className="text-xs text-slate-500 mb-3">Your full audit as a branded PDF</p>
        <a
          href={`/api/public-audit/${auditId}/pdf`}
          target="_blank"
          rel="noopener noreferrer"
          className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs font-medium bg-slate-900 text-white rounded-lg hover:bg-slate-700 transition-colors"
        >
          <Download className="w-3.5 h-3.5" />
          Download PDF
        </a>
      </div>
    </div>
  );
}

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

function FailedView({ audit }: { audit: PublicAuditRecord }) {
  const errorMessage = audit.errorReason
    ? (ERROR_MESSAGES[audit.errorReason] ?? audit.userFacingError ?? "We encountered an issue analyzing this site. Please check the URL and try again.")
    : (audit.userFacingError ?? "We encountered an issue analyzing this site. Please check the URL and try again.");

  return (
    <div className="max-w-lg mx-auto px-4 py-16">
      <div className="bg-white rounded-2xl border border-red-200 p-8 text-center">
        <AlertTriangle className="w-10 h-10 text-red-400 mx-auto mb-3" />
        <h2 className="text-lg font-semibold text-slate-900 mb-2">Audit Could Not Complete</h2>
        <p className="text-sm text-slate-500 mb-6">{errorMessage}</p>
        <a
          href={DEMO_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 bg-slate-900 text-white text-sm font-medium px-5 py-2.5 rounded-lg hover:bg-slate-800 transition-colors"
        >
          Book a demo instead
        </a>
      </div>
    </div>
  );
}

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

function ReportView({ audit, isWelcomeBack }: { audit: PublicAuditRecord; isWelcomeBack?: boolean }) {
  const seo = audit.seoSection;

  useEffect(() => {
    if (seo?.keyFindings?.length) trackEvent(audit.id, "locked_behavioral_viewed");
  }, [audit.id, seo?.keyFindings?.length]);

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

  if (!seo) return null;

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

  const brandName = seo.displayName ?? seo.brandEcho?.brandName ?? audit.requestedWebsite ?? "Your Site";

  const hasCompetitive = !!(seo.competitiveLandscape);
  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 hasBacklinks = !!(seo.backlinkProfile);
  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 hasPrioritizedFindings = !!(seo.prioritizedFindings?.length);
  const hasTeaser = !!(seo.lockedFirstPartyTeaser);
  const isFirstPartyAudit = !seo.lockedFirstPartyTeaser;

  const tocItems = [
    { id: "audit-score", label: "Overview" },
    { id: "audit-ai-performance", label: "AI Performance" },
    ...(hasCompetitive ? [{ id: "audit-competitive", label: "Competitive" }] : []),
    ...(hasCompetitorDeepDive ? [{ id: "audit-competitor-deep-dive", label: "Competitive Intelligence" }] : []),
    ...(hasBacklinks ? [{ id: "audit-backlinks", label: "Backlinks" }] : []),
    { 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" }] : []),
    ...(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-ai-engines", label: "AI Engine Profiles" },
    ...(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" },
    ...(audit.rawData ? [{ id: "audit-technical-health", label: "Technical Health" }] : []),
    { 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" }] : []),
    ...(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" }] : []),
  ];

  function demoNudge(i: number) {
    if ((i + 1) % 3 !== 0 || i >= seo!.priorityActions.length - 1) return null;
    return (
      <div className="text-center py-2">
        <a
          href={DEMO_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="text-xs text-slate-400 hover:text-slate-600"
        >
          Want to ship these fixes faster? meSEO automates implementation.{" "}
          <span className="underline">Book a demo →</span>
        </a>
      </div>
    );
  }

  return (
    <div className="max-w-[1400px] mx-auto px-4 py-10">
      {isWelcomeBack && (
        <div className="mb-6 flex items-center gap-3 bg-indigo-50 border border-indigo-200 rounded-xl px-4 py-3 text-sm text-indigo-800">
          <CheckCircle className="w-4 h-4 shrink-0 text-indigo-500" />
          <span>Welcome back — your audit is ready.</span>
        </div>
      )}

      <div className="lg:grid lg:gap-8 lg:items-start" style={{ gridTemplateColumns: "260px 1fr 260px" }}>

        {/* ── Left rail (desktop only) ── */}
        <aside className="hidden lg:block">
          <div className="sticky top-6 space-y-4">
            <CompletedLeftRail auditId={audit.id} />
            <div className="bg-white rounded-2xl border border-slate-200 p-4">
              <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-2">
                Sections
              </p>
              <AuditTOC items={tocItems} />
            </div>
          </div>
        </aside>

        {/* ── Main content ── */}
        <div className="min-w-0 space-y-6">

          <AuditHero
            brandName={brandName}
            website={audit.requestedWebsite}
            auditDate={auditDate}
            score={seo.healthScore}
            pdfUrl={`/api/public-audit/${audit.id}/pdf`}
            execPdfUrl={seo.executiveBrief ? `/api/public-audit/${audit.id}/pdf?mode=executive` : undefined}
            viewMode={viewMode}
            subtitle="Results are based on a limited automated crawl. Upgrade to meSEO for continuous monitoring and full-site analysis."
          />

          <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 && (
                <div id="audit-upgrade">
                  <LockedFirstPartyTeaser teaser={seo.lockedFirstPartyTeaser} />
                </div>
              )}
              <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 detail 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" && (
            <>
              {/* Locked AI Performance panel */}
              <div id="audit-ai-performance" className="audit-hero-enter">
                <LockedAiPanel auditId={audit.id} />
              </div>

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

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

              {seo.backlinkProfile && (
                <div id="audit-backlinks">
                  <BacklinkProfileSection backlinkProfile={seo.backlinkProfile} />
                </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>
              )}

              {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>
              )}

              <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}
                  />
                )
              }

              {audit.rawData && (
                <TechnicalHealthSection rawData={audit.rawData} />
              )}

              {audit.rawData?.crawlSamples && audit.rawData.crawlSamples.length > 0 && (
                <CrawlSamples samples={audit.rawData.crawlSamples} />
              )}

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

              <InlineConversionCardAi auditId={audit.id} />

              <PriorityActionsSection
                actions={seo.priorityActions}
                demoNudge={demoNudge}
              />

              {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>
              )}

              <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} />
                </div>
              )}

              <InlineConversionCardSiteTag />
            </>
          )}

          <div className="text-center text-xs text-slate-400 py-6 border-t border-slate-100 space-y-1">
            <p>meSEO Free Audit Report · Results based on an automated crawl of up to 5 pages.</p>
            <p>
              This report does not constitute professional SEO advice. For comprehensive analysis,{" "}
              <a
                href={DEMO_URL}
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-500 hover:underline"
              >
                book a demo
              </a>
              .
            </p>
          </div>
        </div>

        {/* ── Right rail (desktop only) ── */}
        <aside className="hidden lg:block">
          <div className="sticky top-6 space-y-4">
            <RailCardAiAttribution />
            <RailCardTestimonial />
            <RailCardSiteTag />
            <RailCardDemo />
          </div>
        </aside>
      </div>
    </div>
  );
}

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

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

  useEffect(() => {
    if (typeof window !== "undefined" && window.location.search.includes("welcome=1")) {
      setIsWelcomeBack(true);
    }
  }, []);

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

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

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

  if (notFound) {
    return (
      <div className="max-w-lg mx-auto px-4 py-16 text-center">
        <p className="text-slate-500">Audit not found.</p>
      </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>
    );
  }

  if (audit.status === "queued" || audit.status === "running") {
    return <ProgressView audit={audit} />;
  }
  if (audit.status === "failed") return <FailedView audit={audit} />;
  return <ReportView audit={audit} isWelcomeBack={isWelcomeBack} />;
}
