"use client";

import { useState, useEffect, useMemo } from "react";
import {
  Database, TrendingUp, Users, MousePointerClick, Eye, Globe,
  BarChart3, DollarSign, Phone, FileText, CalendarCheck,
  ExternalLink, Zap, Shield, Clock, Archive,
} from "lucide-react";
import { BrandStatusBadge } from "@/components/admin/brand-status-badge";

interface Totals {
  gsc: { totalClicks: number; totalImpressions: number; avgPosition: number; avgCtr: number };
  ga4: { totalSessions: number; totalUsers: number; totalKeyEvents: number; totalRevenue: number; note?: string };
  siteTag: { totalSessions: number; totalPageViews: number; totalConversions: number; totalFormSubmits: number; totalPhoneCalls: number; totalBookings: number; totalEvents: number; totalOutboundClicks: number };
  platform: { totalAiCalls: number; totalAiCost: number };
  paid: { totalSpend: number; totalAdClicks: number; totalAdImpressions: number; totalAdConversions: number };
}

interface BrandRow {
  brandId: string; name: string; domain: string; status?: string;
  statusChangedAt?: string | null; statusChangedBy?: string | null;
  snippetDetectedAt?: string | null;
  snippetInstallationMethod?: "direct" | "gtm" | "none" | null;
  snippetCheckedAt?: string | null;
  gscClicks: number; gscImpressions: number; ga4Sessions: number; ga4KeyEvents: number;
  siteTagSessions: number; siteTagConversions: number; siteTagEvents: number;
  firstDataDate: string | null; lastDataDate: string | null; snapshots: number;
}

interface Retention {
  gscOldestData: string | null; gscRetentionMonths: number;
  siteTagOldestData: string | null; snapshotsOldestData: string | null; note: string;
}

interface Data {
  totals: Totals; brands: BrandRow[];
  monthly: Array<{ month: string; gscClicks: number; gscImpressions: number; ga4Sessions: number; siteTagSessions: number; siteTagConversions: number; siteTagEvents: number }>;
  retention: Retention;
  valuation: { totalBrands: number; totalSnapshots: number; dataSpanDays: number };
}

function formatRelative(date: Date | string | null): string {
  if (!date) return "";
  const d = typeof date === "string" ? new Date(date) : date;
  const diffMs = Date.now() - d.getTime();
  const diffMin = Math.floor(diffMs / 60_000);
  const diffHr = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHr / 24);
  if (diffMin < 1) return "just now";
  if (diffMin < 60) return `${diffMin}m ago`;
  if (diffHr < 24) return `${diffHr}h ago`;
  if (diffDay < 7) return `${diffDay}d ago`;
  return d.toLocaleDateString();
}

function fmt(n: number | null | undefined): string {
  if (n == null || typeof n !== "number" || !Number.isFinite(n)) return "0";
  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();
}

function fmtCurrency(n: number | null | undefined, decimals = 2): string {
  if (n == null || typeof n !== "number" || !Number.isFinite(n)) return "0.00";
  return n.toFixed(decimals);
}

function downloadCsv(filename: string, rows: Record<string, string | number | null | undefined>[]) {
  if (rows.length === 0) return;
  const headers = Object.keys(rows[0]);
  const escape = (v: string | number | null | undefined): string => {
    if (v === null || v === undefined) return "";
    const s = String(v);
    if (s.includes(",") || s.includes('"') || s.includes("\n")) {
      return `"${s.replace(/"/g, '""')}"`;
    }
    return s;
  };
  const csv = [
    headers.join(","),
    ...rows.map(row => headers.map(h => escape(row[h])).join(",")),
  ].join("\n");
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

const STORAGE_KEY = "meseo:admin:historical:filters";

type PersistedFilters = {
  statusFilter?: string;
  brandSearch?: string;
  sortField?: string;
  sortDir?: "asc" | "desc";
};

function loadFilters(): PersistedFilters {
  if (typeof window === "undefined") return {};
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return {};
    const parsed = JSON.parse(raw);
    if (typeof parsed !== "object" || parsed === null) return {};
    return parsed as PersistedFilters;
  } catch {
    return {};
  }
}

function saveFilters(filters: PersistedFilters) {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(filters));
  } catch {
    // localStorage full or unavailable — silently no-op
  }
}

export default function HistoricalPage() {
  const [data, setData] = useState<Data | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedBrand, setSelectedBrand] = useState<string>("all");
  const [lastUpdated, setLastUpdated] = useState<number>(0);
  const [, setTick] = useState(0);
  // Separate all-brands fetch — always brandId=all so the Per-Brand
  // Breakdown table shows every brand regardless of dropdown filter.
  const [allBrandsData, setAllBrandsData] = useState<BrandRow[]>([]);
  const [refetchKey, setRefetchKey] = useState(0);

  useEffect(() => {
    const fetchData = () => {
      const isInitial = !data;
      if (isInitial) setLoading(true);
      const params = selectedBrand === "all" ? "brandId=all" : `brandId=${encodeURIComponent(selectedBrand)}`;
      fetch(`/api/admin/historical?${params}`)
        .then((r) => r.ok ? r.json() : null)
        .then((d: Data | null) => { if (d) { setData(d); setLastUpdated(Date.now()); } })
        .finally(() => setLoading(false));
    };
    fetchData();
    const interval = setInterval(fetchData, 30_000);
    return () => clearInterval(interval);
  }, [selectedBrand]); // eslint-disable-line react-hooks/exhaustive-deps

  // Fetch all-brands breakdown once on mount, refresh every 30s.
  // This is independent of selectedBrand so the table always shows all brands.
  useEffect(() => {
    const fetchAll = () => {
      fetch("/api/admin/historical?brandId=all")
        .then((r) => r.ok ? r.json() : null)
        .then((d: Data | null) => { if (d?.brands) setAllBrandsData(d.brands); })
        .catch(() => {});
    };
    fetchAll();
    const interval = setInterval(fetchAll, 30_000);
    return () => clearInterval(interval);
  }, [refetchKey]); // eslint-disable-line react-hooks/exhaustive-deps

  // Tick every 5s to keep the "Xs ago" display fresh
  useEffect(() => {
    const t = setInterval(() => setTick((n) => n + 1), 5000);
    return () => clearInterval(t);
  }, []);

  const [exportBrand, setExportBrand] = useState<string>("all");
  const [statusFilter, setStatusFilter] = useState<"all" | "active" | "non-active">(() => {
    const v = loadFilters().statusFilter;
    return v === "active" || v === "non-active" ? v : "all";
  });
  const [brandSearch, setBrandSearch] = useState<string>(() => loadFilters().brandSearch ?? "");
  const [reactivatingId, setReactivatingId] = useState<string | null>(null);
  const [deactivatingId, setDeactivatingId] = useState<string | null>(null);
  const [suspendingId, setSuspendingId] = useState<string | null>(null);
  const [checkingSnippetIds, setCheckingSnippetIds] = useState<Set<string>>(new Set());
  const [selectedBrandIds, setSelectedBrandIds] = useState<Set<string>>(new Set());
  const [bulkProcessing, setBulkProcessing] = useState(false);

  async function handleReactivate(brandId: string, brandName: string) {
    if (!confirm(`Reactivate "${brandName}"? This sets the status back to active.`)) return;
    setReactivatingId(brandId);
    try {
      const res = await fetch(`/api/admin/brands/${brandId}/reactivate`, { method: "POST" });
      const json = await res.json();
      if (!res.ok) { alert(`Reactivation failed: ${json.error ?? "Unknown error"}`); return; }
      setRefetchKey((k) => k + 1);
    } catch (err) {
      alert(`Reactivation failed: ${err instanceof Error ? err.message : "Unknown error"}`);
    } finally {
      setReactivatingId(null);
    }
  }

  async function handleDeactivate(brandId: string, brandName: string) {
    if (!confirm(`Deactivate "${brandName}"?\n\nThis sets the brand status to inactive. The brand's data is preserved and the brand can be reactivated at any time.`)) return;
    setDeactivatingId(brandId);
    try {
      const res = await fetch(`/api/admin/brands/${brandId}/deactivate`, { method: "POST" });
      const json = await res.json();
      if (!res.ok) { alert(`Deactivation failed: ${json.error ?? "Unknown error"}`); return; }
      setRefetchKey((k) => k + 1);
    } catch (err) {
      alert(`Deactivation failed: ${err instanceof Error ? err.message : "Unknown error"}`);
    } finally {
      setDeactivatingId(null);
    }
  }

  async function handleSuspend(brandId: string, brandName: string) {
    if (!confirm(`Suspend "${brandName}"?\n\nUse for brands violating terms or pending investigation. Suspended brands are hidden from customer-facing UI. All historical data is preserved. You can reactivate later.`)) return;
    setSuspendingId(brandId);
    try {
      const res = await fetch(`/api/admin/brands/${brandId}/suspend`, { method: "POST" });
      const json = await res.json();
      if (!res.ok) { alert(`Suspension failed: ${json.error ?? "Unknown error"}`); return; }
      setRefetchKey((k) => k + 1);
    } catch (err) {
      alert(`Suspension failed: ${err instanceof Error ? err.message : "Unknown error"}`);
    } finally {
      setSuspendingId(null);
    }
  }

  async function handleCheckSnippet(brandId: string) {
    setCheckingSnippetIds((prev) => new Set(prev).add(brandId));
    try {
      const res = await fetch(`/api/admin/brands/${brandId}/check-snippet`, { method: "POST" });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(`Snippet check failed: ${(data as { error?: string }).error ?? res.statusText}`);
        return;
      }
      setRefetchKey((k) => k + 1);
    } finally {
      setCheckingSnippetIds((prev) => {
        const next = new Set(prev);
        next.delete(brandId);
        return next;
      });
    }
  }

  async function handleBulkReactivate() {
    const ids = Array.from(selectedBrandIds);
    const nonActiveIds = ids.filter((id) => {
      const b = filteredBrands.find((x) => x.brandId === id);
      return b && (b.status ?? "active").toLowerCase() !== "active";
    });
    if (nonActiveIds.length === 0) { alert("All selected brands are already active."); return; }
    if (!confirm(`Reactivate ${nonActiveIds.length} brand(s)?`)) return;
    setBulkProcessing(true);
    const results = await Promise.allSettled(
      nonActiveIds.map((id) =>
        fetch(`/api/admin/brands/${id}/reactivate`, { method: "POST" }).then((r) => r.json()),
      ),
    );
    setBulkProcessing(false);
    const failed = results.filter((r) => r.status === "rejected").length;
    if (failed > 0) alert(`Reactivated ${nonActiveIds.length - failed} of ${nonActiveIds.length}. ${failed} failed.`);
    setSelectedBrandIds(new Set());
    setRefetchKey((k) => k + 1);
  }

  async function handleBulkDeactivate() {
    const ids = Array.from(selectedBrandIds);
    const activeIds = ids.filter((id) => {
      const b = filteredBrands.find((x) => x.brandId === id);
      return b && (b.status ?? "active").toLowerCase() === "active";
    });
    if (activeIds.length === 0) { alert("No selected brands are currently active."); return; }
    if (!confirm(`Deactivate ${activeIds.length} brand(s)?\n\nBrands will be hidden from customer-facing UI but historical data is preserved.`)) return;
    setBulkProcessing(true);
    const results = await Promise.allSettled(
      activeIds.map((id) =>
        fetch(`/api/admin/brands/${id}/deactivate`, { method: "POST" }).then((r) => r.json()),
      ),
    );
    setBulkProcessing(false);
    const failed = results.filter((r) => r.status === "rejected").length;
    if (failed > 0) alert(`Deactivated ${activeIds.length - failed} of ${activeIds.length}. ${failed} failed.`);
    setSelectedBrandIds(new Set());
    setRefetchKey((k) => k + 1);
  }

  function toggleSelectAll() {
    if (filteredBrands.length > 0 && selectedBrandIds.size === filteredBrands.length) {
      setSelectedBrandIds(new Set());
    } else {
      setSelectedBrandIds(new Set(filteredBrands.map((b) => b.brandId)));
    }
  }

  function handleExportCsv() {
    const source = selectedBrandIds.size > 0
      ? filteredBrands.filter(b => selectedBrandIds.has(b.brandId))
      : filteredBrands;
    if (source.length === 0) { alert("No brands to export"); return; }
    const rows = source.map(b => ({
      name: b.name,
      domain: b.domain,
      status: b.status ?? "active",
      statusChangedAt: b.statusChangedAt ?? "",
      statusChangedBy: b.statusChangedBy ?? "",
      gscClicks: b.gscClicks,
      gscImpressions: b.gscImpressions,
      ga4Sessions: b.ga4Sessions,
      ga4KeyEvents: b.ga4KeyEvents,
      siteTagSessions: b.siteTagSessions,
      siteTagConversions: b.siteTagConversions,
      siteTagEvents: b.siteTagEvents,
      firstDataDate: b.firstDataDate ?? "",
      lastDataDate: b.lastDataDate ?? "",
      snapshots: b.snapshots,
    }));
    const timestamp = new Date().toISOString().slice(0, 10);
    const scope = selectedBrandIds.size > 0 ? "selected" : statusFilter;
    downloadCsv(`brands-${scope}-${timestamp}.csv`, rows);
  }

  const filteredBrands = useMemo(() => {
    if (!allBrandsData) return [];
    const query = brandSearch.trim().toLowerCase();
    return allBrandsData.filter((b) => {
      const s = (b.status ?? "active").toLowerCase();
      if (statusFilter === "active" && s !== "active") return false;
      if (statusFilter === "non-active" && s === "active") return false;
      if (query && !b.name.toLowerCase().includes(query)) return false;
      return true;
    });
  }, [allBrandsData, statusFilter, brandSearch]);

  const [sortField, setSortField] = useState<string>(() => loadFilters().sortField ?? "gscClicks");
  const [sortDir, setSortDir] = useState<"asc" | "desc">(() => loadFilters().sortDir === "asc" ? "asc" : "desc");

  const sortedBrands = useMemo(() => {
    const arr = [...filteredBrands];
    arr.sort((a, b) => {
      const aVal = (a as any)[sortField];
      const bVal = (b as any)[sortField];
      if (aVal == null && bVal == null) return 0;
      if (aVal == null) return 1;
      if (bVal == null) return -1;
      if (typeof aVal === "number" && typeof bVal === "number") {
        return sortDir === "asc" ? aVal - bVal : bVal - aVal;
      }
      const aStr = String(aVal).toLowerCase();
      const bStr = String(bVal).toLowerCase();
      return sortDir === "asc" ? aStr.localeCompare(bStr) : bStr.localeCompare(aStr);
    });
    return arr;
  }, [filteredBrands, sortField, sortDir]);

  function handleSortClick(field: string) {
    if (sortField === field) {
      setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortDir("desc");
    }
  }

  // If the selected brand is filtered out, fall back to "All Brands"
  useEffect(() => {
    if (selectedBrand !== "all" && !filteredBrands.find((b) => b.brandId === selectedBrand)) {
      setSelectedBrand("all");
    }
  }, [filteredBrands, selectedBrand]);

  // Clear selection when filters change to avoid stale selections from hidden brands
  useEffect(() => {
    setSelectedBrandIds(new Set());
  }, [statusFilter, brandSearch]);

  // Persist filter state across page refreshes
  useEffect(() => {
    saveFilters({ statusFilter, brandSearch, sortField, sortDir });
  }, [statusFilter, brandSearch, sortField, sortDir]);

  const agoStr = lastUpdated ? `${Math.round((Date.now() - lastUpdated) / 1000)}s ago` : "";

  if (loading) return <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" /></div>;
  if (!data) return <div className="max-w-5xl mx-auto px-6 py-12 text-center"><Database className="w-10 h-10 text-slate-200 mx-auto mb-3" /><p className="text-slate-500">Failed to load historical data.</p></div>;

  // Defensive defaults — the API may omit sub-objects if a data source
  // (e.g. GA4, paid media) has never been connected for any brand. Any
  // numeric-formatting helper below would crash on an undefined field.
  const raw = data.totals ?? ({} as Partial<Totals>);
  const gsc = raw.gsc ?? {} as Partial<Totals["gsc"]>;
  const ga4 = raw.ga4 ?? {} as Partial<Totals["ga4"]>;
  const siteTag = raw.siteTag ?? {} as Partial<Totals["siteTag"]>;
  const platform = raw.platform ?? {} as Partial<Totals["platform"]>;
  const paid = raw.paid ?? {} as Partial<Totals["paid"]>;
  const t = {
    gsc: {
      totalClicks: gsc.totalClicks ?? 0,
      totalImpressions: gsc.totalImpressions ?? 0,
      avgPosition: gsc.avgPosition ?? 0,
      avgCtr: gsc.avgCtr ?? 0,
    },
    ga4: {
      totalSessions: ga4.totalSessions ?? 0,
      totalUsers: ga4.totalUsers ?? 0,
      totalKeyEvents: ga4.totalKeyEvents ?? 0,
      totalRevenue: ga4.totalRevenue ?? 0,
    },
    siteTag: {
      totalSessions: siteTag.totalSessions ?? 0,
      totalPageViews: siteTag.totalPageViews ?? 0,
      totalConversions: siteTag.totalConversions ?? 0,
      totalFormSubmits: siteTag.totalFormSubmits ?? 0,
      totalPhoneCalls: siteTag.totalPhoneCalls ?? 0,
      totalBookings: siteTag.totalBookings ?? 0,
      totalEvents: siteTag.totalEvents ?? 0,
      totalOutboundClicks: siteTag.totalOutboundClicks ?? 0,
    },
    platform: {
      totalAiCalls: platform.totalAiCalls ?? 0,
      totalAiCost: platform.totalAiCost ?? 0,
    },
    paid: {
      totalSpend: paid.totalSpend ?? 0,
      totalAdClicks: paid.totalAdClicks ?? 0,
      totalAdImpressions: paid.totalAdImpressions ?? 0,
      totalAdConversions: paid.totalAdConversions ?? 0,
    },
  };
  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
          <Archive className="w-6 h-6 text-brand-600" /> Historical Tracking
          <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-full px-2 py-0.5 ml-2">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" /> LIVE
          </span>
          {agoStr && <span className="text-[10px] text-slate-400 font-normal ml-1">Updated {agoStr}</span>}
        </h1>
        <p className="text-sm text-slate-500 mt-1">Permanent record of all metrics. Auto-refreshes every 30s.</p>
      </div>
      <div className="flex items-center gap-2 flex-wrap">
        <div className="flex items-center gap-2">
          <input
            type="text"
            value={brandSearch}
            onChange={(e) => setBrandSearch(e.target.value)}
            placeholder="Search brands..."
            className="px-3 py-1.5 text-xs border border-slate-200 rounded-lg bg-white w-48"
          />
          {brandSearch && (
            <button onClick={() => setBrandSearch("")} className="text-xs text-slate-500 hover:text-slate-700">
              Clear
            </button>
          )}
        </div>
        <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
          className="px-3 py-1.5 text-xs border border-slate-200 rounded-lg bg-white">
          <option value="all">All statuses</option>
          <option value="active">Active only</option>
          <option value="non-active">Non-active only</option>
        </select>
        {(statusFilter !== "all" || brandSearch || sortField !== "gscClicks" || sortDir !== "desc") && (
          <button
            onClick={() => { setStatusFilter("all"); setBrandSearch(""); setSortField("gscClicks"); setSortDir("desc"); }}
            className="px-3 py-1.5 text-xs text-slate-500 hover:text-slate-700 underline"
          >
            Reset
          </button>
        )}
        <select value={selectedBrand} onChange={(e) => { setSelectedBrand(e.target.value); setExportBrand(e.target.value); }}
          className="px-3 py-1.5 text-xs border border-slate-200 rounded-lg bg-white min-w-[160px]">
          <option value="all">All Brands</option>
          {filteredBrands.map((b) => <option key={b.brandId} value={b.brandId}>{b.name}{b.status && b.status !== "active" ? ` [${b.status}]` : ""}</option>)}
        </select>
        {selectedBrand !== "all" && (
          <a href={`/api/admin/historical/export?brandId=${selectedBrand}&source=all`}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 bg-white text-xs font-semibold text-slate-700 hover:bg-slate-50">
            <ExternalLink className="w-3.5 h-3.5" /> Download CSV
          </a>
        )}
        <button
          onClick={handleExportCsv}
          className="px-3 py-1.5 text-xs border border-slate-200 rounded-lg bg-white hover:bg-slate-50 text-slate-700"
        >
          Export CSV ({selectedBrandIds.size > 0 ? `${selectedBrandIds.size} selected` : `${filteredBrands.length}`})
        </button>
        {loading && <span className="text-xs text-slate-400">Loading…</span>}
      </div>

      {/* GSC */}
      <Section title="Google Search Console" icon={Globe} accent="text-blue-600">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <Card label="Total Clicks Ever" value={fmt(t.gsc.totalClicks)} accent="text-blue-600" />
          <Card label="Total Impressions Ever" value={fmt(t.gsc.totalImpressions)} />
          <Card label="Avg Position (Lifetime)" value={String(t.gsc.avgPosition)} />
          <Card label="Avg CTR (Lifetime)" value={`${t.gsc.avgCtr}%`} />
        </div>
      </Section>

      {/* GA4 */}
      <Section title="Google Analytics 4" icon={BarChart3} accent="text-orange-600">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <Card label="Total Sessions Ever" value={fmt(t.ga4.totalSessions)} />
          <Card label="Total Users Ever" value={fmt(t.ga4.totalUsers)} />
          <Card label="GA4 Key Events" value={fmt(t.ga4.totalKeyEvents)} accent="text-emerald-600" />
          <Card label="Total Revenue" value={`$${fmt(t.ga4.totalRevenue)}`} accent="text-amber-600" />
        </div>
      </Section>

      {/* Site Tag */}
      <Section title="Site Tag (First-Party)" icon={Zap} accent="text-emerald-600">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <Card label="Total Sessions" value={fmt(t.siteTag.totalSessions)} />
          <Card label="Total Page Views" value={fmt(t.siteTag.totalPageViews)} />
          <Card label="Total Conversions" value={fmt(t.siteTag.totalConversions)} accent="text-emerald-600" />
          <Card label="Total Form Submits" value={fmt(t.siteTag.totalFormSubmits)} />
          <Card label="Total Phone Calls" value={fmt(t.siteTag.totalPhoneCalls)} />
          <Card label="Total Bookings" value={fmt(t.siteTag.totalBookings)} />
          <Card label="Total Events" value={fmt(t.siteTag.totalEvents)} />
          <Card label="Total Outbound Clicks" value={fmt(t.siteTag.totalOutboundClicks)} />
        </div>
      </Section>

      {/* Platform + Paid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Section title="Platform" icon={Shield} accent="text-violet-600">
          <div className="grid grid-cols-2 gap-3">
            <Card label="Total AI Calls" value={fmt(t.platform.totalAiCalls)} />
            <Card label="Total AI Cost" value={`$${fmtCurrency(t.platform?.totalAiCost)}`} accent="text-amber-600" />
          </div>
        </Section>
        <Section title="Paid Media" icon={DollarSign} accent="text-amber-600">
          <div className="grid grid-cols-2 gap-3">
            <Card label="Total Ad Spend" value={`$${fmt(t.paid.totalSpend)}`} accent="text-amber-600" />
            <Card label="Total Ad Clicks" value={fmt(t.paid.totalAdClicks)} />
            <Card label="Total Ad Impressions" value={fmt(t.paid.totalAdImpressions)} />
            <Card label="Ad Conversions" value={fmt(t.paid.totalAdConversions)} accent="text-emerald-600" />
          </div>
        </Section>
      </div>

      {/* Per-Brand Breakdown */}
      {allBrandsData.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">
            <Users className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Per-Brand Breakdown</h3>
            <span className="text-[10px] text-slate-400 ml-1">
              {statusFilter !== "all" && brandSearch ? "Filtered by status and name search" :
               statusFilter !== "all" ? "Filtered by status" :
               brandSearch ? "Filtered by name search" :
               "All brands"} · not filtered by brand dropdown
            </span>
          </div>
          {selectedBrandIds.size >= 1 && (
            <div className="flex items-center gap-2 px-5 py-2 bg-slate-50 border-b border-slate-100">
              <span className="text-xs text-slate-600 font-medium">{selectedBrandIds.size} selected</span>
              <button onClick={handleBulkReactivate} disabled={bulkProcessing}
                className="px-3 py-1 text-xs font-semibold rounded border border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
                Reactivate all
              </button>
              <button onClick={handleBulkDeactivate} disabled={bulkProcessing}
                className="px-3 py-1 text-xs font-semibold rounded border border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100 disabled:opacity-50">
                Deactivate all
              </button>
              <button onClick={() => setSelectedBrandIds(new Set())}
                className="px-3 py-1 text-xs text-slate-500 hover:text-slate-700">
                Clear
              </button>
              {bulkProcessing && <span className="text-xs text-slate-400">Processing…</span>}
            </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-3 py-2 w-8">
                  <input type="checkbox" className="rounded"
                    checked={filteredBrands.length > 0 && selectedBrandIds.size === filteredBrands.length}
                    onChange={toggleSelectAll} />
                </th>
                <th className="px-5 py-2 cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("name")}>Brand {sortField === "name" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 text-right cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("gscClicks")}>GSC Clicks {sortField === "gscClicks" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 text-right cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("gscImpressions")}>Impressions {sortField === "gscImpressions" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 text-right cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("siteTagSessions")}>Sessions {sortField === "siteTagSessions" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 text-right cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("siteTagConversions")}>Conversions {sortField === "siteTagConversions" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 text-right cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("siteTagEvents")}>Events {sortField === "siteTagEvents" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("firstDataDate")}>Data Since {sortField === "firstDataDate" && (sortDir === "asc" ? "▲" : "▼")}</th>
                <th className="px-5 py-2 text-right cursor-pointer select-none hover:bg-slate-100" onClick={() => handleSortClick("snapshots")}>Snapshots {sortField === "snapshots" && (sortDir === "asc" ? "▲" : "▼")}</th>
              </tr></thead>
              <tbody className="divide-y divide-slate-100">{sortedBrands.map((b) => (
                <tr key={b.brandId} className={`hover:bg-slate-50 ${selectedBrandIds.has(b.brandId) ? "bg-violet-50" : ""}`}>
                  <td className="px-3 py-2 w-8">
                    <input type="checkbox" className="rounded" checked={selectedBrandIds.has(b.brandId)}
                      onChange={() => setSelectedBrandIds((prev) => {
                        const next = new Set(prev);
                        next.has(b.brandId) ? next.delete(b.brandId) : next.add(b.brandId);
                        return next;
                      })} />
                  </td>
                  <td className="px-5 py-2">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-slate-800">{b.name}</span>
                      <BrandStatusBadge status={b.status} hideIfActive />
                      {b.status && b.status.toLowerCase() !== "active" && (
                        <button
                          onClick={() => handleReactivate(b.brandId, b.name)}
                          disabled={reactivatingId === b.brandId}
                          className="inline-flex items-center rounded border border-slate-200 bg-white px-2 py-0.5 text-[10px] font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-50"
                        >
                          {reactivatingId === b.brandId ? "Reactivating…" : "Reactivate"}
                        </button>
                      )}
                      {(!b.status || b.status.toLowerCase() === "active") && (
                        <>
                          <button
                            onClick={() => handleDeactivate(b.brandId, b.name)}
                            disabled={deactivatingId === b.brandId}
                            className="inline-flex items-center rounded border border-amber-200 bg-amber-50 px-2 py-0.5 text-[10px] font-semibold text-amber-700 hover:bg-amber-100 disabled:opacity-50"
                          >
                            {deactivatingId === b.brandId ? "Deactivating…" : "Deactivate"}
                          </button>
                          <button
                            onClick={() => handleSuspend(b.brandId, b.name)}
                            disabled={suspendingId === b.brandId}
                            className="inline-flex items-center rounded border border-red-200 bg-red-50 px-2 py-0.5 text-[10px] font-semibold text-red-700 hover:bg-red-100 disabled:opacity-50"
                          >
                            {suspendingId === b.brandId ? "Suspending…" : "Suspend"}
                          </button>
                        </>
                      )}
                      {b.snippetCheckedAt ? (
                        <span className={`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-semibold ${
                          b.snippetInstallationMethod === "direct"
                            ? "bg-green-50 text-green-700"
                            : b.snippetInstallationMethod === "gtm"
                            ? "bg-blue-50 text-blue-700"
                            : "bg-slate-100 text-slate-500"
                        }`}>
                          <span className={`inline-block w-1.5 h-1.5 rounded-full ${
                            b.snippetInstallationMethod === "direct" ? "bg-green-500"
                            : b.snippetInstallationMethod === "gtm" ? "bg-blue-500"
                            : "bg-slate-400"
                          }`} />
                          {b.snippetInstallationMethod === "direct" ? "Direct"
                            : b.snippetInstallationMethod === "gtm" ? "GTM"
                            : "Not detected"}
                        </span>
                      ) : (
                        <span className="inline-flex items-center rounded px-1.5 py-0.5 text-[10px] text-slate-400">Unchecked</span>
                      )}
                      <button
                        onClick={() => handleCheckSnippet(b.brandId)}
                        disabled={checkingSnippetIds.has(b.brandId)}
                        className="inline-flex items-center rounded-md border border-slate-200 bg-white px-2 py-0.5 text-xs font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
                      >
                        {checkingSnippetIds.has(b.brandId) ? "Checking…" : "Check"}
                      </button>
                    </div>
                    {b.statusChangedAt && (
                      <div className="text-xs text-slate-500 mt-0.5">
                        Changed {formatRelative(b.statusChangedAt)}{b.statusChangedBy && ` by ${b.statusChangedBy}`}
                      </div>
                    )}
                    {b.snippetCheckedAt && (
                      <div className="text-xs text-slate-400 mt-0.5">Snippet checked {formatRelative(b.snippetCheckedAt)}</div>
                    )}
                    <span className="text-xs text-slate-400">{b.domain}</span>
                  </td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(b.gscClicks)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(b.gscImpressions)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(b.siteTagSessions || b.ga4Sessions)}</td>
                  <td className="px-5 py-2 text-right tabular-nums font-semibold text-emerald-700">{fmt(b.siteTagConversions || b.ga4KeyEvents)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(b.siteTagEvents)}</td>
                  <td className="px-5 py-2 text-xs text-slate-500">{b.firstDataDate ?? "—"}</td>
                  <td className="px-5 py-2 text-right tabular-nums text-slate-500">{b.snapshots}</td>
                </tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      )}

      {/* Data Preservation Status */}
      <div className="bg-white rounded-xl border border-slate-200 p-5 space-y-3">
        <div className="flex items-center gap-2">
          <Clock className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Data Preservation Status</h3>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 text-xs text-slate-600">
          <div className="bg-blue-50 rounded-lg p-3 border border-blue-100">
            <p className="font-semibold text-blue-800">GSC</p>
            <p>Since {data.retention.gscOldestData ?? "—"}</p>
            <p className="text-blue-600">{data.retention.gscRetentionMonths}mo retention — snapshots preserve beyond</p>
          </div>
          <div className="bg-emerald-50 rounded-lg p-3 border border-emerald-100">
            <p className="font-semibold text-emerald-800">Site Tag</p>
            <p>Since {data.retention.siteTagOldestData ?? "—"}</p>
            <p className="text-emerald-600">No expiration — you own this data</p>
          </div>
          <div className="bg-violet-50 rounded-lg p-3 border border-violet-100">
            <p className="font-semibold text-violet-800">Snapshots</p>
            <p>{fmt(data.valuation?.totalSnapshots)} daily snapshots</p>
            <p className="text-violet-600">Permanent — survives all retention windows</p>
          </div>
          <div className="bg-slate-50 rounded-lg p-3 border border-slate-200">
            <p className="font-semibold text-slate-800">Platform</p>
            <p>{data.valuation.totalBrands} brands · {data.valuation.dataSpanDays}d span</p>
            <p className="text-slate-500">{data.retention.note}</p>
          </div>
        </div>
      </div>

      {/* Backfill Controls */}
      <div className="bg-white rounded-xl border border-slate-200 p-5 space-y-3">
        <div className="flex items-center gap-2">
          <Database className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Data Backfill</h3>
          <p className="text-[10px] text-slate-400 ml-2">Pull historical data from Google APIs into permanent storage</p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <BackfillButton label="Backfill GA4 (36mo)" endpoint="/api/admin/debug/backfill-ga4-history" brandId={selectedBrand} />
          <BackfillButton label="Backfill GSC (16mo)" endpoint="/api/admin/debug/backfill-gsc-history" brandId={selectedBrand} />
          <BackfillButton label="Rebuild Snapshots" endpoint="/api/admin/debug/backfill-snapshots" brandId={selectedBrand} />
        </div>
      </div>

      {/* Monthly Trend */}
      {data.monthly.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">
            <TrendingUp className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Monthly Trend</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">Month</th>
                <th className="px-5 py-2 text-right">GSC Clicks</th>
                <th className="px-5 py-2 text-right">Impressions</th>
                <th className="px-5 py-2 text-right">GA4 Sessions</th>
                <th className="px-5 py-2 text-right">ST Sessions</th>
                <th className="px-5 py-2 text-right">ST Conv</th>
                <th className="px-5 py-2 text-right">ST Events</th>
              </tr></thead>
              <tbody className="divide-y divide-slate-100">{data.monthly.map((m) => (
                <tr key={m.month} className="hover:bg-slate-50">
                  <td className="px-5 py-2 font-medium text-slate-800">{m.month}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(m.gscClicks)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(m.gscImpressions)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(m.ga4Sessions)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(m.siteTagSessions)}</td>
                  <td className="px-5 py-2 text-right tabular-nums text-emerald-700">{fmt(m.siteTagConversions)}</td>
                  <td className="px-5 py-2 text-right tabular-nums">{fmt(m.siteTagEvents)}</td>
                </tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

function Section({ title, icon: Icon, accent = "text-brand-600", children }: { title: string; icon: typeof Database; accent?: string; children: React.ReactNode }) {
  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2">
        <Icon className={`w-4 h-4 ${accent}`} />
        <h2 className="font-bold text-slate-800 text-sm uppercase tracking-widest">{title}</h2>
      </div>
      {children}
    </div>
  );
}

function BackfillButton({ label, endpoint, brandId }: { label: string; endpoint: string; brandId: string }) {
  const [running, setRunning] = useState(false);
  const [result, setResult] = useState<string | null>(null);
  const run = async () => {
    setRunning(true);
    setResult(null);
    try {
      const params = brandId !== "all" ? `?brandId=${encodeURIComponent(brandId)}` : "";
      const res = await fetch(`${endpoint}${params}`, { method: "POST" });
      const data = await res.json();
      setResult(res.ok ? `Done: ${JSON.stringify(data).slice(0, 200)}` : `Error: ${data.error ?? res.status}`);
    } catch (err) {
      setResult(`Failed: ${err instanceof Error ? err.message : "unknown"}`);
    } finally { setRunning(false); }
  };
  return (
    <div className="space-y-1">
      <button onClick={run} disabled={running}
        className="px-3 py-1.5 rounded-lg border border-slate-200 bg-white text-xs font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5">
        {running ? <span className="w-3 h-3 border-2 border-brand-600 border-t-transparent rounded-full animate-spin" /> : <Database className="w-3.5 h-3.5" />}
        {label}
      </button>
      {result && <p className="text-[10px] text-slate-500 max-w-xs truncate" title={result}>{result}</p>}
    </div>
  );
}

function Card({ label, value, accent = "text-slate-900" }: { label: string; value: string; accent?: string }) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-4 py-3">
      <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-widest">{label}</p>
      <p className={`text-xl font-bold tabular-nums mt-0.5 ${accent}`}>{value}</p>
    </div>
  );
}
