"use client";

/**
 * AI Visibility — Track brand presence in AI-generated answers.
 * Monitors ChatGPT, Perplexity, Gemini, Claude citations.
 */

import { useState, useEffect, useCallback } from "react";
import { useBrand } from "@/context/brand-context";
import { useBackgroundTasks } from "@/lib/stores/task-store";
import FeatureGate from "@/components/plan/feature-gate";
import {
  Bot, Eye, Sparkles, Loader2, Search, Plus, Trash2, CheckCircle2, XCircle,
  TrendingUp, BarChart3, Play, ChevronDown, ChevronUp, ChevronRight, X, MessageSquare, Zap,
  AlertTriangle, MapPin,
} from "lucide-react";

interface CheckResult {
  id: string; query: string; mentioned: boolean; position: number | null;
  context: string | null; fullResponse: string | null; sentiment: string | null;
  competitors: string[] | null; checkedAt: string;
}

interface QueryRecord {
  id: string; query: string; category: string | null; isActive: boolean;
  intent: string | null; targetLocation: string | null;
}

interface SuggestedQuery { query: string; intent: string; targetLocation: string; }

// Gated behind the ai_visibility feature — Professional+ only.
// Wraps the internal page in FeatureGate so the sidebar + route
// land on the same upgrade prompt when the user is on Growth.
export default function AiVisibilityPageGated() {
  return (
    <FeatureGate feature="ai_visibility">
      <AiVisibilityPage />
    </FeatureGate>
  );
}

function AiVisibilityPage() {
  const { brand } = useBrand();
  const { addTask, completeTask, failTask } = useBackgroundTasks();

  const [queries, setQueries] = useState<QueryRecord[]>([]);
  const [results, setResults] = useState<CheckResult[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null); // query text to confirm
  const [suggestingBranded, setSuggestingBranded] = useState(false);
  const [suggestingNonBranded, setSuggestingNonBranded] = useState(false);
  const [suggestedBranded, setSuggestedBranded] = useState<SuggestedQuery[]>([]);
  const [suggestedNonBranded, setSuggestedNonBranded] = useState<SuggestedQuery[]>([]);
  const [brandedExpanded, setBrandedExpanded] = useState(true);
  const [nonBrandedExpanded, setNonBrandedExpanded] = useState(true);
  const [auditing, setAuditing] = useState(false);
  const [checking, setChecking] = useState<string | null>(null);
  const [customQuery, setCustomQuery] = useState("");
  const [expanded, setExpanded] = useState<string | null>(null);
  const [recommendations, setRecommendations] = useState<string | null>(null);
  const [recsLoading, setRecsLoading] = useState(false);
  const [filter, setFilter] = useState<"all" | "mentioned" | "missing">("all");

  const loadData = useCallback(async () => {
    if (!brand?.id) return;
    setLoading(true);
    const [qr, rr] = await Promise.all([
      fetch(`/api/ai-visibility/queries?brandId=${brand.id}`).then((r) => r.ok ? r.json() : { queries: [] }),
      fetch(`/api/ai-visibility/results?brandId=${brand.id}`).then((r) => r.ok ? r.json() : { results: [] }),
    ]);
    setQueries(qr.queries || []); setResults(rr.results || []);
    setLoading(false);
  }, [brand.id]);
  useEffect(() => { loadData(); }, [loadData]);

  async function suggestBranded() {
    setSuggestingBranded(true);
    const r = await fetch("/api/ai-visibility/suggest-queries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id, type: "branded" }) });
    if (r.ok) { const d = await r.json(); setSuggestedBranded(d.suggestions || d.queries?.map((q: string) => ({ query: q, intent: "commercial", targetLocation: "" })) || []); }
    setSuggestingBranded(false);
  }

  async function suggestNonBranded() {
    setSuggestingNonBranded(true);
    const r = await fetch("/api/ai-visibility/suggest-queries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id, type: "nonbranded" }) });
    if (r.ok) { const d = await r.json(); setSuggestedNonBranded(d.suggestions || d.queries?.map((q: string) => ({ query: q, intent: "local", targetLocation: "" })) || []); }
    setSuggestingNonBranded(false);
  }

  async function saveQueries(items: SuggestedQuery[] | string[], category: string = "general") {
    const queryTexts = items.map((i) => typeof i === "string" ? i : i.query);
    await fetch("/api/ai-visibility/queries/save", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ brandId: brand.id, queries: items, category }),
    });
    setSuggestedBranded((prev) => prev.filter((q) => !queryTexts.includes(q.query)));
    setSuggestedNonBranded((prev) => prev.filter((q) => !queryTexts.includes(q.query)));
    loadData();
  }

  async function addCustom() {
    if (!customQuery.trim()) return;
    await saveQueries([customQuery.trim()]);
    setCustomQuery("");
  }

  async function deleteQuery(id: string) {
    setQueries((prev) => prev.filter((q) => q.id !== id));
    setResults((prev) => {
      const q = queries.find((q) => q.id === id);
      return q ? prev.filter((r) => r.query !== q.query) : prev;
    });
    await fetch(`/api/ai-visibility/queries/${id}`, { method: "DELETE" });
    setConfirmDelete(null);
  }

  /** Delete a keyword from results by its query text. Hits the
   *  delete-by-query endpoint unconditionally so orphaned rows in
   *  AiVisibilityCheck (cached AI responses with no matching query row)
   *  get cleaned up too — otherwise the result card reappears after
   *  refresh because only the UI was filtered. */
  async function deleteByQuery(queryText: string) {
    setResults((prev) => prev.filter((r) => r.query !== queryText));
    setQueries((prev) => prev.filter((q) => q.query !== queryText));
    await fetch("/api/ai-visibility/delete-by-query", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ brandId: brand.id, queries: [queryText] }),
    });
    setConfirmDelete(null);
  }

  async function bulkDelete() {
    if (selected.size === 0) return;
    const selectedQueries = Array.from(selected);
    // Optimistic UI
    setResults((prev) => prev.filter((r) => !selected.has(r.query)));
    setQueries((prev) => prev.filter((q) => !selected.has(q.query)));
    setSelected(new Set());
    // Always call the text-keyed delete endpoint (not the id-keyed
    // bulk-delete) — the selection contains query TEXT and may include
    // result-card queries with no matching AiVisibilityQuery row, which
    // the id-keyed path can't handle.
    await fetch("/api/ai-visibility/delete-by-query", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ brandId: brand.id, queries: selectedQueries }),
    });
  }

  function toggleSelect(query: string) {
    setSelected((prev) => { const n = new Set(prev); if (n.has(query)) n.delete(query); else n.add(query); return n; });
  }

  function toggleSelectAll() {
    if (selected.size === filtered.length) setSelected(new Set());
    else setSelected(new Set(filtered.map((r) => r.query)));
  }

  async function checkOne(query: string) {
    setChecking(query);
    await fetch("/api/ai-visibility/check", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id, query }) });
    await loadData();
    setChecking(null);
  }

  async function runAudit() {
    setAuditing(true);
    const taskId = addTask({ id: `aiv_${Date.now()}`, type: "ai_visibility_audit", label: "Running AI Visibility Audit...", brandId: brand.id, resultUrl: "/ai-visibility" });
    try {
      const r = await fetch("/api/ai-visibility/audit", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id }) });
      if (r.ok) { const d = await r.json(); completeTask(taskId, { resultUrl: "/ai-visibility", resultSummary: `Mentioned in ${d.mentionedCount}/${d.totalQueries} queries (score: ${d.score})` }); await loadData(); }
      else failTask(taskId, "Audit failed");
    } catch { failTask(taskId, "Network error"); }
    setAuditing(false);
  }

  async function loadRecs() {
    setRecsLoading(true);
    const r = await fetch("/api/ai-visibility/recommendations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId: brand.id }) });
    if (r.ok) { const d = await r.json(); setRecommendations(d.recommendations || null); }
    setRecsLoading(false);
  }

  // Computed stats
  const mentionedResults = results.filter((r) => r.mentioned);
  const mentionRate = results.length > 0 ? Math.round((mentionedResults.length / results.length) * 100) : 0;
  const positions = mentionedResults.map((r) => r.position).filter((p): p is number => p != null);
  const avgPosition = positions.length > 0 ? (positions.reduce((a, b) => a + b, 0) / positions.length).toFixed(1) : "—";
  const sentiments = { positive: 0, neutral: 0, negative: 0 };
  mentionedResults.forEach((r) => { if (r.sentiment === "positive") sentiments.positive++; else if (r.sentiment === "negative") sentiments.negative++; else sentiments.neutral++; });
  const allComps = results.flatMap((r) => (r.competitors as string[]) || []);
  const compCounts: Record<string, number> = {};
  allComps.forEach((c) => { compCounts[c] = (compCounts[c] || 0) + 1; });
  const topComps = Object.entries(compCounts).sort((a, b) => b[1] - a[1]).slice(0, 6);

  const filtered = filter === "all" ? results : filter === "mentioned" ? results.filter((r) => r.mentioned) : results.filter((r) => !r.mentioned);

  if (loading) return <div className="flex items-center justify-center h-64"><Loader2 className="w-8 h-8 animate-spin text-slate-300" /></div>;

  return (
    <div className="space-y-6 max-w-6xl">
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-purple-50 flex items-center justify-center"><Eye className="w-5 h-5 text-purple-600" /></div>
          <div>
            <h1 className="text-2xl font-bold text-slate-900">AI Visibility</h1>
            <p className="text-sm text-slate-500">Track how {brand.name} appears in AI-generated answers</p>
          </div>
        </div>
        <button onClick={runAudit} disabled={auditing || queries.length === 0} className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white text-sm font-semibold rounded-lg hover:bg-purple-700 disabled:opacity-50">
          {auditing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />} {auditing ? "Auditing..." : "Run Full Audit"}
        </button>
      </div>

      {/* Overview cards */}
      {results.length > 0 && (
        <div className="grid grid-cols-4 gap-4">
          <div className="bg-white rounded-xl border border-slate-200 p-4 text-center">
            <p className="text-2xl font-bold text-purple-600">{mentionRate}%</p>
            <p className="text-[11px] text-slate-500">Mention Rate</p>
          </div>
          <div className="bg-white rounded-xl border border-slate-200 p-4 text-center">
            <p className="text-2xl font-bold text-slate-900">{mentionedResults.length}<span className="text-sm font-normal text-slate-400">/{results.length}</span></p>
            <p className="text-[11px] text-slate-500">Queries Mentioned</p>
          </div>
          <div className="bg-white rounded-xl border border-slate-200 p-4 text-center">
            <p className="text-2xl font-bold text-teal-600">{avgPosition}</p>
            <p className="text-[11px] text-slate-500">Avg Position</p>
          </div>
          <div className="bg-white rounded-xl border border-slate-200 p-4 text-center flex items-center justify-center gap-3">
            <span className="text-xs"><span className="font-bold text-green-600">{sentiments.positive}</span> pos</span>
            <span className="text-xs"><span className="font-bold text-slate-600">{sentiments.neutral}</span> neu</span>
            <span className="text-xs"><span className="font-bold text-red-600">{sentiments.negative}</span> neg</span>
          </div>
        </div>
      )}

      {/* Query management */}
      <div className="bg-white rounded-xl border border-slate-200 p-5">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-bold text-slate-800">Monitored Queries ({queries.length})</h2>
          <div className="flex items-center gap-2">
            <button onClick={suggestBranded} disabled={suggestingBranded} className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 disabled:opacity-50">
              {suggestingBranded ? <Loader2 className="w-3 h-3 animate-spin" /> : <Sparkles className="w-3 h-3" />} Branded Queries
            </button>
            <button onClick={suggestNonBranded} disabled={suggestingNonBranded} className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-teal-600 bg-teal-50 rounded-lg hover:bg-teal-100 disabled:opacity-50">
              {suggestingNonBranded ? <Loader2 className="w-3 h-3 animate-spin" /> : <Sparkles className="w-3 h-3" />} Non-Branded Queries
            </button>
            {(suggestedBranded.length > 0 || suggestedNonBranded.length > 0) && (
              <button onClick={() => { setBrandedExpanded(false); setNonBrandedExpanded(false); }} className="text-[10px] font-semibold text-slate-400 hover:text-slate-600">
                Collapse All
              </button>
            )}
          </div>
        </div>

        {/* Suggested branded queries */}
        {suggestedBranded.length > 0 && (
          <div className="mb-4 p-3 rounded-lg bg-purple-50 border border-purple-200">
            <div className="flex items-center justify-between">
              <button onClick={() => setBrandedExpanded(!brandedExpanded)} className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-purple-600">
                {brandedExpanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
                AI-Suggested Branded Queries ({suggestedBranded.length})
              </button>
              <button onClick={() => saveQueries(suggestedBranded, "branded")} className="text-[10px] font-semibold text-purple-600 hover:underline">Add All Branded ({suggestedBranded.length})</button>
            </div>
            {brandedExpanded && (
              <div className="flex flex-wrap gap-1.5 mt-2">
                {suggestedBranded.map((s) => (
                  <button key={s.query} onClick={() => saveQueries([s], "branded")} className="flex items-center gap-1 px-2.5 py-1 text-xs bg-white border border-purple-200 rounded-full text-purple-700 hover:bg-purple-100">
                    <Plus className="w-3 h-3" /> {s.query}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Suggested non-branded queries */}
        {suggestedNonBranded.length > 0 && (
          <div className="mb-4 p-3 rounded-lg bg-teal-50 border border-teal-200">
            <div className="flex items-center justify-between">
              <button onClick={() => setNonBrandedExpanded(!nonBrandedExpanded)} className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-teal-600">
                {nonBrandedExpanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
                AI-Suggested Non-Branded Queries ({suggestedNonBranded.length})
              </button>
              <button onClick={() => saveQueries(suggestedNonBranded, "non-branded")} className="text-[10px] font-semibold text-teal-600 hover:underline">Add All Non-Branded ({suggestedNonBranded.length})</button>
            </div>
            {nonBrandedExpanded && (
              <div className="flex flex-wrap gap-1.5 mt-2">
                {suggestedNonBranded.map((s) => (
                  <button key={s.query} onClick={() => saveQueries([s], "non-branded")} className="flex items-center gap-1 px-2.5 py-1 text-xs bg-white border border-teal-200 rounded-full text-teal-700 hover:bg-teal-100 group">
                    <Plus className="w-3 h-3" />
                    <span>{s.query}</span>
                    {s.targetLocation && <span className="ml-1 text-[9px] text-teal-400 group-hover:text-teal-600 flex items-center gap-0.5"><MapPin className="w-2.5 h-2.5" />{s.targetLocation}</span>}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Add custom */}
        <div className="flex items-center gap-2 mb-3">
          <div className="relative flex-1">
            <input value={customQuery} onChange={(e) => setCustomQuery(e.target.value)} onKeyDown={(e) => e.key === "Enter" && addCustom()} placeholder="Add custom query..." className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500/40" />
            {customQuery.trim() && queries.some((q) => q.query.toLowerCase() === customQuery.trim().toLowerCase()) && (
              <span className="absolute right-2 top-1/2 -translate-y-1/2 text-[10px] font-semibold text-amber-600 bg-amber-50 border border-amber-200 rounded-full px-2 py-0.5">already tracking</span>
            )}
          </div>
          <button onClick={addCustom} disabled={!customQuery.trim()} className="px-3 py-2 bg-slate-900 text-white text-xs font-semibold rounded-lg hover:bg-slate-800 disabled:opacity-50 shrink-0">Add</button>
        </div>

        {/* Query list */}
        {queries.length > 0 && (
          <div className="space-y-1 max-h-48 overflow-y-auto">
            {queries.map((q) => (
              <div key={q.id} className="flex items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-slate-50">
                <Search className="w-3 h-3 text-slate-400 shrink-0" />
                <span className="text-xs text-slate-700 flex-1 truncate">{q.query}</span>
                {q.targetLocation && (
                  <span className="flex items-center gap-0.5 text-[9px] text-slate-400 shrink-0">
                    <MapPin className="w-2.5 h-2.5" />{q.targetLocation}
                  </span>
                )}
                {q.intent && (
                  <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded-full shrink-0 ${
                    q.intent === "local" ? "bg-emerald-50 text-emerald-600" :
                    q.intent === "transactional" ? "bg-blue-50 text-blue-600" :
                    q.intent === "informational" ? "bg-slate-100 text-slate-500" :
                    "bg-amber-50 text-amber-600"
                  }`}>{q.intent}</span>
                )}
                {q.category && (
                  <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded-full shrink-0 ${
                    q.category === "branded" ? "bg-purple-50 text-purple-600" :
                    q.category === "non-branded" ? "bg-teal-50 text-teal-600" :
                    "bg-slate-100 text-slate-500"
                  }`}>
                    {q.category === "branded" ? "Branded" : q.category === "non-branded" ? "Non-Branded" : "General"}
                  </span>
                )}
                <button onClick={() => deleteQuery(q.id)} className="text-slate-300 hover:text-red-500"><Trash2 className="w-3 h-3" /></button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Results table */}
      {results.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="flex items-center justify-between px-5 py-3 border-b border-slate-100">
            <div className="flex items-center gap-3">
              <h2 className="text-sm font-bold text-slate-800">Results</h2>
              {selected.size > 0 && (
                <button onClick={bulkDelete} className="flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-semibold text-red-600 bg-red-50 border border-red-200 hover:bg-red-100">
                  <Trash2 className="w-3 h-3" /> Remove {selected.size}
                </button>
              )}
            </div>
            <div className="flex gap-1">
              {(["all", "mentioned", "missing"] as const).map((f) => (
                <button key={f} onClick={() => setFilter(f)} className={`px-2.5 py-1 text-[11px] font-semibold rounded-md capitalize ${filter === f ? "bg-slate-900 text-white" : "text-slate-500 hover:bg-slate-100"}`}>{f}</button>
              ))}
            </div>
          </div>
          {/* Select all bar */}
          <div className="flex items-center gap-2 px-5 py-2 border-b border-slate-100 bg-slate-50/50">
            <input type="checkbox" checked={selected.size > 0 && selected.size === filtered.length} onChange={toggleSelectAll} className="rounded border-slate-300 text-purple-600 focus:ring-purple-500" />
            <span className="text-[10px] text-slate-500">{selected.size > 0 ? `${selected.size} selected` : "Select all"}</span>
          </div>
          <div className="divide-y divide-slate-100">
            {filtered.map((r) => (
              <div key={r.id}>
                <div className="flex items-center gap-3 px-5 py-3 hover:bg-slate-50 cursor-pointer" onClick={() => setExpanded(expanded === r.id ? null : r.id)}>
                  <input type="checkbox" checked={selected.has(r.query)} onChange={(e) => { e.stopPropagation(); toggleSelect(r.query); }} onClick={(e) => e.stopPropagation()} className="rounded border-slate-300 text-purple-600 focus:ring-purple-500 shrink-0" />
                  {r.mentioned
                    ? <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0" />
                    : <span className="inline-flex items-center gap-1 text-[9px] font-bold uppercase tracking-wide text-amber-700 bg-amber-50 border border-amber-200 rounded px-1.5 py-0.5 shrink-0"><AlertTriangle className="w-2.5 h-2.5" />AI Gap</span>
                  }
                  <span className="text-xs text-slate-700 flex-1 truncate">{r.query}</span>
                  {r.position && <span className={`text-xs font-bold px-1.5 py-0.5 rounded ${r.position <= 3 ? "bg-green-50 text-green-700" : r.position <= 6 ? "bg-amber-50 text-amber-700" : "bg-red-50 text-red-700"}`}>#{r.position}</span>}
                  {r.sentiment && <span className={`text-[10px] capitalize hidden sm:inline ${r.sentiment === "positive" ? "text-green-600" : r.sentiment === "negative" ? "text-red-600" : "text-slate-500"}`}>{r.sentiment}</span>}
                  <button onClick={(e) => { e.stopPropagation(); checkOne(r.query); }} disabled={checking === r.query} className="text-[10px] font-semibold text-purple-600 hover:underline disabled:opacity-50 shrink-0">
                    {checking === r.query ? <Loader2 className="w-3 h-3 animate-spin" /> : "Recheck"}
                  </button>
                  {/* Inline delete with confirmation */}
                  {confirmDelete === r.query ? (
                    <span className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
                      <button onClick={() => deleteByQuery(r.query)} className="text-[10px] font-semibold text-red-600 hover:underline">Remove</button>
                      <button onClick={() => setConfirmDelete(null)} className="text-[10px] font-semibold text-slate-400 hover:underline">Cancel</button>
                    </span>
                  ) : (
                    <button onClick={(e) => { e.stopPropagation(); setConfirmDelete(r.query); }} className="text-slate-300 hover:text-red-500 shrink-0" title="Remove keyword">
                      <Trash2 className="w-3 h-3" />
                    </button>
                  )}
                  {expanded === r.id ? <ChevronUp className="w-3 h-3 text-slate-400" /> : <ChevronDown className="w-3 h-3 text-slate-400" />}
                </div>
                {expanded === r.id && (
                  <div className="px-5 pb-4 space-y-3">
                    {!r.mentioned && (
                      <div className="rounded-lg border border-amber-200 bg-amber-50 p-3">
                        <p className="text-[11px] font-bold text-amber-800 flex items-center gap-1.5 mb-1">
                          <AlertTriangle className="w-3.5 h-3.5" /> AI Visibility Gap
                        </p>
                        <p className="text-[11px] text-amber-700 leading-snug">
                          {brand.name} does not appear in AI responses for &ldquo;{r.query}&rdquo;. This is a missed opportunity — searchers asking this question are not discovering your brand via AI assistants.
                        </p>
                        {r.competitors && (r.competitors as string[]).length > 0 && (
                          <p className="text-[11px] text-amber-700 mt-1">
                            <span className="font-semibold">Competitors appearing instead:</span>{" "}
                            {(r.competitors as string[]).join(", ")}
                          </p>
                        )}
                        <p className="text-[10px] text-amber-600 mt-1.5 font-medium">
                          Opportunity: Create or update content targeting this query to improve AI citation likelihood.
                        </p>
                      </div>
                    )}
                    {r.fullResponse && (
                      <div className="bg-slate-50 rounded-lg p-4 text-xs text-slate-600 leading-relaxed whitespace-pre-line max-h-48 overflow-y-auto">{r.fullResponse}</div>
                    )}
                    {r.context && <p className="text-xs"><span className="font-semibold text-green-700">Mention context:</span> {r.context}</p>}
                    {r.mentioned && r.competitors && (r.competitors as string[]).length > 0 && (
                      <div className="flex items-center gap-1 flex-wrap">
                        <span className="text-[10px] text-slate-500">Competitors:</span>
                        {(r.competitors as string[]).map((c, i) => <span key={i} className="text-[10px] px-1.5 py-0.5 rounded bg-red-50 text-red-700">{c}</span>)}
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Competitor comparison */}
      {topComps.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 p-5">
          <h2 className="text-sm font-bold text-slate-800 mb-3 flex items-center gap-2"><BarChart3 className="w-4 h-4 text-slate-500" /> Competitor Mentions</h2>
          <div className="space-y-2">
            {topComps.map(([name, count]) => (
              <div key={name} className="flex items-center gap-3">
                <span className="text-xs text-slate-700 w-40 truncate">{name}</span>
                <div className="flex-1 h-5 bg-slate-100 rounded-full overflow-hidden">
                  <div className="h-full bg-red-400 rounded-full" style={{ width: `${Math.min(100, (count / (topComps[0]?.[1] || 1)) * 100)}%` }} />
                </div>
                <span className="text-xs font-bold text-slate-600 w-8 text-right">{count}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* AI Recommendations */}
      <div className="rounded-xl p-5" style={{ background: "linear-gradient(135deg, #0B1120 0%, #1E293B 100%)" }}>
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2"><Zap className="w-4 h-4 text-purple-400" /><h2 className="text-sm font-bold text-white">AI Recommendations</h2></div>
          <button onClick={loadRecs} disabled={recsLoading} className="px-3 py-1.5 text-xs font-semibold text-purple-300 bg-white/10 rounded-lg hover:bg-white/20 disabled:opacity-50">
            {recsLoading ? <Loader2 className="w-3 h-3 animate-spin" /> : "Get Recommendations"}
          </button>
        </div>
        {recommendations ? (
          <p className="text-sm text-slate-300 leading-relaxed whitespace-pre-line">{recommendations}</p>
        ) : (
          <p className="text-sm text-slate-500">Click &quot;Get Recommendations&quot; for AI-powered visibility improvement tips.</p>
        )}
      </div>
    </div>
  );
}
