"use client";

import { useEffect, useState } from "react";
import { TrendBadge } from "@/components/admin/trend-badge";
import type { AiSearchPerformance } from "@/lib/audit/types";
import { nmoney } from "@/lib/utils";

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

function engineLabel(raw: string): string {
  const map: Record<string, string> = {
    chatgpt: "ChatGPT",
    "chat gpt": "ChatGPT",
    openai: "ChatGPT",
    perplexity: "Perplexity",
    claude: "Claude",
    anthropic: "Claude",
    gemini: "Gemini",
    bard: "Gemini",
    google_ai_overview: "Google AI Overview",
    google_ai: "Google AI Overview",
    google: "Google AI",
    copilot: "Copilot",
    bing: "Copilot",
    grok: "Grok",
    unknown: "Other",
  };
  return map[raw.toLowerCase()] ?? raw;
}

function urlPath(url: string): string {
  try {
    const u = new URL(url);
    const p = u.pathname.replace(/\/$/, "") || "/";
    return p.length > 40 ? p.slice(0, 38) + "…" : p;
  } catch {
    return url.length > 40 ? url.slice(0, 38) + "…" : url;
  }
}

// ─── Sparkline ────────────────────────────────────────────────────────────────

function ReferralSparkline({ data }: { data: Array<{ date: string; count: number }> }) {
  const [hoverIdx, setHoverIdx] = useState<number | null>(null);

  if (!data || data.length < 2) return null;

  const W = 400;
  const H = 72;
  const PAD = 6;
  const maxCount = Math.max(...data.map((d) => d.count), 1);
  const segW = (W - PAD * 2) / (data.length - 1);

  const pts = data.map((d, i) => ({
    x: PAD + i * segW,
    y: H - PAD - (d.count / maxCount) * (H - PAD * 2),
    date: d.date,
    count: d.count,
  }));

  const polyPoints = pts.map((p) => `${p.x},${p.y}`).join(" ");
  const fillPath = [
    `M ${pts[0].x} ${H}`,
    ...pts.map((p) => `L ${p.x} ${p.y}`),
    `L ${pts[pts.length - 1].x} ${H}`,
    "Z",
  ].join(" ");

  const hovered = hoverIdx !== null ? pts[hoverIdx] : null;

  return (
    <div className="relative mt-5">
      <svg
        viewBox={`0 0 ${W} ${H}`}
        style={{ height: H, width: "100%", display: "block" }}
        onMouseLeave={() => setHoverIdx(null)}
      >
        <defs>
          <linearGradient id="sparkg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#818cf8" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#818cf8" stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d={fillPath} fill="url(#sparkg)" />
        <polyline
          points={polyPoints}
          fill="none"
          stroke="#818cf8"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        {pts.map((p, i) => (
          <rect
            key={i}
            x={p.x - segW / 2}
            y={0}
            width={segW}
            height={H}
            fill="transparent"
            onMouseEnter={() => setHoverIdx(i)}
            style={{ cursor: "crosshair" }}
          />
        ))}
        {hovered && (
          <circle
            cx={hovered.x}
            cy={hovered.y}
            r="3.5"
            fill="#818cf8"
            stroke="white"
            strokeWidth="1.5"
          />
        )}
      </svg>
      {hovered && (
        <div
          className="absolute -top-7 text-[10px] bg-slate-900 border border-white/20 text-indigo-100 px-2 py-1 rounded pointer-events-none whitespace-nowrap z-10"
          style={{
            left: `${((hovered.x - PAD) / (W - PAD * 2)) * 100}%`,
            transform: "translateX(-50%)",
          }}
        >
          {new Date(hovered.date + "T12:00:00").toLocaleDateString("en-US", {
            month: "short",
            day: "numeric",
          })}
          : {hovered.count}
        </div>
      )}
    </div>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────

interface Props {
  data: AiSearchPerformance;
  /** Passed through for QA telemetry only */
  brandId?: string | null;
  siteTagDaysActive?: number | null;
}

export function AiSearchPerformancePanel({ data, brandId, siteTagDaysActive }: Props) {
  useEffect(() => {
    console.log("[audit-ui] aiSection rendered:", {
      brandId,
      totalReferrals: data.totalReferrals30d,
    });
  }, [brandId, data.totalReferrals30d]);

  const totalEngineCount = data.topEngines.reduce((s, e) => s + e.count, 0);
  const showRevenue = data.estimatedAttributedRevenue > 0;

  return (
    <div className="rounded-2xl overflow-hidden shadow-xl bg-gradient-to-br from-slate-900 via-indigo-950 to-slate-900">
      {/* ── Header ── */}
      <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="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75" />
            <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500" />
          </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>

      {/* ── Narrative ── */}
      {data.narrative && (
        <p className="px-6 pt-2 pb-1 text-sm text-indigo-100/65 leading-relaxed max-w-3xl">
          {data.narrative}
        </p>
      )}

      {/* ── Metrics grid: hero number | engine bars ── */}
      <div className="grid sm:grid-cols-2 mt-4 border-t border-white/10">
        {/* Hero stat */}
        <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="text-7xl sm:text-8xl font-black tabular-nums text-white leading-none tracking-tight">
              {data.totalReferrals30d.toLocaleString()}
            </div>
            {data.trendVsTrailing90d != null && (
              <div className="mt-4 flex items-center gap-2.5">
                <TrendBadge pct={data.trendVsTrailing90d} />
                <span className="text-[11px] text-indigo-200/40">vs prior 60 days</span>
              </div>
            )}
            {data.referralsByDay && data.referralsByDay.length > 1 && (
              <ReferralSparkline data={data.referralsByDay} />
            )}
            {siteTagDaysActive != null && (
              <p className="text-[10px] text-indigo-300/35 mt-3">
                Based on {siteTagDaysActive} day{siteTagDaysActive === 1 ? "" : "s"} of Site Tag data
              </p>
            )}
          </div>
          {showRevenue && (
            <div className="mt-8 pt-5 border-t border-white/10">
              <p className="text-[10px] font-semibold uppercase tracking-widest text-indigo-300/60 mb-1.5">
                Attributed revenue
              </p>
              <p className="text-3xl font-bold tabular-nums text-emerald-400 leading-none">
                {nmoney(data.estimatedAttributedRevenue)}
              </p>
            </div>
          )}
        </div>

        {/* Engine breakdown */}
        <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 · last 30 days
          </p>
          {data.topEngines.length === 0 ? (
            <p className="text-xs text-indigo-200/35">No engine data yet</p>
          ) : (
            <div className="space-y-3.5">
              {data.topEngines.map((e) => {
                const pct =
                  totalEngineCount > 0 ? (e.count / totalEngineCount) * 100 : 0;
                return (
                  <div key={e.engine} className="flex items-center gap-3">
                    <span className="text-sm text-indigo-100/70 w-28 shrink-0 truncate font-medium">
                      {engineLabel(e.engine)}
                    </span>
                    <div className="flex-1 bg-white/10 rounded-full h-1.5 overflow-hidden">
                      <div
                        className="h-full rounded-full bg-indigo-400 transition-all"
                        style={{ width: `${pct.toFixed(1)}%` }}
                      />
                    </div>
                    <span className="text-sm tabular-nums text-indigo-100/55 w-10 text-right shrink-0 font-semibold">
                      {e.count.toLocaleString()}
                    </span>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* ── Top attributed pages ── */}
      {data.topAttributedPages.length > 0 && (
        <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>
          <div className="overflow-x-auto -mx-1 px-1">
            <table className="w-full text-xs min-w-[320px]">
              <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 whitespace-nowrap">AI Visits</th>
                  <th className="text-right font-medium pb-2.5 pl-3 whitespace-nowrap">Conversions</th>
                </tr>
              </thead>
              <tbody>
                {data.topAttributedPages.map((p, i) => (
                  <tr
                    key={p.url}
                    className={`text-indigo-100/65 ${i < data.topAttributedPages.length - 1 ? "border-b border-white/5" : ""}`}
                  >
                    <td className="py-2.5 pr-6 font-mono text-[11px] text-indigo-200/70" title={p.url}>
                      {urlPath(p.url)}
                    </td>
                    <td className="py-2.5 px-3 text-right tabular-nums font-medium">{p.aiVisits.toLocaleString()}</td>
                    <td className="py-2.5 pl-3 text-right tabular-nums">
                      {p.conversions > 0 ? (
                        <span className="text-emerald-400/90 font-semibold">{p.conversions}</span>
                      ) : (
                        <span className="text-indigo-100/25">—</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
