"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import {
  ArrowLeft, TrendingUp, Globe, ExternalLink,
  AlertTriangle, Lightbulb, Eye, BookOpen, Zap, ChevronRight,
  BarChart3, Target, Minus, Users, Plus,
} from "lucide-react";

// ─── Dev-only mock data flag ─────────────────────────────────────────────────
// The competitor detail view currently has no real data source — the rich
// per-competitor breakdowns below are hand-authored templates. In production
// we show a clean empty state. Dev users can set
// NEXT_PUBLIC_DEBUG_MOCK_DATA=true to preview the template with static data.
const DEV_MOCK_ENABLED =
  process.env.NEXT_PUBLIC_MESEO_ENV === "development" &&
  process.env.NEXT_PUBLIC_DEBUG_MOCK_DATA === "true";

// ─── Mock Data (dev only) ────────────────────────────────────────────────────

const COMPETITORS: Record<string, CompetitorDetail> = {
  "moz-blog": {
    name: "Moz Blog",
    domain: "moz.com",
    type: "National",
    visibilityScore: 92,
    yourScore: 74,
    monthlyTraffic: "2.4M",
    domainAuthority: 91,
    backlinks: "14.2M",
    topKeywords: 48200,
    summary:
      "Moz is the category-defining authority in SEO education. Built over 15+ years, their blog dominates informational queries across every funnel stage. Their moat is a combination of extreme domain authority, a massive backlink profile, and relentless publishing cadence.",
    trend: [58, 62, 67, 70, 76, 82, 88, 90, 91, 92, 92, 92],
    strongestPages: [
      { url: "/learn/seo", keyword: "what is SEO", traffic: "84k/mo", rank: 1 },
      { url: "/blog/meta-descriptions", keyword: "how to write meta descriptions", traffic: "29k/mo", rank: 2 },
      { url: "/tools/keyword-explorer", keyword: "keyword research tool", traffic: "21k/mo", rank: 1 },
      { url: "/learn/seo/on-page-seo", keyword: "on-page SEO", traffic: "18k/mo", rank: 3 },
      { url: "/blog/backlinks", keyword: "what are backlinks", traffic: "14k/mo", rank: 2 },
    ],
    whereWinning: [
      { category: "Informational SEO", gap: "+24 pts", keywords: 1840 },
      { category: "Tool Comparison Terms", gap: "+19 pts", keywords: 620 },
      { category: "Technical SEO Guides", gap: "+31 pts", keywords: 970 },
      { category: "Link Building", gap: "+28 pts", keywords: 740 },
    ],
    whyWinning: [
      "Domain authority of 91 — nearly impossible to outrank on competitive queries without massive link investment.",
      "Publishes 3–5 long-form articles per week, each targeting a distinct keyword cluster with full internal linking.",
      "Free tools (Keyword Explorer, Link Explorer) create millions of organic backlinks and branded return visits.",
      "15 years of topical authority signals — Google treats their content as a primary source for SEO topics.",
    ],
    pagesToStudy: [
      { url: "moz.com/learn/seo", reason: "Pillar page structure — covers every SEO subtopic in one canonically linked hub.", takeaway: "Build a /learn/seo hub page" },
      { url: "moz.com/blog/meta-descriptions", reason: "Ranks #2 for a query with 80k monthly searches. Clean structure, strong FAQ section.", takeaway: "Rewrite your meta description guide" },
      { url: "moz.com/tools/keyword-explorer", reason: "Tool page driving 21k visits/mo. Proves product pages can rank for informational terms.", takeaway: "Add keyword explorer landing page" },
    ],
    structuralTakeaways: [
      "Every blog post links to at least 3 internal tool pages — driving users toward conversion from content.",
      "H2 headers are written as exact-match search queries, which boosts featured snippet capture.",
      "All guides include a 'Frequently Asked Questions' section with 5–8 PAA-style questions.",
      "Schema markup (Article, FAQ, HowTo) is applied site-wide — heavily increases SERP real estate.",
      "Page speed scores average 94/100 on desktop, 87/100 on mobile — no performance drag.",
    ],
    recommendations: [
      { priority: "High", action: "Build a pillar hub page at /learn/seo covering all SEO subtopics.", effort: "1 week", impact: "High" },
      { priority: "High", action: "Rewrite your meta description guide targeting exact-match FAQ structure.", effort: "3 hrs", impact: "High" },
      { priority: "Medium", action: "Add FAQ schema markup to your 10 highest-traffic guides.", effort: "2 hrs", impact: "Med" },
      { priority: "Medium", action: "Internal link all blog posts to at least 2 product/feature pages.", effort: "4 hrs", impact: "Med" },
      { priority: "Low", action: "Launch a free keyword tool to build branded backlinks over time.", effort: "2 weeks", impact: "High" },
    ],
  },

  "semrush-blog": {
    name: "SEMrush Blog",
    domain: "semrush.com",
    type: "National",
    visibilityScore: 89,
    yourScore: 74,
    monthlyTraffic: "1.9M",
    domainAuthority: 88,
    backlinks: "9.8M",
    topKeywords: 39100,
    summary:
      "SEMrush operates the highest-volume SEO content machine in the industry. They publish 20+ articles per week and target every SEO keyword cluster imaginable. Their strategy is volume + tooling — get ranked, then convert to SaaS.",
    trend: [55, 60, 64, 68, 73, 78, 83, 85, 87, 88, 89, 89],
    strongestPages: [
      { url: "/blog/seo-tips", keyword: "SEO tips for beginners", traffic: "61k/mo", rank: 2 },
      { url: "/blog/keyword-research", keyword: "keyword research tutorial", traffic: "17k/mo", rank: 3 },
      { url: "/blog/technical-seo", keyword: "technical SEO checklist", traffic: "12k/mo", rank: 1 },
      { url: "/features/site-audit", keyword: "website audit tool", traffic: "9k/mo", rank: 4 },
      { url: "/blog/backlink-audit", keyword: "backlink audit guide", traffic: "7k/mo", rank: 2 },
    ],
    whereWinning: [
      { category: "Beginner SEO Content", gap: "+18 pts", keywords: 2100 },
      { category: "Keyword Research", gap: "+22 pts", keywords: 880 },
      { category: "Technical SEO", gap: "+15 pts", keywords: 640 },
      { category: "SaaS Tool Terms", gap: "+27 pts", keywords: 1200 },
    ],
    whyWinning: [
      "Content velocity: 20+ articles/week saturates every long-tail keyword variation.",
      "Each article is tightly coupled to a specific SaaS feature, creating a content-to-conversion flywheel.",
      "Massive affiliate and partner network drives thousands of editorial backlinks monthly.",
      "Strong video + blog repurposing strategy amplifies reach across YouTube and LinkedIn.",
    ],
    pagesToStudy: [
      { url: "semrush.com/blog/seo-tips", reason: "Ranks #2 for 'SEO tips' with 61k searches/mo. Uses numbered list format with jump links.", takeaway: "Create a comprehensive SEO tips listicle" },
      { url: "semrush.com/blog/keyword-research", reason: "Step-by-step format with screenshots drives strong engagement and dwell time.", takeaway: "Reformat your keyword guide as a step-by-step" },
      { url: "semrush.com/blog/technical-seo", reason: "Checklist format ranks #1 — checklist posts capture 'checklist' modifier queries.", takeaway: "Publish a technical SEO checklist post" },
    ],
    structuralTakeaways: [
      "Numbered/listicle H2s ('10 Tips for X') dominate across their blog — easy to skim, high CTR.",
      "Every post ends with a CTA to the relevant SaaS feature — content and product are fully connected.",
      "Heavy use of comparison tables (us vs. competitor) captures high-intent commercial queries.",
      "Consistent use of annotated screenshots improves visual engagement and time-on-page.",
      "Blog posts are refreshed annually with updated data, maintaining freshness signals.",
    ],
    recommendations: [
      { priority: "High", action: "Publish a '10 SEO Tips for Beginners' listicle targeting beginner keywords.", effort: "4 hrs", impact: "High" },
      { priority: "High", action: "Create a Technical SEO Checklist post — checklist format ranks well.", effort: "3 hrs", impact: "High" },
      { priority: "Medium", action: "Add a product CTA at the end of every blog post.", effort: "2 hrs", impact: "Med" },
      { priority: "Medium", action: "Build a competitor comparison page (you vs. Moz, SEMrush, etc.).", effort: "1 day", impact: "High" },
      { priority: "Low", action: "Refresh your top 5 posts with updated data and screenshots.", effort: "1 day", impact: "Med" },
    ],
  },

  "contentking": {
    name: "ContentKing",
    domain: "contentkingapp.com",
    type: "National",
    visibilityScore: 87,
    yourScore: 74,
    monthlyTraffic: "980k",
    domainAuthority: 74,
    backlinks: "4.1M",
    topKeywords: 22400,
    summary:
      "ContentKing punches above its DA weight by producing extremely detailed long-form pillar content. Their technical SEO guide is one of the most-linked pages in the industry. They prove that depth + structure beats volume when targeting mid-to-bottom-funnel queries.",
    trend: [48, 52, 57, 61, 67, 72, 77, 80, 83, 85, 86, 87],
    strongestPages: [
      { url: "/blog/seo-guide", keyword: "technical SEO guide", traffic: "38k/mo", rank: 2 },
      { url: "/blog/crawlability", keyword: "improve crawlability", traffic: "11k/mo", rank: 1 },
      { url: "/blog/site-structure", keyword: "website structure SEO", traffic: "9k/mo", rank: 3 },
      { url: "/blog/internal-linking", keyword: "internal linking strategy", traffic: "8k/mo", rank: 2 },
      { url: "/blog/page-speed", keyword: "page speed optimization", traffic: "6k/mo", rank: 4 },
    ],
    whereWinning: [
      { category: "Technical SEO Depth", gap: "+16 pts", keywords: 520 },
      { category: "Crawlability & Indexing", gap: "+29 pts", keywords: 310 },
      { category: "Site Architecture", gap: "+21 pts", keywords: 280 },
      { category: "Internal Linking", gap: "+18 pts", keywords: 190 },
    ],
    whyWinning: [
      "Their technical SEO guide is 12,000+ words with a linked table of contents — a reference-class document.",
      "Strong internal linking between related technical topics keeps users on-site and signals topic clusters.",
      "High editorial backlink rate — other SEO blogs cite them as a primary source, boosting DA quickly.",
      "Every guide targets a specific practitioner pain point with step-by-step solutions, not just theory.",
    ],
    pagesToStudy: [
      { url: "contentkingapp.com/blog/seo-guide", reason: "12k-word technical pillar. Most cited SEO guide outside of Google's own docs.", takeaway: "Write a definitive technical SEO guide" },
      { url: "contentkingapp.com/blog/internal-linking", reason: "Ranks #2 for 'internal linking strategy' — includes diagrams and real examples.", takeaway: "Build an internal linking strategy guide with diagrams" },
      { url: "contentkingapp.com/blog/crawlability", reason: "#1 for a 9k/mo keyword by covering crawl budget in more depth than anyone else.", takeaway: "Write a crawl budget + crawlability deep-dive" },
    ],
    structuralTakeaways: [
      "All long-form guides include a sticky table of contents with anchor links — reduces bounce rate.",
      "Use of custom diagrams and flowcharts in technical content earns editorial links from other blogs.",
      "Topic cluster model: every technical guide links to 4–6 sub-guides on related concepts.",
      "Authors are listed with credentials and photos — builds E-E-A-T signals Google rewards.",
      "Guides are structured as 'The Definitive Guide' — signals comprehensiveness to both users and Google.",
    ],
    recommendations: [
      { priority: "High", action: "Write a 8–10k word definitive technical SEO guide with a table of contents.", effort: "2 days", impact: "High" },
      { priority: "High", action: "Add author bios with credentials to all major guides (E-E-A-T signal).", effort: "2 hrs", impact: "Med" },
      { priority: "Medium", action: "Create custom diagrams for your top 5 technical guides.", effort: "1 day", impact: "Med" },
      { priority: "Medium", action: "Map your content into topic clusters with clear internal linking paths.", effort: "4 hrs", impact: "High" },
      { priority: "Low", action: "Add sticky table-of-contents navigation to all long-form posts.", effort: "3 hrs", impact: "Med" },
    ],
  },
};

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

interface StrongPage { url: string; keyword: string; traffic: string; rank: number }
interface WinArea { category: string; gap: string; keywords: number }
interface StudyPage { url: string; reason: string; takeaway: string }
interface Rec { priority: string; action: string; effort: string; impact: string }

interface CompetitorDetail {
  name: string; domain: string; type: string;
  visibilityScore: number; yourScore: number;
  monthlyTraffic: string; domainAuthority: number;
  backlinks: string; topKeywords: number;
  summary: string;
  trend: number[];
  strongestPages: StrongPage[];
  whereWinning: WinArea[];
  whyWinning: string[];
  pagesToStudy: StudyPage[];
  structuralTakeaways: string[];
  recommendations: Rec[];
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

const priorityStyles: Record<string, string> = {
  High:   "bg-red-50 text-red-700 border-red-200",
  Medium: "bg-amber-50 text-amber-700 border-amber-200",
  Low:    "bg-blue-50 text-blue-600 border-blue-200",
};

function MiniTrend({ data, score }: { data: number[]; score: number }) {
  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = max - min || 1;
  const w = 200, h = 48, pad = 4;
  const step = (w - pad * 2) / (data.length - 1);
  const pts = data.map((v, i) => {
    const x = pad + i * step;
    const y = h - pad - ((v - min) / range) * (h - pad * 2);
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  const lastPt = pts.split(" ").pop()!.split(",");
  return (
    <div className="flex items-end gap-4">
      <svg width={w} height={h} className="overflow-visible">
        <polyline points={pts} fill="none" stroke="#DC2626" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx={lastPt[0]} cy={lastPt[1]} r="3" fill="#DC2626" />
      </svg>
      <div className="text-right">
        <p className="text-2xl font-black text-slate-900 tabular-nums">{score}</p>
        <p className="text-xs text-slate-400">current score</p>
      </div>
    </div>
  );
}

function RankBadge({ rank }: { rank: number }) {
  const color = rank === 1 ? "bg-green-100 text-green-700" : rank <= 3 ? "bg-amber-50 text-amber-700" : "bg-slate-100 text-slate-500";
  return <span className={`text-xs font-bold px-1.5 py-0.5 rounded ${color}`}>#{rank}</span>;
}

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

export default function CompetitorDetailPage() {
  const { slug } = useParams<{ slug: string }>();
  const c = DEV_MOCK_ENABLED ? COMPETITORS[slug as string] : undefined;

  // Production path — no real competitor data source exists yet. Show a
  // clean empty state and keep the link back to the parent listing.
  if (!DEV_MOCK_ENABLED) {
    return (
      <div className="space-y-5 max-w-2xl">
        <Link href="/competitors" className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800 transition-colors">
          <ArrowLeft className="w-4 h-4" /> Back to Competitors
        </Link>

        <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
          <div className="bg-gradient-to-br from-brand-50/60 via-white to-white px-8 py-12 text-center">
            <div className="w-16 h-16 rounded-2xl bg-white border border-brand-200 flex items-center justify-center mx-auto mb-5 shadow-sm">
              <Users className="w-8 h-8 text-brand-600" />
            </div>
            <h2 className="text-xl font-bold text-slate-900 mb-2">No Competitor Data Yet</h2>
            <p className="text-sm text-slate-500 max-w-md mx-auto leading-relaxed">
              Add competitors to track and compare their SEO performance against yours — visibility scores, strongest pages, ranking keywords, and gap analysis.
            </p>
          </div>
          <div className="border-t border-slate-100 bg-slate-50/50 px-8 py-4 flex items-center justify-between flex-wrap gap-3">
            <p className="text-xs text-slate-500">
              Competitor tracking for <span className="font-semibold text-slate-700">{slug}</span> is not configured.
            </p>
            <Link
              href="/competitors"
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-brand-600 text-white text-xs font-semibold hover:bg-brand-700 transition-colors"
            >
              <Plus className="w-3 h-3" />
              Add Competitor
            </Link>
          </div>
        </div>
      </div>
    );
  }

  if (!c) {
    return (
      <div className="flex flex-col items-center justify-center py-32 gap-4">
        <p className="text-slate-400 text-sm">Competitor not found.</p>
        <Link href="/competitors" className="text-brand-600 text-sm font-semibold flex items-center gap-1 hover:underline">
          <ArrowLeft className="w-4 h-4" /> Back to Competitors
        </Link>
      </div>
    );
  }

  const delta = c.visibilityScore - c.yourScore;

  return (
    <div className="space-y-5">

      {/* Back */}
      <Link href="/competitors" className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800 transition-colors">
        <ArrowLeft className="w-4 h-4" /> Back to Competitors
      </Link>

      {/* ══ 1. HEADER ══════════════════════════════════════════════════════════ */}
      <div className="bg-gradient-to-r from-slate-900 to-slate-800 rounded-2xl px-6 py-5">
        <div className="flex flex-col sm:flex-row sm:items-start gap-5">
          <div className="flex-1">
            <div className="flex flex-wrap items-center gap-2 mb-1">
              <span className={`text-xs font-semibold px-2 py-0.5 rounded border ${
                c.type === "National" ? "bg-blue-900/40 text-blue-300 border-blue-700" :
                c.type === "Local"    ? "bg-green-900/40 text-green-300 border-green-700" :
                                       "bg-amber-900/40 text-amber-300 border-amber-700"
              }`}>{c.type}</span>
              <span className="text-slate-400 text-xs">{c.domain}</span>
            </div>
            <h1 className="text-2xl font-bold text-white">{c.name}</h1>
            <p className="text-slate-400 text-sm mt-2 max-w-xl leading-relaxed">{c.summary}</p>
          </div>
          {/* Score comparison */}
          <div className="flex gap-4 shrink-0">
            <div className="bg-slate-700/50 rounded-xl px-5 py-4 text-center border border-slate-600/40">
              <p className="text-3xl font-black text-white tabular-nums">{c.visibilityScore}</p>
              <p className="text-xs text-slate-400 mt-0.5">Their score</p>
            </div>
            <div className="bg-slate-700/50 rounded-xl px-5 py-4 text-center border border-slate-600/40">
              <p className="text-3xl font-black text-brand-400 tabular-nums">{c.yourScore}</p>
              <p className="text-xs text-slate-400 mt-0.5">Your score</p>
            </div>
            <div className={`rounded-xl px-5 py-4 text-center border ${
              delta > 0 ? "bg-red-900/30 border-red-700/40" : "bg-green-900/30 border-green-700/40"
            }`}>
              <p className={`text-3xl font-black tabular-nums ${delta > 0 ? "text-red-400" : "text-green-400"}`}>
                {delta > 0 ? "+" : ""}{delta}
              </p>
              <p className="text-xs text-slate-400 mt-0.5">{delta > 0 ? "Ahead of you" : "Behind you"}</p>
            </div>
          </div>
        </div>
      </div>

      {/* ══ 2. STAT STRIP ══════════════════════════════════════════════════════ */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "Monthly Traffic", value: c.monthlyTraffic, icon: Globe, color: "text-brand-600" },
          { label: "Domain Authority", value: String(c.domainAuthority), icon: Target, color: "text-purple-600" },
          { label: "Backlinks", value: c.backlinks, icon: ExternalLink, color: "text-green-600" },
          { label: "Ranking Keywords", value: c.topKeywords.toLocaleString(), icon: BarChart3, color: "text-amber-600" },
        ].map((s) => (
          <div key={s.label} className="bg-white rounded-xl border border-slate-200 px-4 py-4 flex items-center gap-3">
            <s.icon className={`w-5 h-5 shrink-0 ${s.color}`} />
            <div>
              <p className="text-xl font-bold text-slate-900 tabular-nums">{s.value}</p>
              <p className="text-xs text-slate-500">{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* ══ 3. TREND + STRONGEST PAGES ════════════════════════════════════════ */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">

        {/* Visibility Trend */}
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-800 text-sm">Visibility Trend</h2>
            <span className="ml-auto text-xs text-slate-400">Last 12 months</span>
          </div>
          <div className="px-5 py-5">
            <MiniTrend data={c.trend} score={c.visibilityScore} />
            <div className="mt-4 flex items-center gap-2 text-xs text-slate-500">
              <span className="w-3 h-0.5 bg-brand-500 inline-block rounded" />
              {c.name} visibility score over time
            </div>
          </div>
        </div>

        {/* Strongest Pages */}
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Eye className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-800 text-sm">Strongest Pages</h2>
          </div>
          <ul className="divide-y divide-slate-100">
            {c.strongestPages.map((p, i) => (
              <li key={i} className="px-5 py-3 flex items-center gap-3">
                <RankBadge rank={p.rank} />
                <div className="flex-1 min-w-0">
                  <p className="font-mono text-xs text-brand-600 truncate">{p.url}</p>
                  <p className="text-xs text-slate-500 truncate mt-0.5">&ldquo;{p.keyword}&rdquo;</p>
                </div>
                <span className="text-xs font-semibold text-green-700 bg-green-50 border border-green-100 px-2 py-0.5 rounded whitespace-nowrap">
                  {p.traffic}
                </span>
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* ══ 4. WHERE WINNING + WHY WINNING ════════════════════════════════════ */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">

        {/* Where They're Winning */}
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2 bg-red-50/50">
            <AlertTriangle className="w-4 h-4 text-red-500" />
            <h2 className="font-bold text-slate-800 text-sm">Where They&apos;re Winning</h2>
          </div>
          <ul className="divide-y divide-slate-100">
            {c.whereWinning.map((w, i) => (
              <li key={i} className="px-5 py-4">
                <div className="flex items-center justify-between mb-1.5">
                  <p className="text-sm font-semibold text-slate-800">{w.category}</p>
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-bold text-red-600">{w.gap}</span>
                    <span className="text-xs text-slate-400">{w.keywords.toLocaleString()} keywords</span>
                  </div>
                </div>
                <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
                  <div className="h-full bg-red-400 rounded-full" style={{ width: `${Math.min(100, parseInt(w.gap) + 74)}%` }} />
                </div>
              </li>
            ))}
          </ul>
        </div>

        {/* Why They're Winning */}
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2 bg-amber-50/50">
            <Zap className="w-4 h-4 text-amber-500" />
            <h2 className="font-bold text-slate-800 text-sm">Why They&apos;re Winning</h2>
          </div>
          <ul className="divide-y divide-slate-100">
            {c.whyWinning.map((reason, i) => (
              <li key={i} className="px-5 py-3.5 flex gap-3">
                <span className="w-5 h-5 rounded-full bg-amber-100 text-amber-700 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">
                  {i + 1}
                </span>
                <p className="text-sm text-slate-700 leading-relaxed">{reason}</p>
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* ══ 5. PAGES TO STUDY ══════════════════════════════════════════════════ */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
          <BookOpen className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Pages to Study</h2>
          <span className="ml-auto text-xs text-slate-400">Analyze these pages to close the gap</span>
        </div>
        <div className="divide-y divide-slate-100">
          {c.pagesToStudy.map((p, i) => (
            <div key={i} className="px-5 py-4 flex gap-4">
              <span className="w-6 h-6 rounded-full bg-brand-50 text-brand-600 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">
                {i + 1}
              </span>
              <div className="flex-1 min-w-0">
                <p className="font-mono text-xs text-brand-600 mb-1">{p.url}</p>
                <p className="text-sm text-slate-600 leading-relaxed mb-2">{p.reason}</p>
                <div className="inline-flex items-center gap-1.5 bg-green-50 border border-green-200 text-green-700 text-xs font-semibold px-2.5 py-1 rounded-full">
                  <ChevronRight className="w-3 h-3" />
                  Your move: {p.takeaway}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ══ 6. STRUCTURAL TAKEAWAYS ════════════════════════════════════════════ */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
          <Target className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Structural Takeaways</h2>
          <span className="ml-auto text-xs text-slate-400">What makes their site structure work</span>
        </div>
        <ul className="divide-y divide-slate-100">
          {c.structuralTakeaways.map((t, i) => (
            <li key={i} className="px-5 py-3.5 flex gap-3 items-start">
              <Minus className="w-3.5 h-3.5 text-slate-300 mt-1 shrink-0" />
              <p className="text-sm text-slate-700 leading-relaxed">{t}</p>
            </li>
          ))}
        </ul>
      </div>

      {/* ══ 7. RECOMMENDED RESPONSES ═══════════════════════════════════════════ */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2 bg-blue-50/50">
          <Lightbulb className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Recommended Responses</h2>
          <span className="ml-auto text-xs text-slate-400">Actions to close the gap</span>
        </div>
        <ul className="divide-y divide-slate-100">
          {c.recommendations.map((r, i) => (
            <li key={i} className="px-5 py-3.5 flex items-start gap-3">
              <span className={`shrink-0 mt-0.5 text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded border ${priorityStyles[r.priority]}`}>
                {r.priority}
              </span>
              <p className="flex-1 text-sm text-slate-700 leading-relaxed">{r.action}</p>
              <div className="shrink-0 text-right space-y-0.5">
                <p className="text-[10px] text-slate-400 whitespace-nowrap">{r.effort}</p>
                <p className={`text-[10px] font-semibold whitespace-nowrap ${
                  r.impact === "High" ? "text-green-600" : r.impact === "Med" ? "text-amber-600" : "text-slate-400"
                }`}>{r.impact} impact</p>
              </div>
            </li>
          ))}
        </ul>
      </div>

    </div>
  );
}
