"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import {
  ArrowLeft, Bot, CheckCircle2, XCircle, AlertCircle,
  Link2, Link2Off, Minus, Users, TrendingUp, TrendingDown,
  Lightbulb, ChevronRight, MessageSquareQuote, Zap,
} from "lucide-react";

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

type MentionStatus = "Mentioned" | "Not Mentioned" | "Partial";
type CitationStatus = "Cited" | "Not Cited" | "Indirect";

interface TrendPoint { week: string; ourScore: number; competitorAvg: number }
interface Competitor { name: string; mentioned: boolean; cited: boolean; excerpt: string }
interface Recommendation { priority: "High" | "Medium" | "Low"; action: string; effort: string }

interface PromptDetail {
  id: string;
  prompt: string;
  aiTool: string;
  lastChecked: string;
  ourVisibility: number;
  competitorAvg: number;
  mentionStatus: MentionStatus;
  citationStatus: CitationStatus;
  answerSummary: string;
  ourExcerpt: string | null;
  whyAppeared: string | null;
  whyMissed: string | null;
  competitors: Competitor[];
  trend: TrendPoint[];
  recommendations: Recommendation[];
}

// ─── Mock Data ────────────────────────────────────────────────────────────────

const PROMPTS: Record<string, PromptDetail> = {
  "best-seo-tool-small-businesses": {
    id: "best-seo-tool-small-businesses",
    prompt: "What is the best SEO tool for small businesses?",
    aiTool: "ChatGPT",
    lastChecked: "Today, 9:14 am",
    ourVisibility: 72,
    competitorAvg: 91,
    mentionStatus: "Mentioned",
    citationStatus: "Cited",
    answerSummary:
      "ChatGPT listed 5 tools for small businesses, ranking Semrush and Moz as top picks. meSEO was included as a third option with a specific callout for its AI visibility tracking feature. The answer linked directly to meSEO's homepage as a citation source.",
    ourExcerpt:
      '"…meSEO is a strong option for small business owners who want to track both traditional SEO metrics and AI search visibility in a single dashboard. Its crawl health reports are particularly useful for non-technical users…"',
    whyAppeared:
      "Your /features page was cited because it clearly describes AI visibility tracking — a differentiating capability that ChatGPT pulled as a unique signal. The structured content and descriptive headings made it easy for the model to extract a relevant quote.",
    whyMissed: null,
    competitors: [
      { name: "Semrush", mentioned: true, cited: true, excerpt: "Ranked #1 — cited for comprehensive keyword and backlink data for SMBs." },
      { name: "Moz", mentioned: true, cited: true, excerpt: "Ranked #2 — cited for beginner-friendly interface and free tier." },
      { name: "Ahrefs", mentioned: true, cited: false, excerpt: "Mentioned as a power-user option; no direct citation link." },
      { name: "Ubersuggest", mentioned: true, cited: false, excerpt: "Mentioned as a budget alternative; no citation." },
    ],
    trend: [
      { week: "Jan W1", ourScore: 48, competitorAvg: 80 },
      { week: "Jan W2", ourScore: 52, competitorAvg: 82 },
      { week: "Jan W3", ourScore: 55, competitorAvg: 84 },
      { week: "Jan W4", ourScore: 60, competitorAvg: 86 },
      { week: "Feb W1", ourScore: 64, competitorAvg: 88 },
      { week: "Feb W2", ourScore: 68, competitorAvg: 89 },
      { week: "Feb W3", ourScore: 70, competitorAvg: 90 },
      { week: "Feb W4", ourScore: 72, competitorAvg: 91 },
    ],
    recommendations: [
      { priority: "High", action: "Expand your /features page with a dedicated section for small business use cases — AI models weight use-case alignment heavily.", effort: "2 hrs" },
      { priority: "High", action: "Add a comparison table of meSEO vs Semrush vs Moz targeting SMB needs to capture 'best SEO tool' queries.", effort: "3 hrs" },
      { priority: "Medium", action: "Create a dedicated SMB landing page with testimonials and pricing clarity.", effort: "1 day" },
      { priority: "Low", action: "Publish a blog post: 'Why Small Businesses Need AI Visibility Tracking' to build topical authority.", effort: "4 hrs" },
    ],
  },

  "improve-google-ranking": {
    id: "improve-google-ranking",
    prompt: "How do I improve my website's Google ranking?",
    aiTool: "Perplexity",
    lastChecked: "Today, 9:14 am",
    ourVisibility: 58,
    competitorAvg: 84,
    mentionStatus: "Partial",
    citationStatus: "Indirect",
    answerSummary:
      "Perplexity provided a detailed 7-step answer covering technical SEO, backlinks, content quality, and Core Web Vitals. meSEO was referenced indirectly via a cited blog post from a third-party roundup that listed meSEO as a recommended audit tool. No direct citation to meSEO's own domain.",
    ourExcerpt:
      '"…tools like meSEO can help you run a full technical audit to identify crawl errors, broken links, and missing meta tags before they hurt your ranking…"',
    whyAppeared:
      "meSEO appeared indirectly because a third-party SEO blog that cited your content was itself cited by Perplexity. This is a weak signal — you are one step removed from the primary source.",
    whyMissed: null,
    competitors: [
      { name: "Moz", mentioned: true, cited: true, excerpt: "Cited directly for their beginner's guide to Google ranking signals." },
      { name: "Semrush", mentioned: true, cited: true, excerpt: "Cited for their Core Web Vitals explainer article." },
      { name: "ContentKing", mentioned: true, cited: false, excerpt: "Mentioned for technical SEO monitoring; no direct citation." },
      { name: "Google Search Console", mentioned: true, cited: true, excerpt: "Cited as primary recommended tool for all users." },
    ],
    trend: [
      { week: "Jan W1", ourScore: 30, competitorAvg: 72 },
      { week: "Jan W2", ourScore: 34, competitorAvg: 74 },
      { week: "Jan W3", ourScore: 38, competitorAvg: 76 },
      { week: "Jan W4", ourScore: 42, competitorAvg: 78 },
      { week: "Feb W1", ourScore: 46, competitorAvg: 80 },
      { week: "Feb W2", ourScore: 50, competitorAvg: 81 },
      { week: "Feb W3", ourScore: 54, competitorAvg: 83 },
      { week: "Feb W4", ourScore: 58, competitorAvg: 84 },
    ],
    recommendations: [
      { priority: "High", action: "Publish a comprehensive 'How to improve Google ranking' guide (2,000+ words) targeting this exact query — you currently have no direct-match content.", effort: "1 day" },
      { priority: "High", action: "Get a direct citation: reach out to SEO blogs that Perplexity cites and pitch a meSEO feature mention.", effort: "3 hrs" },
      { priority: "Medium", action: "Add a structured 'Step-by-step' section to your /technical-audit page targeting ranking improvement queries.", effort: "2 hrs" },
      { priority: "Low", action: "Create a Core Web Vitals explainer post — currently no meSEO content covers this topic that AI models cite.", effort: "4 hrs" },
    ],
  },

  "technical-seo-audit-tools": {
    id: "technical-seo-audit-tools",
    prompt: "Which tools help with technical SEO audits?",
    aiTool: "Claude AI",
    lastChecked: "Today, 9:14 am",
    ourVisibility: 81,
    competitorAvg: 76,
    mentionStatus: "Mentioned",
    citationStatus: "Cited",
    answerSummary:
      "Claude AI listed 6 technical SEO audit tools. meSEO ranked 2nd, cited directly for its crawl health dashboard and broken link detection. The answer highlighted meSEO's real-time crawl feature as a differentiator. This is one of your strongest performing prompts.",
    ourExcerpt:
      '"…meSEO stands out for its real-time crawl health dashboard, which surfaces broken links, missing meta descriptions, and page speed issues in a single view. It is particularly well-suited for teams who want actionable audit results without deep technical expertise…"',
    whyAppeared:
      "Your /technical-audit page has strong topical authority for technical SEO audit queries. It uses clear, descriptive headings that match the query intent, includes a features list that AI models can easily extract, and has been cited by at least 3 external SEO resources that build your citation authority.",
    whyMissed: null,
    competitors: [
      { name: "Screaming Frog", mentioned: true, cited: true, excerpt: "Ranked #1 — cited as the industry standard desktop crawler." },
      { name: "Sitebulb", mentioned: true, cited: false, excerpt: "Mentioned as a visual alternative to Screaming Frog." },
      { name: "ContentKing", mentioned: true, cited: true, excerpt: "Cited for real-time continuous monitoring capability." },
      { name: "DeepCrawl", mentioned: true, cited: false, excerpt: "Mentioned for enterprise-scale crawling needs." },
    ],
    trend: [
      { week: "Jan W1", ourScore: 55, competitorAvg: 70 },
      { week: "Jan W2", ourScore: 60, competitorAvg: 71 },
      { week: "Jan W3", ourScore: 63, competitorAvg: 72 },
      { week: "Jan W4", ourScore: 67, competitorAvg: 73 },
      { week: "Feb W1", ourScore: 70, competitorAvg: 74 },
      { week: "Feb W2", ourScore: 74, competitorAvg: 75 },
      { week: "Feb W3", ourScore: 78, competitorAvg: 75 },
      { week: "Feb W4", ourScore: 81, competitorAvg: 76 },
    ],
    recommendations: [
      { priority: "High", action: "Add a 'vs Screaming Frog' comparison section to your /technical-audit page to capture users evaluating alternatives.", effort: "2 hrs" },
      { priority: "Medium", action: "Create a dedicated 'Technical SEO Audit Checklist' post to capture checklist-modifier queries.", effort: "3 hrs" },
      { priority: "Medium", action: "Earn citations from 2–3 more external SEO resources to maintain your citation advantage over ContentKing.", effort: "1 week" },
      { priority: "Low", action: "Add video walkthrough of your crawl dashboard — AI models increasingly cite multimedia content.", effort: "1 day" },
    ],
  },

  "fix-broken-links": {
    id: "fix-broken-links",
    prompt: "How do I find and fix broken links on my site?",
    aiTool: "Google SGE",
    lastChecked: "Today, 9:14 am",
    ourVisibility: 44,
    competitorAvg: 68,
    mentionStatus: "Not Mentioned",
    citationStatus: "Not Cited",
    answerSummary:
      "Google SGE answered this query using content from Moz, Ahrefs, and Google's own Search Console documentation. No mention of meSEO in the answer. The response focused on methodology (crawling your site) and named specific free tools. meSEO's broken link detection feature was not surfaced.",
    ourExcerpt: null,
    whyAppeared: null,
    whyMissed:
      "meSEO has no dedicated content page targeting 'broken links' or '404 errors' as a topic. Google SGE pulled from pages that directly answer the how-to intent with step-by-step instructions. Your /technical-audit page mentions broken links as a feature but does not provide an instructional guide — which is what AI models prioritise for how-to queries.",
    competitors: [
      { name: "Moz", mentioned: true, cited: true, excerpt: "Cited for step-by-step guide to finding broken links with Moz Pro." },
      { name: "Ahrefs", mentioned: true, cited: true, excerpt: "Cited for Site Audit broken link report walkthrough." },
      { name: "Screaming Frog", mentioned: true, cited: false, excerpt: "Mentioned as a free tool to crawl and find 404s." },
      { name: "Google Search Console", mentioned: true, cited: true, excerpt: "Cited as the primary free option to identify crawl errors." },
    ],
    trend: [
      { week: "Jan W1", ourScore: 20, competitorAvg: 55 },
      { week: "Jan W2", ourScore: 22, competitorAvg: 57 },
      { week: "Jan W3", ourScore: 25, competitorAvg: 59 },
      { week: "Jan W4", ourScore: 28, competitorAvg: 61 },
      { week: "Feb W1", ourScore: 32, competitorAvg: 63 },
      { week: "Feb W2", ourScore: 36, competitorAvg: 65 },
      { week: "Feb W3", ourScore: 40, competitorAvg: 67 },
      { week: "Feb W4", ourScore: 44, competitorAvg: 68 },
    ],
    recommendations: [
      { priority: "High", action: "Publish a dedicated 'How to Find and Fix Broken Links' guide (step-by-step format) featuring meSEO's detection tool.", effort: "3 hrs" },
      { priority: "High", action: "Create a landing page at /features/broken-link-checker to give AI models a quotable feature page for this specific query.", effort: "2 hrs" },
      { priority: "Medium", action: "Add a '404 Error Fixes' section to your /technical-audit page with instructional content.", effort: "1 hr" },
      { priority: "Low", action: "Build a free broken link checker widget to attract backlinks and AI citations for this topic.", effort: "1 week" },
    ],
  },
};

// ─── 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 MentionBadge({ status }: { status: MentionStatus }) {
  const cfg: Record<MentionStatus, { style: string; icon: React.ReactNode }> = {
    "Mentioned":     { style: "bg-green-50 text-green-700 border-green-200", icon: <CheckCircle2 className="w-3 h-3" /> },
    "Not Mentioned": { style: "bg-red-50 text-red-600 border-red-200",       icon: <XCircle className="w-3 h-3" /> },
    "Partial":       { style: "bg-amber-50 text-amber-700 border-amber-200", icon: <AlertCircle className="w-3 h-3" /> },
  };
  const { style, icon } = cfg[status];
  return (
    <span className={`inline-flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-full border ${style}`}>
      {icon}{status}
    </span>
  );
}

function CitationBadge({ status }: { status: CitationStatus }) {
  const cfg: Record<CitationStatus, { style: string; icon: React.ReactNode }> = {
    "Cited":     { style: "bg-green-50 text-green-700 border-green-200", icon: <Link2 className="w-3 h-3" /> },
    "Not Cited": { style: "bg-red-50 text-red-600 border-red-200",       icon: <Link2Off className="w-3 h-3" /> },
    "Indirect":  { style: "bg-blue-50 text-blue-700 border-blue-200",    icon: <Minus className="w-3 h-3" /> },
  };
  const { style, icon } = cfg[status];
  return (
    <span className={`inline-flex items-center gap-1 text-xs font-semibold px-2.5 py-1 rounded-full border ${style}`}>
      {icon}{status}
    </span>
  );
}

// ─── Trend chart ──────────────────────────────────────────────────────────────

const CW = 520, CH = 120, PAD = { t: 8, r: 16, b: 28, l: 28 };

function px(i: number, n: number) {
  return PAD.l + (i / (n - 1)) * (CW - PAD.l - PAD.r);
}
function py(v: number) {
  return PAD.t + (CH - PAD.t - PAD.b) - (v / 100) * (CH - PAD.t - PAD.b);
}

function TrendChart({ data }: { data: TrendPoint[] }) {
  const n = data.length;
  const ourPts  = data.map((d, i) => `${px(i, n).toFixed(1)},${py(d.ourScore).toFixed(1)}`).join(" ");
  const cmpPts  = data.map((d, i) => `${px(i, n).toFixed(1)},${py(d.competitorAvg).toFixed(1)}`).join(" ");
  return (
    <svg viewBox={`0 0 ${CW} ${CH}`} className="w-full" aria-label="Prompt visibility trend">
      {[25, 50, 75].map(v => (
        <line key={v} x1={PAD.l} y1={py(v)} x2={CW - PAD.r} y2={py(v)} stroke="#f1f5f9" strokeWidth={1} />
      ))}
      {data.map((d, i) => (
        <text key={d.week} x={px(i, n)} y={CH - 4} textAnchor="middle" fontSize={8} fill="#94a3b8">{d.week}</text>
      ))}
      <polyline points={cmpPts} fill="none" stroke="#f97316" strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" strokeDasharray="4 3" />
      <polyline points={ourPts}  fill="none" stroke="#DC2626" strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" />
      {data.map((d, i) => (
        <circle key={i} cx={px(i, n)} cy={py(d.ourScore)} r={3} fill="#DC2626" stroke="white" strokeWidth={1.5} />
      ))}
    </svg>
  );
}

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

export default function PromptDetailPage() {
  const { slug } = useParams<{ slug: string }>();
  const p = PROMPTS[slug as string];

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

  const appeared = p.mentionStatus !== "Not Mentioned";
  const delta = p.ourVisibility - p.competitorAvg;

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

      {/* Back */}
      <Link href="/ai-visibility" 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 AI Visibility
      </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 gap-4">
          <div className="flex flex-wrap items-center gap-2">
            <span className="flex items-center gap-1.5 text-xs font-medium text-slate-400 bg-slate-700/60 border border-slate-600/40 px-2.5 py-1 rounded-full">
              <Bot className="w-3.5 h-3.5" />{p.aiTool}
            </span>
            <span className="text-slate-500 text-xs">Last checked: {p.lastChecked}</span>
          </div>
          <div>
            <p className="text-xs font-semibold uppercase tracking-widest text-slate-400 mb-1.5">Prompt</p>
            <h1 className="text-xl font-bold text-white leading-snug max-w-2xl">&ldquo;{p.prompt}&rdquo;</h1>
          </div>
          <div className="flex flex-wrap gap-3">
            <MentionBadge status={p.mentionStatus} />
            <CitationBadge status={p.citationStatus} />
          </div>
        </div>
      </div>

      {/* ══ 2. SCORE STRIP ══════════════════════════════════════════════════════ */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4 text-center">
          <p className="text-3xl font-black text-brand-600 tabular-nums">{p.ourVisibility}</p>
          <p className="text-xs text-slate-500 mt-0.5">Your visibility</p>
          <div className="mt-2 h-1.5 bg-slate-100 rounded-full overflow-hidden">
            <div className="h-full bg-brand-500 rounded-full" style={{ width: `${p.ourVisibility}%` }} />
          </div>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4 text-center">
          <p className="text-3xl font-black text-orange-500 tabular-nums">{p.competitorAvg}</p>
          <p className="text-xs text-slate-500 mt-0.5">Competitor avg</p>
          <div className="mt-2 h-1.5 bg-slate-100 rounded-full overflow-hidden">
            <div className="h-full bg-orange-400 rounded-full" style={{ width: `${p.competitorAvg}%` }} />
          </div>
        </div>
        <div className={`rounded-xl border px-5 py-4 text-center ${
          delta >= 0 ? "bg-green-50 border-green-200" : "bg-red-50 border-red-200"
        }`}>
          <p className={`text-3xl font-black tabular-nums ${delta >= 0 ? "text-green-600" : "text-red-600"}`}>
            {delta >= 0 ? "+" : ""}{delta}
          </p>
          <p className="text-xs text-slate-500 mt-0.5">vs competitors</p>
          <div className="mt-2 flex justify-center">
            {delta >= 0
              ? <TrendingUp className="w-4 h-4 text-green-500" />
              : <TrendingDown className="w-4 h-4 text-red-500" />}
          </div>
        </div>
      </div>

      {/* ══ 3. ANSWER SUMMARY ══════════════════════════════════════════════════ */}
      <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">
          <MessageSquareQuote className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Answer Summary</h2>
          <span className="ml-auto text-xs text-slate-400">{p.aiTool}</span>
        </div>
        <div className="px-5 py-4 space-y-4">
          <p className="text-sm text-slate-700 leading-relaxed">{p.answerSummary}</p>
          {p.ourExcerpt && (
            <div className="bg-brand-50 border-l-4 border-brand-500 rounded-r-lg px-4 py-3">
              <p className="text-xs font-semibold text-brand-600 mb-1.5">How meSEO was mentioned</p>
              <p className="text-sm text-slate-700 italic leading-relaxed">{p.ourExcerpt}</p>
            </div>
          )}
        </div>
      </div>

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

        {/* 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">Trend History</h2>
            <span className="ml-auto text-xs text-slate-400">8 weeks</span>
          </div>
          <div className="px-5 py-4">
            <TrendChart data={p.trend} />
            <div className="mt-3 flex items-center gap-5">
              <div className="flex items-center gap-1.5 text-xs text-slate-500">
                <span className="w-6 h-0.5 bg-brand-500 inline-block rounded" />
                meSEO
              </div>
              <div className="flex items-center gap-1.5 text-xs text-slate-500">
                <span className="w-6 border-t-2 border-dashed border-orange-400 inline-block" />
                Competitor avg
              </div>
            </div>
          </div>
        </div>

        {/* Competitors Present */}
        <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">
            <Users className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-800 text-sm">Competitors Present</h2>
            <span className="ml-auto text-xs text-slate-400">{p.competitors.length} detected</span>
          </div>
          <ul className="divide-y divide-slate-100">
            {p.competitors.map((c, i) => (
              <li key={i} className="px-5 py-3.5">
                <div className="flex items-center gap-2 mb-1">
                  <p className="text-sm font-semibold text-slate-800">{c.name}</p>
                  <span className={`text-[10px] font-semibold px-1.5 py-0.5 rounded border ${
                    c.mentioned ? "bg-green-50 text-green-700 border-green-200" : "bg-slate-100 text-slate-500 border-slate-200"
                  }`}>{c.mentioned ? "Mentioned" : "Not Mentioned"}</span>
                  <span className={`text-[10px] font-semibold px-1.5 py-0.5 rounded border ${
                    c.cited ? "bg-blue-50 text-blue-700 border-blue-200" : "bg-slate-100 text-slate-500 border-slate-200"
                  }`}>{c.cited ? "Cited" : "Not Cited"}</span>
                </div>
                <p className="text-xs text-slate-500 leading-relaxed">{c.excerpt}</p>
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* ══ 5. WHY WE DID / DIDN'T APPEAR ════════════════════════════════════ */}
      <div className={`rounded-xl border overflow-hidden ${
        appeared ? "bg-green-50 border-green-200" : "bg-red-50 border-red-200"
      }`}>
        <div className={`px-5 py-3.5 border-b flex items-center gap-2 ${
          appeared ? "border-green-200" : "border-red-200"
        }`}>
          {appeared
            ? <CheckCircle2 className="w-4 h-4 text-green-600" />
            : <XCircle className="w-4 h-4 text-red-500" />}
          <h2 className={`font-bold text-sm ${appeared ? "text-green-800" : "text-red-800"}`}>
            {appeared ? "Why We Appeared" : "Why We Were Missed"}
          </h2>
          <span className={`ml-auto text-xs ${appeared ? "text-green-600" : "text-red-500"}`}>
            {appeared ? "Signal analysis" : "Gap analysis"}
          </span>
        </div>
        <div className="px-5 py-4">
          <p className="text-sm leading-relaxed text-slate-700">
            {appeared ? p.whyAppeared : p.whyMissed}
          </p>
        </div>
      </div>

      {/* ══ 6. RECOMMENDED ACTIONS ════════════════════════════════════════════ */}
      <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 Actions</h2>
          <span className="ml-auto text-xs text-slate-400">To improve for this prompt</span>
        </div>
        <ul className="divide-y divide-slate-100">
          {p.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>
              <span className="shrink-0 text-[10px] text-slate-400 whitespace-nowrap pt-0.5">{r.effort}</span>
            </li>
          ))}
        </ul>
      </div>

    </div>
  );
}
