"use client";

import { useState, useEffect, useCallback, Fragment } from "react";
import { useBrand } from "@/context/brand-context";
import FeatureGate from "@/components/plan/feature-gate";
import {
  DollarSign, TrendingUp, Users, Target, BarChart3, Eye,
  ArrowUpRight, MousePointerClick, Layers, GitBranch,
  UserCheck, Home, Zap, AlertTriangle, Plug, ExternalLink,
  Smartphone, Calendar, Clock, Percent, ArrowRight,
} from "lucide-react";

type TabKey = "overview" | "attribution" | "visitors" | "campaigns" | "clusters" | "reconciliation";
const TABS: Array<{ id: TabKey; label: string }> = [
  { id: "overview", label: "Overview" },
  { id: "attribution", label: "Attribution" },
  { id: "visitors", label: "Visitor Journeys" },
  { id: "campaigns", label: "Campaigns" },
  { id: "clusters", label: "Audience Clusters" },
  { id: "reconciliation", label: "Ad vs Reality" },
];
type Range = "7d" | "28d" | "90d";
const RANGES: Array<{ id: Range; label: string }> = [
  { id: "7d", label: "7d" }, { id: "28d", label: "28d" }, { id: "90d", label: "90d" },
];

export default function PaidMediaPageGated() {
  return (
    <FeatureGate feature="paid_media">
      <PaidMediaPage />
    </FeatureGate>
  );
}

function PaidMediaPage() {
  const { brand } = useBrand();
  const [tab, setTab] = useState<TabKey>("overview");
  const [range, setRange] = useState<Range>("28d");
  const [data, setData] = useState<Record<string, unknown> | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!brand?.id) return;
    if (!brand?.id) return;
    setLoading(true);
    setError(null);
    try {
      const ep = tab === "overview" ? "overview" : tab === "attribution" ? "attribution"
        : tab === "visitors" ? "visitors" : tab === "campaigns" ? "campaigns"
        : tab === "clusters" ? "households" : "reconciliation";
      const res = await fetch(`/api/paid-media/${ep}?brandId=${brand.id}&range=${range}`);
      if (!res.ok) throw new Error(`${res.status}`);
      setData(await res.json());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load");
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [brand?.id, tab, range]);

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

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Paid Media Intelligence</h1>
          <p className="text-sm text-slate-500 mt-1">Multi-touch attribution · Paid vs organic · Ad-spend reconciliation</p>
        </div>
        <div className="inline-flex bg-slate-100 rounded-lg p-0.5">
          {RANGES.map((r) => (
            <button key={r.id} onClick={() => setRange(r.id)}
              className={`px-2.5 py-1 text-[11px] font-semibold rounded-md transition-colors ${range === r.id ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"}`}
            >{r.label}</button>
          ))}
        </div>
      </div>

      <div className="border-b border-slate-200">
        <nav className="flex gap-6 -mb-px">
          {TABS.map((t) => (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === t.id ? "border-brand-600 text-brand-600" : "border-transparent text-slate-500 hover:text-slate-700"}`}
            >{t.label}</button>
          ))}
        </nav>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-24">
          <div className="w-6 h-6 border-2 border-brand-600 border-t-transparent rounded-full animate-spin" />
          <span className="ml-3 text-sm text-slate-500">Loading…</span>
        </div>
      ) : error ? (
        <ErrorBanner message={error} onRetry={load} />
      ) : data && (
        <>
          {tab === "overview" && <OverviewTab data={data} />}
          {tab === "attribution" && <AttributionTab data={data} />}
          {tab === "visitors" && <VisitorsTab data={data} />}
          {tab === "campaigns" && <CampaignsTab data={data} />}
          {tab === "clusters" && <ClustersTab data={data} />}
          {tab === "reconciliation" && <ReconciliationTab data={data} />}
        </>
      )}
    </div>
  );
}

// ─── Shared components ──────────────────────────────────────────

function KPI({ icon: Icon, label, value, sub, accent = "text-brand-600" }: {
  icon: typeof DollarSign; label: string; value: string; sub?: string; accent?: string;
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
      <div className="flex items-center gap-2 mb-1">
        <Icon className={`w-4 h-4 ${accent}`} />
        <span className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">{label}</span>
      </div>
      <p className="text-2xl font-bold text-slate-900 tabular-nums">{value}</p>
      {sub && <p className="text-[11px] text-slate-500 mt-0.5">{sub}</p>}
    </div>
  );
}

function Empty({ icon: Icon, title, desc, cta }: {
  icon: typeof DollarSign; title: string; desc: string;
  cta?: { label: string; href: string };
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
      <Icon className="w-10 h-10 text-slate-200 mx-auto mb-3" />
      <h2 className="text-lg font-bold text-slate-900 mb-1">{title}</h2>
      <p className="text-sm text-slate-500 max-w-md mx-auto">{desc}</p>
      {cta && (
        <a href={cta.href} className="inline-flex items-center gap-1.5 mt-4 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-semibold hover:bg-brand-700">
          <Plug className="w-4 h-4" /> {cta.label}
        </a>
      )}
    </div>
  );
}

function ErrorBanner({ message, onRetry }: { message: string; onRetry: () => void }) {
  return (
    <div className="bg-red-50 border border-red-200 rounded-xl px-5 py-4 flex items-start gap-3">
      <AlertTriangle className="w-5 h-5 text-red-500 mt-0.5 shrink-0" />
      <div>
        <p className="text-sm font-semibold text-red-900">Failed to load</p>
        <p className="text-xs text-red-700 mt-1">{message}</p>
        <button onClick={onRetry} className="text-xs font-semibold text-red-700 underline mt-2">Retry</button>
      </div>
    </div>
  );
}

function ChannelDot({ paid }: { paid: boolean }) {
  return <span className={`inline-block w-2 h-2 rounded-full shrink-0 ${paid ? "bg-amber-500" : "bg-emerald-500"}`} />;
}

function fmt(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 10_000) return `${(n / 1_000).toFixed(1)}K`;
  return n.toLocaleString();
}

// ─── OVERVIEW TAB ───────────────────────────────────────────────

function OverviewTab({ data: d }: { data: Record<string, unknown> }) {
  const totals = (d.totals ?? {}) as { sessions?: number; conversions?: number; conversionRate?: number; paidShareOfConversions?: number; organicShareOfConversions?: number; assistedShareOfConversions?: number };
  const paid = (d.paidChannels ?? {}) as { totalSessions?: number; totalConversions?: number; spend?: number; roas?: number; cpc?: number; cpl?: number; channels?: Array<{ channel: string; sessions: number; conversions: number; spend: number }> };
  const organic = (d.organicChannels ?? {}) as { totalSessions?: number; totalConversions?: number; channels?: Array<{ channel: string; sessions: number; conversions: number }> };
  const assisted = (d.assistedConversions ?? {}) as { total?: number; paidAssistedOrganic?: number; organicAssistedPaid?: number; avgTouchpoints?: number };

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KPI icon={Users} label="Total Sessions" value={fmt(totals.sessions ?? 0)} />
        <KPI icon={TrendingUp} label="Conversions" value={fmt(totals.conversions ?? 0)} accent="text-emerald-600" />
        <KPI icon={Percent} label="Conv Rate" value={`${totals.conversionRate ?? 0}%`} />
        <KPI icon={GitBranch} label="Avg Touchpoints" value={String(assisted.avgTouchpoints ?? 0)} sub="sessions before conversion" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-slate-200 p-5 space-y-3">
          <div className="flex items-center gap-2">
            <ChannelDot paid />
            <h3 className="font-bold text-slate-800 text-sm">Paid Channels</h3>
          </div>
          <div className="grid grid-cols-3 gap-2 text-center">
            <div><p className="text-lg font-bold tabular-nums">{fmt(paid.totalSessions ?? 0)}</p><p className="text-[10px] text-slate-400 uppercase">Sessions</p></div>
            <div><p className="text-lg font-bold tabular-nums text-emerald-600">{paid.totalConversions ?? 0}</p><p className="text-[10px] text-slate-400 uppercase">Conv</p></div>
            <div><p className="text-lg font-bold tabular-nums">{(totals.paidShareOfConversions ?? 0)}%</p><p className="text-[10px] text-slate-400 uppercase">Share</p></div>
          </div>
          {(paid.spend ?? 0) > 0 ? (
            <div className="text-xs text-slate-600 space-y-0.5 border-t border-slate-100 pt-2">
              <p>Spend: <span className="font-semibold">${fmt(paid.spend ?? 0)}</span> · ROAS: <span className="font-semibold">{paid.roas ?? 0}x</span></p>
              <p>CPC: ${paid.cpc ?? 0} · CPL: ${paid.cpl ?? 0}</p>
            </div>
          ) : (
            <p className="text-[11px] text-slate-400 border-t border-slate-100 pt-2">Connect an ad platform for spend + ROAS data</p>
          )}
          {paid.channels && paid.channels.length > 0 && (
            <div className="space-y-1">{paid.channels.map((c) => (
              <div key={c.channel} className="flex items-center justify-between text-xs">
                <span className="text-slate-600">{c.channel}</span>
                <span className="tabular-nums font-semibold">{c.sessions} sess · {c.conversions} conv</span>
              </div>
            ))}</div>
          )}
        </div>

        <div className="bg-white rounded-xl border border-slate-200 p-5 space-y-3">
          <div className="flex items-center gap-2">
            <ChannelDot paid={false} />
            <h3 className="font-bold text-slate-800 text-sm">Organic Channels</h3>
          </div>
          <div className="grid grid-cols-3 gap-2 text-center">
            <div><p className="text-lg font-bold tabular-nums">{fmt(organic.totalSessions ?? 0)}</p><p className="text-[10px] text-slate-400 uppercase">Sessions</p></div>
            <div><p className="text-lg font-bold tabular-nums text-emerald-600">{organic.totalConversions ?? 0}</p><p className="text-[10px] text-slate-400 uppercase">Conv</p></div>
            <div><p className="text-lg font-bold tabular-nums">{(totals.organicShareOfConversions ?? 0)}%</p><p className="text-[10px] text-slate-400 uppercase">Share</p></div>
          </div>
          {organic.channels && organic.channels.length > 0 && (
            <div className="space-y-1 border-t border-slate-100 pt-2">{organic.channels.map((c) => (
              <div key={c.channel} className="flex items-center justify-between text-xs">
                <span className="text-slate-600">{c.channel}</span>
                <span className="tabular-nums font-semibold">{c.sessions} sess · {c.conversions} conv</span>
              </div>
            ))}</div>
          )}
        </div>

        <div className="bg-white rounded-xl border border-slate-200 p-5 space-y-3">
          <div className="flex items-center gap-2">
            <GitBranch className="w-4 h-4 text-violet-600" />
            <h3 className="font-bold text-slate-800 text-sm">Assisted Conversions</h3>
          </div>
          {(assisted.total ?? 0) > 0 ? (
            <>
              <p className="text-3xl font-bold tabular-nums text-violet-700">{assisted.total}</p>
              <p className="text-[10px] text-slate-400 uppercase">{totals.assistedShareOfConversions ?? 0}% of conversions</p>
              <div className="text-xs text-slate-600 space-y-1 border-t border-slate-100 pt-2">
                <p><span className="font-semibold text-amber-700">{assisted.paidAssistedOrganic ?? 0}</span> paid assisted organic — saw an ad, converted organically</p>
                <p><span className="font-semibold text-emerald-700">{assisted.organicAssistedPaid ?? 0}</span> organic assisted paid — found you organically, converted through paid</p>
              </div>
            </>
          ) : (
            <>
              <p className="text-3xl font-bold tabular-nums text-slate-300">—</p>
              <p className="text-xs text-slate-500 border-t border-slate-100 pt-2">
                Assist tracking active — no cross-channel paths detected in this window.
              </p>
              <p className="text-[11px] text-slate-400">
                Assists appear when the same visitor converts via both paid and organic channels within the date range.
              </p>
            </>
          )}
        </div>
      </div>

      {(totals.conversions ?? 0) === 0 && (
        <Empty icon={Layers} title="No conversion data yet" desc="Conversions will appear as visitors interact with your site. Run the paid-media rebuild cron to compute attribution paths from existing data." />
      )}
    </div>
  );
}

// ─── ATTRIBUTION TAB ────────────────────────────────────────────

function AttributionTab({ data: d }: { data: Record<string, unknown> }) {
  const totalPaths = (d.totalPaths ?? 0) as number;
  const avgTP = (d.avgTouchpoints ?? 0) as number;
  const avgDays = (d.avgDaysToConvert ?? 0) as number;
  const assisted = (d.assisted ?? {}) as { total?: number; paidAssistedOrganic?: number; organicAssistedPaid?: number };
  const paths = (d.paths ?? []) as Array<{
    conversionType: string; touchpointCount: number; daysBetweenFirstAndConversion: number;
    touchpoints: Array<{ channel: string; timestamp: string }>;
  }>;
  const firstTouch = (d.firstTouchSummary ?? {}) as Record<string, { conversions: number; revenue: number }>;
  const lastTouch = (d.lastTouchSummary ?? {}) as Record<string, { conversions: number; revenue: number }>;

  if (totalPaths === 0) return <Empty icon={GitBranch} title="No attribution paths yet" desc="Run POST /api/paid-media/attribution?brandId=... to build paths from existing conversions, or wait for the daily cron." />;

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KPI icon={GitBranch} label="Attribution Paths" value={fmt(totalPaths)} />
        <KPI icon={MousePointerClick} label="Avg Touchpoints" value={String(avgTP)} sub="sessions before conversion" />
        <KPI icon={Clock} label="Avg Days to Convert" value={String(avgDays)} />
        <KPI icon={Layers} label="Assisted Conversions" value={String(assisted.total ?? 0)} accent="text-violet-600" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <ChannelTable title="First-Touch Attribution" summary={firstTouch} />
        <ChannelTable title="Last-Touch Attribution" summary={lastTouch} />
      </div>

      <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">
          <GitBranch className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Recent Conversion Paths</h3>
        </div>
        <div className="divide-y divide-slate-100 max-h-96 overflow-y-auto">
          {paths.slice(0, 20).map((p, i) => (
            <div key={i} className="px-5 py-3">
              <div className="flex items-center gap-1.5 flex-wrap">
                {p.touchpoints.map((tp, j) => (
                  <span key={j} className="inline-flex items-center gap-1">
                    <span className={`text-[11px] font-semibold px-2 py-0.5 rounded-full border ${j === p.touchpoints.length - 1 ? "bg-emerald-50 border-emerald-200 text-emerald-700" : "bg-slate-50 border-slate-200 text-slate-600"}`}>
                      {tp.channel}
                    </span>
                    {j < p.touchpoints.length - 1 && <ArrowRight className="w-3 h-3 text-slate-300" />}
                  </span>
                ))}
              </div>
              <p className="text-[10px] text-slate-400 mt-1">{p.conversionType.replace(/_/g, " ")} · {p.touchpointCount} touchpoints · {p.daysBetweenFirstAndConversion}d</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ChannelTable({ title, summary }: { title: string; summary: Record<string, { conversions: number; revenue: number }> }) {
  const rows = Object.entries(summary).sort(([, a], [, b]) => b.conversions - a.conversions);
  if (rows.length === 0) return null;
  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-5 py-3 border-b border-slate-100"><h3 className="font-bold text-slate-800 text-sm">{title}</h3></div>
      <table className="w-full text-sm">
        <thead><tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
          <th className="px-5 py-2">Channel</th><th className="px-5 py-2 text-right">Conv</th><th className="px-5 py-2 text-right">Revenue</th>
        </tr></thead>
        <tbody className="divide-y divide-slate-100">{rows.map(([ch, d]) => (
          <tr key={ch} className="hover:bg-slate-50">
            <td className="px-5 py-2 font-medium text-slate-800">{ch}</td>
            <td className="px-5 py-2 text-right tabular-nums">{d.conversions}</td>
            <td className="px-5 py-2 text-right tabular-nums text-slate-500">${Math.round(d.revenue).toLocaleString()}</td>
          </tr>
        ))}</tbody>
      </table>
    </div>
  );
}

// ─── VISITOR JOURNEYS TAB ───────────────────────────────────────

const PAID_CH = new Set(["Paid Search", "Paid Social", "Display", "OTT/CTV"]);

function VisitorsTab({ data: d }: { data: Record<string, unknown> }) {
  const summary = (d.summary ?? {}) as { total?: number; returning?: number; converted?: number; avgSessionsPerVisitor?: number };
  const visitors = (d.visitors ?? []) as Array<{
    visitorId: string; totalSessions: number; totalConversions: number;
    firstSeenAt: string; lastSeenAt: string;
    devices: Array<{ device?: string; browser?: string }>;
    channelHistory: Array<{ channel: string; source?: string; date?: string }>;
    conversionHistory: Array<{ type: string; pageUrl: string; date: string; value?: number }>;
  }>;

  if ((summary.total ?? 0) === 0) return <Empty icon={Users} title="No visitor profiles yet" desc="Profiles build automatically from session + conversion data. Run the paid-media rebuild cron to populate." />;

  // Visitors with multi-channel or multi-conversion journeys worth showing
  const journeyVisitors = visitors.filter((v) =>
    (v.conversionHistory?.length ?? 0) >= 2 ||
    [...new Set((v.channelHistory ?? []).map((c) => c.channel))].length >= 2
  );

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KPI icon={Users} label="Visitors" value={fmt(summary.total ?? 0)} />
        <KPI icon={UserCheck} label="Returning" value={fmt(summary.returning ?? 0)} sub="2+ sessions" accent="text-violet-600" />
        <KPI icon={TrendingUp} label="Converted" value={fmt(summary.converted ?? 0)} accent="text-emerald-600" />
        <KPI icon={BarChart3} label="Avg Sessions" value={String(summary.avgSessionsPerVisitor ?? 0)} sub="per visitor" />
      </div>

      {/* Multi-touch journey paths */}
      <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 justify-between">
          <div>
            <h3 className="font-bold text-slate-800 text-sm">Multi-Touch Journey Paths</h3>
            {journeyVisitors.length > 0 && (
              <p className="text-[11px] text-slate-400 mt-0.5">{journeyVisitors.length} visitor{journeyVisitors.length !== 1 ? "s" : ""} with cross-channel or multi-conversion paths</p>
            )}
          </div>
          <GitBranch className="w-4 h-4 text-violet-400" />
        </div>
        {journeyVisitors.length > 0 ? (
          <div className="divide-y divide-slate-100">
            {journeyVisitors.slice(0, 25).map((v) => {
              // Merge channel sessions + conversion events sorted chronologically
              const events: Array<{ date: string; kind: "session" | "conversion"; label: string; paid?: boolean }> = [
                ...(v.channelHistory ?? []).map((c) => ({
                  date: c.date ?? "",
                  kind: "session" as const,
                  label: c.channel,
                  paid: PAID_CH.has(c.channel),
                })),
                ...(v.conversionHistory ?? []).map((c) => ({
                  date: c.date,
                  kind: "conversion" as const,
                  label: c.type,
                })),
              ].sort((a, b) => a.date.localeCompare(b.date));

              return (
                <div key={v.visitorId} className="px-5 py-3 flex items-start gap-3">
                  <span className="font-mono text-[10px] text-slate-400 shrink-0 mt-0.5 w-20 truncate">{v.visitorId.slice(0, 10)}…</span>
                  <div className="flex items-center gap-1 flex-wrap flex-1 min-w-0">
                    {events.map((e, i) => (
                      <Fragment key={i}>
                        {i > 0 && <ArrowRight className="w-3 h-3 text-slate-300 shrink-0" />}
                        {e.kind === "session" ? (
                          <span className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${e.paid ? "bg-amber-50 text-amber-700" : "bg-blue-50 text-blue-700"}`}>
                            {e.label}
                          </span>
                        ) : (
                          <span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 font-medium">
                            ✓ {e.label}
                          </span>
                        )}
                      </Fragment>
                    ))}
                  </div>
                  <span className="text-[10px] text-slate-400 shrink-0">{v.totalConversions} conv</span>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="px-5 py-8 text-center">
            <p className="text-sm font-semibold text-slate-500">No multi-touch paths in this window</p>
            <p className="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
              Paths appear when the same visitor converts via both paid and organic channels, or converts more than once.
            </p>
          </div>
        )}
      </div>

      {/* Full visitor profiles table */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100"><h3 className="font-bold text-slate-800 text-sm">Visitor Profiles</h3></div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead><tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
              <th className="px-5 py-2">Visitor</th><th className="px-5 py-2 text-right">Sessions</th><th className="px-5 py-2 text-right">Conv</th>
              <th className="px-5 py-2">Channels</th><th className="px-5 py-2">Devices</th><th className="px-5 py-2">Last Seen</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-100">{visitors.slice(0, 50).map((v) => (
              <tr key={v.visitorId} className="hover:bg-slate-50">
                <td className="px-5 py-2 font-mono text-xs text-slate-500 truncate max-w-[100px]">{v.visitorId.slice(0, 12)}…</td>
                <td className="px-5 py-2 text-right tabular-nums">{v.totalSessions}</td>
                <td className="px-5 py-2 text-right tabular-nums font-semibold text-emerald-700">{v.totalConversions}</td>
                <td className="px-5 py-2"><div className="flex gap-1 flex-wrap">{[...new Set((v.channelHistory ?? []).map((c) => c.channel))].slice(0, 3).map((ch) => (
                  <span key={ch} className="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-600">{ch}</span>
                ))}</div></td>
                <td className="px-5 py-2"><div className="flex gap-1">{(v.devices ?? []).slice(0, 2).map((dv, i) => (
                  <span key={i} className="text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-700">{dv.device ?? "?"}</span>
                ))}</div></td>
                <td className="px-5 py-2 text-xs text-slate-500">{new Date(v.lastSeenAt).toLocaleDateString()}</td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── CAMPAIGNS TAB ──────────────────────────────────────────────

function CampaignsTab({ data: d }: { data: Record<string, unknown> }) {
  if (!(d.connected as boolean)) {
    return (
      <div className="space-y-6">
        <Empty icon={Target} title="Connect Your Ad Platforms" desc="Link Google Ads, Meta, LinkedIn, or TikTok to see campaign performance with Site Tag-verified conversions."
          cta={{ label: "Go to Integrations", href: "/integrations" }} />
        <div className="flex justify-center gap-3">
          {["Google Ads", "Meta", "LinkedIn", "TikTok"].map((p) => (
            <a key={p} href="/integrations" className="px-4 py-2 rounded-lg border border-slate-200 bg-white text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center gap-1.5">
              <ExternalLink className="w-3.5 h-3.5" /> {p}
            </a>
          ))}
        </div>
      </div>
    );
  }

  const campaigns = (d.campaigns ?? []) as Array<{ campaignName: string; platform: string; impressions: number; clicks: number; spend: number; platformConversions: number }>;
  const summary = (d.summary ?? {}) as { totalCampaigns?: number; totalSpend?: number; totalClicks?: number; totalImpressions?: number };

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KPI icon={Target} label="Campaigns" value={String(summary.totalCampaigns ?? 0)} />
        <KPI icon={DollarSign} label="Total Spend" value={`$${fmt(summary.totalSpend ?? 0)}`} accent="text-amber-600" />
        <KPI icon={MousePointerClick} label="Clicks" value={fmt(summary.totalClicks ?? 0)} />
        <KPI icon={Eye} label="Impressions" value={fmt(summary.totalImpressions ?? 0)} />
      </div>
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100"><h3 className="font-bold text-slate-800 text-sm">Campaign Performance</h3></div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead><tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
              <th className="px-5 py-2">Campaign</th><th className="px-5 py-2">Platform</th>
              <th className="px-5 py-2 text-right">Impr</th><th className="px-5 py-2 text-right">Clicks</th>
              <th className="px-5 py-2 text-right">Spend</th><th className="px-5 py-2 text-right">Conv</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-100">{campaigns.map((c) => (
              <tr key={c.campaignName + c.platform} className="hover:bg-slate-50">
                <td className="px-5 py-2 font-medium text-slate-800 truncate max-w-[200px]">{c.campaignName}</td>
                <td className="px-5 py-2 text-xs capitalize text-slate-500">{c.platform.replace(/_/g, " ")}</td>
                <td className="px-5 py-2 text-right tabular-nums">{fmt(c.impressions)}</td>
                <td className="px-5 py-2 text-right tabular-nums">{fmt(c.clicks)}</td>
                <td className="px-5 py-2 text-right tabular-nums">${Math.round(c.spend).toLocaleString()}</td>
                <td className="px-5 py-2 text-right tabular-nums font-semibold text-emerald-700">{c.platformConversions}</td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── AUDIENCE CLUSTERS TAB ──────────────────────────────────────

function ClustersTab({ data: d }: { data: Record<string, unknown> }) {
  const summary = (d.summary ?? {}) as { total?: number; multiDevice?: number; converting?: number; avgVisitorsPerCluster?: number };
  const clusters = (d.clusters ?? []) as Array<{
    ipSubnet: string; city?: string; region?: string; deviceCount: number;
    sessionCount: number; conversionCount: number; confidence: string; visitorIds: string[];
  }>;

  if ((summary.total ?? 0) === 0) return <Empty icon={Home} title="No audience clusters yet" desc="Clusters form automatically as visitors return from shared network subnets. Run the paid-media rebuild cron to populate." />;

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KPI icon={Home} label="Clusters" value={fmt(summary.total ?? 0)} />
        <KPI icon={Smartphone} label="Multi-Device" value={fmt(summary.multiDevice ?? 0)} sub="2+ devices" accent="text-violet-600" />
        <KPI icon={TrendingUp} label="Converting" value={fmt(summary.converting ?? 0)} accent="text-emerald-600" />
        <KPI icon={Users} label="Avg Visitors" value={String(summary.avgVisitorsPerCluster ?? 0)} sub="per cluster" />
      </div>
      <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">
          <Home className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Top Audience Clusters</h3>
        </div>
        <table className="w-full text-sm">
          <thead><tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
            <th className="px-5 py-2">Location</th><th className="px-5 py-2 text-right">Visitors</th>
            <th className="px-5 py-2 text-right">Devices</th><th className="px-5 py-2 text-right">Sessions</th>
            <th className="px-5 py-2 text-right">Conv</th><th className="px-5 py-2">Confidence</th>
          </tr></thead>
          <tbody className="divide-y divide-slate-100">{clusters.slice(0, 30).map((c) => (
            <tr key={c.ipSubnet + (c.city ?? "")} className="hover:bg-slate-50">
              <td className="px-5 py-2"><span className="font-medium text-slate-800">{c.city ?? "Unknown"}</span>{c.region && <span className="text-xs text-slate-400 ml-1">{c.region}</span>}</td>
              <td className="px-5 py-2 text-right tabular-nums">{(c.visitorIds ?? []).length}</td>
              <td className="px-5 py-2 text-right tabular-nums">{c.deviceCount}</td>
              <td className="px-5 py-2 text-right tabular-nums">{c.sessionCount}</td>
              <td className="px-5 py-2 text-right tabular-nums font-semibold text-emerald-700">{c.conversionCount}</td>
              <td className="px-5 py-2"><span className={`text-[10px] font-bold uppercase px-2 py-0.5 rounded-full ${c.confidence === "high" ? "bg-emerald-50 text-emerald-700" : c.confidence === "medium" ? "bg-amber-50 text-amber-700" : "bg-slate-100 text-slate-500"}`}>{c.confidence}</span></td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    </div>
  );
}

// ─── AD VS REALITY TAB ──────────────────────────────────────────

function ReconciliationTab({ data: d }: { data: Record<string, unknown> }) {
  if (!(d.connected as boolean)) {
    return (
      <div className="space-y-6">
        <Empty icon={Zap} title="Connect Your Ad Platforms" desc="Link an ad platform to compare their claimed conversions against what the Site Tag actually measured on your site."
          cta={{ label: "Go to Integrations", href: "/integrations" }} />
        <div className="flex justify-center gap-3">
          {["Google Ads", "Meta", "LinkedIn"].map((p) => (
            <a key={p} href="/integrations" className="px-4 py-2 rounded-lg border border-slate-200 bg-white text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center gap-1.5">
              <ExternalLink className="w-3.5 h-3.5" /> {p}
            </a>
          ))}
        </div>
      </div>
    );
  }

  const claimed = (d.overallClaimed ?? 0) as number;
  const verified = (d.overallVerified ?? 0) as number;
  const gap = (d.overallDiscrepancy ?? 0) as number;
  const byPlatform = (d.byPlatform ?? []) as Array<{ platform: string; platformClaimed: number; siteTagVerified: number; discrepancy: number; discrepancyPct: number }>;

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
        <KPI icon={BarChart3} label="Platform Claims" value={fmt(claimed)} sub="What ad platforms report" accent="text-amber-600" />
        <KPI icon={Zap} label="Site Tag Verified" value={fmt(verified)} sub="What actually happened" accent="text-emerald-600" />
        <KPI icon={gap > 0 ? ArrowUpRight : Target} label="Discrepancy" value={`${gap > 0 ? "+" : ""}${gap}`} sub={claimed > 0 ? `${Math.round((gap / claimed) * 100)}% gap` : "—"} accent={gap > 0 ? "text-red-600" : "text-emerald-600"} />
      </div>
      {byPlatform.length > 0 && (
        <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">
            <Zap className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Ad vs Reality by Platform</h3>
          </div>
          <table className="w-full text-sm">
            <thead><tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400">
              <th className="px-5 py-2">Platform</th><th className="px-5 py-2 text-right">Claimed</th>
              <th className="px-5 py-2 text-right">Verified</th><th className="px-5 py-2 text-right">Gap</th><th className="px-5 py-2 text-right">Gap %</th>
            </tr></thead>
            <tbody className="divide-y divide-slate-100">{byPlatform.map((p) => (
              <tr key={p.platform} className="hover:bg-slate-50">
                <td className="px-5 py-2 font-medium text-slate-800 capitalize">{p.platform.replace(/_/g, " ")}</td>
                <td className="px-5 py-2 text-right tabular-nums text-amber-700">{p.platformClaimed}</td>
                <td className="px-5 py-2 text-right tabular-nums text-emerald-700 font-semibold">{p.siteTagVerified}</td>
                <td className="px-5 py-2 text-right tabular-nums text-red-600">{p.discrepancy > 0 ? "+" : ""}{p.discrepancy}</td>
                <td className="px-5 py-2 text-right tabular-nums text-red-600">{p.discrepancyPct}%</td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      )}
    </div>
  );
}
