"use client";

/**
 * Admin → Platform Analytics → Data Moat
 *
 * The cumulative first-party data advantage. Every metric here is
 * a number a competitor would have to spend money + time to
 * replicate — useful for investor + pricing conversations and for
 * answering "what does meSEO know that GA4 doesn't?".
 */

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Database, ArrowLeft, Loader2, AlertTriangle, RefreshCw,
  Activity, Users as UsersIcon, MousePointerClick, FileSearch,
  Search, Sparkles, Shield,
} from "lucide-react";
import {
  PageHeader, SectionHeader, Card, CardHeader, EmptyState, Sparkline,
} from "@/components/admin";

interface Volumes {
  trackedEvents: number; trackedSessions: number; siteConversions: number;
  pagesCrawled: number; keywordsTracked: number; aiInteractions: number;
  growthPerDay: { trackedEvents: number; trackedSessions: number; siteConversions: number; aiInteractions: number };
}
interface DailyPoint { date: string; count: number }
interface CumulativePoint { date: string; total: number }
interface BrandRow {
  brandId: string; name: string; events: number; sessions: number;
  conversions: number; pagesCrawled: number; keywords: number;
  daysOfData: number; richnessScore: number;
}
interface MoatMetrics {
  firstPartyEventsGa4Cant: number;
  bookingFunnelInteractions: number;
  pluginsDetected: number;
  brandsWithPlugins: number;
  realUserCwv: number;
}
interface Payload {
  scope: { generatedAt: string };
  volumes: Volumes;
  growth: { eventsByDay: DailyPoint[]; cumulative: CumulativePoint[]; doubleDays: number | null };
  perBrand: BrandRow[];
  moat: MoatMetrics;
}

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

export default function DataMoatPage() {
  const [data, setData] = useState<Payload | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [retryKey, setRetryKey] = useState(0);

  useEffect(() => {
    setError(null);
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 15_000);
    fetch("/api/admin/analytics/data-moat", { signal: controller.signal })
      .then(async (r) => {
        if (!r.ok) {
          let msg = `HTTP ${r.status}`;
          try { const body = await r.json(); if (body?.error) msg = `${msg}: ${body.error}`; } catch {}
          throw new Error(msg);
        }
        return r.json() as Promise<Payload>;
      })
      .then(setData)
      .catch((err: Error) => {
        if (err.name === "AbortError") setError("Request timed out after 15s — try Retry.");
        else setError(err.message || "Failed to load data moat.");
      })
      .finally(() => clearTimeout(timeoutId));
    return () => { clearTimeout(timeoutId); controller.abort(); };
  }, [retryKey]);

  if (error) {
    return (
      <div className="max-w-2xl mx-auto mt-16">
        <div className="rounded-xl border border-rose-200 bg-rose-50 p-6 text-center">
          <AlertTriangle className="w-8 h-8 text-rose-500 mx-auto mb-2" />
          <h2 className="text-sm font-bold text-slate-900">Couldn&apos;t load Data Moat</h2>
          <p className="text-xs text-slate-600 mt-1">{error}</p>
          <button
            onClick={() => setRetryKey((k) => k + 1)}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 mt-4 rounded-lg bg-white border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50"
          >
            <RefreshCw className="w-3 h-3" /> Retry
          </button>
        </div>
      </div>
    );
  }

  if (!data) {
    return <div className="flex items-center justify-center py-24"><Loader2 className="w-5 h-5 text-slate-400 animate-spin" /></div>;
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Data Moat"
        subtitle="First-party data advantage — what meSEO has captured that no competitor can replicate"
        icon={Database}
        actions={
          <Link href="/admin/analytics" className="inline-flex items-center gap-1 text-[11px] text-slate-600 hover:text-slate-900">
            <ArrowLeft className="w-3 h-3" />Back to Analytics
          </Link>
        }
      />

      {/* Volume hero — six headline numbers + per-day growth */}
      <section>
        <SectionHeader title="Total data volume" />
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          <VolumeCard icon={Activity} label="TrackedEvents" value={fmt(data.volumes.trackedEvents)} sub={`+${fmt(data.volumes.growthPerDay.trackedEvents)}/day`} accent="text-violet-600" bg="bg-violet-50" />
          <VolumeCard icon={UsersIcon} label="TrackedSessions" value={fmt(data.volumes.trackedSessions)} sub={`+${fmt(data.volumes.growthPerDay.trackedSessions)}/day`} accent="text-indigo-600" bg="bg-indigo-50" />
          <VolumeCard icon={MousePointerClick} label="SiteConversions" value={fmt(data.volumes.siteConversions)} sub={`+${fmt(data.volumes.growthPerDay.siteConversions)}/day`} accent="text-emerald-600" bg="bg-emerald-50" />
          <VolumeCard icon={FileSearch} label="Pages crawled" value={fmt(data.volumes.pagesCrawled)} sub="lifetime" accent="text-amber-600" bg="bg-amber-50" />
          <VolumeCard icon={Search} label="Keywords tracked" value={fmt(data.volumes.keywordsTracked)} sub="distinct" accent="text-cyan-600" bg="bg-cyan-50" />
          <VolumeCard icon={Sparkles} label="AI interactions" value={fmt(data.volumes.aiInteractions)} sub={`+${fmt(data.volumes.growthPerDay.aiInteractions)}/day`} accent="text-fuchsia-600" bg="bg-fuchsia-50" />
        </div>
      </section>

      {/* Growth — events per day sparkline + cumulative + doubling */}
      <section>
        <SectionHeader title="Growth"
          right={data.growth.doubleDays != null ? (
            <span className="text-[10px] text-slate-500">
              At current rate, lifetime events double every <span className="font-bold text-slate-800 tabular-nums">{data.growth.doubleDays}</span> days
            </span>
          ) : undefined}
        />
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
          <Card>
            <CardHeader title="Events per day · last 90 days" />
            <div className="px-5 py-4 h-32">
              <Sparkline points={data.growth.eventsByDay.map((d) => d.count)} color="#8B5CF6" variant="area" />
            </div>
            <div className="px-5 py-2 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500 flex items-center justify-between">
              <span>{data.growth.eventsByDay[0]?.date ?? "—"}</span>
              <span className="font-semibold text-slate-700">{fmt(data.growth.eventsByDay.reduce((s, p) => s + p.count, 0))} events in 90 days</span>
              <span>{data.growth.eventsByDay[data.growth.eventsByDay.length - 1]?.date ?? "—"}</span>
            </div>
          </Card>
          <Card>
            <CardHeader title="Cumulative · running total" />
            <div className="px-5 py-4 h-32">
              <Sparkline points={data.growth.cumulative.map((d) => d.total)} color="#10B981" variant="line" />
            </div>
            <div className="px-5 py-2 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500 flex items-center justify-between">
              <span>start</span>
              <span className="font-semibold text-slate-700">{fmt(data.growth.cumulative[data.growth.cumulative.length - 1]?.total ?? 0)} total</span>
              <span>now</span>
            </div>
          </Card>
        </div>
      </section>

      {/* Moat metrics — what GA4 misses */}
      <section>
        <SectionHeader title="Competitive moat" right={<span className="text-[10px] text-slate-400">numbers GA4 / SEMrush / Ahrefs don&apos;t have</span>} />
        <Card>
          <div className="p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <MoatCell
              icon={Shield}
              label="Conversions GA4 doesn't see"
              value={fmt(data.moat.firstPartyEventsGa4Cant)}
              caption="gtag-intercepted + plugin postMessage paths captured by t.js"
              accent="text-emerald-600"
            />
            <MoatCell
              icon={Activity}
              label="Booking funnel interactions"
              value={fmt(data.moat.bookingFunnelInteractions)}
              caption="widget opens + step events + submit + confirm across all brands"
              accent="text-violet-600"
            />
            <MoatCell
              icon={Sparkles}
              label="Plugins auto-detected"
              value={`${data.moat.pluginsDetected} types`}
              caption={`across ${data.moat.brandsWithPlugins} brand${data.moat.brandsWithPlugins === 1 ? "" : "s"}`}
              accent="text-indigo-600"
            />
            <MoatCell
              icon={Database}
              label="Real-user CWV measurements"
              value={fmt(data.moat.realUserCwv)}
              caption="LCP / FID / CLS samples from actual visitors (not lab data)"
              accent="text-cyan-600"
            />
          </div>
          <div className="px-5 py-2.5 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500">
            These numbers compound — every page-load adds to TrackedEvents, every conversion to SiteConversions,
            every audit to PageRecord. A competitor would need to install our Site Tag on every brand's site to
            replicate this dataset, which by definition they can&apos;t.
          </div>
        </Card>
      </section>

      {/* Per-brand depth */}
      <section>
        <SectionHeader title="Per-brand data depth"
          right={<span className="text-[10px] text-slate-400">top {data.perBrand.length} by richness score</span>}
        />
        <Card>
          {data.perBrand.length === 0 ? (
            <EmptyState icon={Database} title="No brand data yet" description="As Site Tags are installed and audits run, this table will populate." />
          ) : (
            <table className="w-full text-xs">
              <thead className="text-[10px] font-bold uppercase tracking-widest text-slate-400 border-b border-slate-100 bg-slate-50/40">
                <tr>
                  <th className="text-left px-4 py-2">Brand</th>
                  <th className="text-right px-4 py-2">Events</th>
                  <th className="text-right px-4 py-2">Sessions</th>
                  <th className="text-right px-4 py-2">Conversions</th>
                  <th className="text-right px-4 py-2">Pages</th>
                  <th className="text-right px-4 py-2">Keywords</th>
                  <th className="text-right px-4 py-2">Days</th>
                  <th className="text-right px-4 py-2">Richness</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {data.perBrand.map((b) => (
                  <tr key={b.brandId} className="hover:bg-slate-50">
                    <td className="px-4 py-2 font-medium text-slate-800 truncate max-w-[260px]">{b.name}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-700">{fmt(b.events)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-700">{fmt(b.sessions)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-700">{fmt(b.conversions)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-700">{fmt(b.pagesCrawled)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-700">{fmt(b.keywords)}</td>
                    <td className="px-4 py-2 text-right tabular-nums text-slate-500">{b.daysOfData}d</td>
                    <td className="px-4 py-2 text-right">
                      <span className={`inline-block px-2 py-0.5 rounded text-[10px] font-bold tabular-nums ${
                        b.richnessScore >= 70 ? "bg-emerald-50 text-emerald-700 border border-emerald-200"
                        : b.richnessScore >= 40 ? "bg-amber-50 text-amber-700 border border-amber-200"
                        : "bg-slate-100 text-slate-600 border border-slate-200"
                      }`}>
                        {b.richnessScore}/100
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Card>
      </section>
    </div>
  );
}

function VolumeCard({
  icon: Icon, label, value, sub, accent, bg,
}: {
  icon: typeof Activity;
  label: string;
  value: string;
  sub: string;
  accent: string;
  bg: string;
}) {
  return (
    <Card>
      <div className="p-4">
        <div className="flex items-center justify-between mb-2">
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</p>
          <span className={`w-6 h-6 rounded-md ${bg} ${accent} flex items-center justify-center`}>
            <Icon className="w-3 h-3" />
          </span>
        </div>
        <p className="text-2xl font-bold text-slate-900 tabular-nums leading-tight">{value}</p>
        <p className="text-[10px] text-slate-500 mt-0.5">{sub}</p>
      </div>
    </Card>
  );
}

function MoatCell({
  icon: Icon, label, value, caption, accent,
}: {
  icon: typeof Activity;
  label: string;
  value: string;
  caption: string;
  accent: string;
}) {
  return (
    <div>
      <div className="flex items-center gap-1.5 mb-1">
        <Icon className={`w-3.5 h-3.5 ${accent}`} />
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</p>
      </div>
      <p className={`text-2xl font-bold tabular-nums ${accent}`}>{value}</p>
      <p className="text-[11px] text-slate-500 mt-1 leading-relaxed">{caption}</p>
    </div>
  );
}
