"use client";

/**
 * Admin → Brands — premium operations-center surface.
 *
 * Layout: page header + stats bar + filter bar with grid/list
 * toggle. Grid view shows each brand as a card with a colored
 * health ring + integration dots + quick stats. List view keeps
 * the dense table for power users. Click-to-open detail drawer
 * unchanged from the prior commit.
 */

import { useEffect, useMemo, useState } from "react";
import {
  Search, X, Loader2, ChevronLeft, ChevronRight, Globe, Activity,
  Users as UsersIcon, Trash2, ArrowRightLeft, ExternalLink, AlertTriangle,
  LayoutGrid, List as ListIcon, Building2,
} from "lucide-react";
import {
  PageHeader, StatCard, Card, CardHeader, EmptyState,
  TableSkeleton, DataTable, type Column,
} from "@/components/admin";
import { APP_URL } from "@/lib/config";

interface BrandRow {
  id: string;
  name: string;
  domain: string;
  logoUrl: string | null;
  orgName: string;
  ownerName: string | null;
  ownerEmail: string | null;
  memberCount: number;
  plan: string;
  billingCycle: string;
  createdAt: string;
  ga4Connected: boolean;
  gscConnected: boolean;
  gbpConnected: boolean;
  siteTagInstalled: boolean;
  totalEvents: number;
  lastAuditScore: number | null;
  lastAuditDate: string | null;
  lastActivityAt: string | null;
  siteTagLastEventAt: string | null;
}

interface BrandList {
  brands: BrandRow[];
  total: number; page: number; limit: number; hasMore: boolean;
}

interface BrandDetail {
  brand: {
    id: string; name: string; domain: string; logoUrl: string | null;
    industry: string | null; location: string | null;
    plan: string; billingCycle: string; planExpiresAt: string | null;
    healthcareMode: boolean; dataRetentionDays: number | null;
    dpaStatus: string; dpaSignedAt: string | null;
    createdAt: string; orgName: string;
  };
  members: Array<{ id: string; role: string; joinedAt: string; user: { id: string; name: string | null; email: string; image: string | null } }>;
  integrations: Array<{ integrationId: string; connected: boolean; status: string; lastSynced: string | null; syncError: string | null }>;
  siteTag: { siteId: string; status: string; lastEventAt: string | null; installedAt: string } | null;
  stats: {
    events: number; sessions: number; conversions: number; siteEvents: number;
    gscQueries: number; gscPages: number; pageRecords: number;
    gscClicks90d: number; gscImpressions90d: number;
  };
  latestAudit: { id: string; crawlHealth: number; status: string; createdAt: string } | null;
  recentActivity: Array<{ id: string; action: string; category: string; userId: string | null; metadata: unknown; timestamp: string }>;
  featureAdoption: Array<{ action: string; count: number; lastUsed: string | null }>;
}

function formatDate(s: string | null): string {
  if (!s) return "—";
  try { return new Date(s).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }); } catch { return s; }
}
function formatRelative(s: string | null): string {
  if (!s) return "—";
  try {
    const sec = Math.floor((Date.now() - new Date(s).getTime()) / 1000);
    if (sec < 60) return "just now";
    if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
    if (sec < 86_400) return `${Math.floor(sec / 3600)}h ago`;
    return `${Math.floor(sec / 86_400)}d ago`;
  } catch { return s; }
}
function formatNumber(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();
}

const PLAN_BADGE: Record<string, string> = {
  trial:        "bg-amber-50 text-amber-700 border-amber-200",
  growth:       "bg-slate-100 text-slate-700 border-slate-200",
  professional: "bg-blue-50 text-blue-700 border-blue-200",
  agency:       "bg-violet-50 text-violet-700 border-violet-200",
  agency_pro:   "bg-purple-50 text-purple-700 border-purple-200",
  enterprise:   "bg-emerald-50 text-emerald-700 border-emerald-200",
};

export default function AdminBrandsPage() {
  const [q, setQ] = useState("");
  const [planFilter, setPlanFilter] = useState("");
  const [view, setView] = useState<"grid" | "list">("list");
  const [page, setPage] = useState(1);
  const [data, setData] = useState<BrandList | null>(null);
  const [loading, setLoading] = useState(true);

  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [detail, setDetail] = useState<BrandDetail | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  const [toast, setToast] = useState<string | null>(null);
  const show = (msg: string) => { setToast(msg); setTimeout(() => setToast(null), 2200); };

  const [deleteTarget, setDeleteTarget] = useState<BrandRow | null>(null);
  const [deleteConfirmText, setDeleteConfirmText] = useState("");
  const [deletingBrand, setDeletingBrand] = useState(false);

  useEffect(() => {
    const handle = setTimeout(() => {
      const params = new URLSearchParams();
      if (q.trim()) params.set("q", q.trim());
      if (planFilter) params.set("plan", planFilter);
      params.set("page", String(page));
      setLoading(true);
      fetch(`/api/admin/brands?${params.toString()}`)
        .then((r) => (r.ok ? r.json() : null))
        .then((d) => setData(d))
        .finally(() => setLoading(false));
    }, 250);
    return () => clearTimeout(handle);
  }, [q, planFilter, page]);

  useEffect(() => {
    if (!selectedId) { setDetail(null); return; }
    setDetailLoading(true);
    fetch(`/api/admin/brands/${selectedId}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => setDetail(d))
      .finally(() => setDetailLoading(false));
  }, [selectedId]);

  const totalPages = useMemo(() => data ? Math.max(1, Math.ceil(data.total / data.limit)) : 1, [data]);

  // ── Stats bar derived from current page ──
  const stats = useMemo(() => {
    if (!data) return null;
    const list = data.brands;
    const auditScores = list.filter((b) => b.lastAuditScore != null).map((b) => b.lastAuditScore!);
    const avgAudit = auditScores.length > 0
      ? Math.round(auditScores.reduce((s, n) => s + n, 0) / auditScores.length)
      : null;
    return {
      total: data.total,
      withSiteTag: list.filter((b) => b.siteTagInstalled).length,
      withGsc:     list.filter((b) => b.gscConnected).length,
      withGa4:     list.filter((b) => b.ga4Connected).length,
      avgAudit,
    };
  }, [data]);

  function openDeleteModal(b: BrandRow) {
    setDeleteTarget(b);
    setDeleteConfirmText("");
  }
  async function confirmDeleteBrand() {
    if (!deleteTarget || deleteConfirmText !== deleteTarget.name) return;
    setDeletingBrand(true);
    const res = await fetch(`/api/admin/brands/${deleteTarget.id}`, { method: "DELETE" });
    if (res.ok) {
      show("Brand deactivated — all data preserved");
      setSelectedId(null);
      setDeleteTarget(null);
      setDeleteConfirmText("");
      setPage(1);
      const params = new URLSearchParams();
      if (q.trim()) params.set("q", q.trim());
      if (planFilter) params.set("plan", planFilter);
      params.set("page", "1");
      fetch(`/api/admin/brands?${params.toString()}`).then((r) => r.json()).then(setData);
    } else show("Delete failed");
    setDeletingBrand(false);
  }
  async function transferBrand(b: BrandRow) {
    const email = window.prompt(`Transfer ${b.name} to which user's organization? Enter their email:`);
    if (!email) return;
    const res = await fetch(`/api/admin/brands/${b.id}/transfer`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ownerEmail: email.trim() }),
    });
    if (res.ok) { show("Transferred"); if (selectedId === b.id) { const r = await fetch(`/api/admin/brands/${b.id}`); if (r.ok) setDetail(await r.json()); } }
    else { const d = await res.json().catch(() => ({})); show(d.message || "Transfer failed"); }
  }

  const columns: Array<Column<BrandRow>> = [
    {
      key: "brand",
      header: "Brand",
      cell: (b) => (
        <div className="flex items-center gap-2.5 min-w-0">
          {b.logoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={b.logoUrl} alt="" className="w-8 h-8 rounded-lg object-contain bg-slate-50 border border-slate-100 shrink-0" />
          ) : (
            <span className="w-8 h-8 rounded-lg bg-gradient-to-br from-slate-200 to-slate-300 text-slate-600 text-xs font-semibold flex items-center justify-center shrink-0">
              {b.name[0]?.toUpperCase()}
            </span>
          )}
          <div className="min-w-0">
            <p className="text-xs font-semibold text-slate-900 truncate max-w-[200px]">{b.name}</p>
            <p className="text-[10px] text-slate-500 font-mono truncate max-w-[200px]">{b.domain}</p>
          </div>
        </div>
      ),
    },
    {
      key: "owner",
      header: "Owner",
      cell: (b) => (
        <div className="min-w-0">
          <p className="text-xs text-slate-700 truncate max-w-[160px]">{b.ownerName || "—"}</p>
          <p className="text-[10px] text-slate-500 truncate max-w-[160px]">{b.ownerEmail || ""}</p>
        </div>
      ),
    },
    {
      key: "plan",
      header: "Plan",
      cell: (b) => (
        <div>
          <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${PLAN_BADGE[b.plan] ?? PLAN_BADGE.growth}`}>
            {b.plan.replace("_", " ")}
          </span>
          <p className="text-[10px] text-slate-400 mt-0.5">{b.billingCycle}</p>
        </div>
      ),
    },
    {
      key: "integrations",
      header: "Integrations",
      align: "center",
      cell: (b) => (
        <div className="flex items-center justify-center gap-1.5">
          <Dot on={b.ga4Connected} label="GA4" />
          <Dot on={b.gscConnected} label="GSC" />
          <Dot on={b.gbpConnected} label="GBP" />
          <Dot on={b.siteTagInstalled} label="Tag" />
        </div>
      ),
    },
    {
      key: "events",
      header: "Events",
      align: "right",
      cell: (b) => <span className="text-xs text-slate-700 tabular-nums">{formatNumber(b.totalEvents)}</span>,
    },
    {
      key: "audit",
      header: "Audit",
      align: "right",
      cell: (b) => {
        if (b.lastAuditScore == null) return <span className="text-xs text-slate-400">—</span>;
        const cls = b.lastAuditScore >= 80 ? "text-emerald-600" : b.lastAuditScore >= 50 ? "text-amber-600" : "text-rose-600";
        return <span className={`text-xs font-semibold tabular-nums ${cls}`}>{b.lastAuditScore}/100</span>;
      },
    },
    {
      key: "active",
      header: "Last activity",
      align: "right",
      cell: (b) => <span className="text-[10px] text-slate-500 tabular-nums">{formatRelative(b.lastActivityAt ?? b.siteTagLastEventAt)}</span>,
    },
  ];

  return (
    <div className="space-y-6 transition-opacity duration-200">
      <PageHeader
        title="Brands"
        subtitle={data ? `${data.total.toLocaleString()} total brands across all organizations` : "Loading…"}
        icon={Building2}
      />

      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
          <StatCard label="Total brands" value={stats.total.toLocaleString()} variant="compact" />
          <StatCard label="With Site Tag" value={stats.withSiteTag.toLocaleString()} variant="compact" valueClass="text-emerald-600" />
          <StatCard label="With GSC" value={stats.withGsc.toLocaleString()} variant="compact" valueClass="text-blue-600" />
          <StatCard label="With GA4" value={stats.withGa4.toLocaleString()} variant="compact" valueClass="text-orange-600" />
          <StatCard label="Avg health" value={stats.avgAudit != null ? `${stats.avgAudit}/100` : "—"} variant="compact"
            valueClass={stats.avgAudit != null && stats.avgAudit >= 80 ? "text-emerald-600" : stats.avgAudit != null && stats.avgAudit >= 50 ? "text-amber-600" : "text-rose-600"} />
        </div>
      )}

      {/* Filter bar with view toggle */}
      <div className="bg-white border border-slate-100 rounded-xl shadow-sm p-3 flex items-center gap-2 flex-wrap">
        <div className="relative flex-1 min-w-[220px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" />
          <input
            value={q}
            onChange={(e) => { setQ(e.target.value); setPage(1); }}
            placeholder="Search name or domain…"
            className="w-full pl-9 pr-3 py-2 text-sm bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500"
          />
        </div>
        <select
          value={planFilter}
          onChange={(e) => { setPlanFilter(e.target.value); setPage(1); }}
          className="px-3 py-2 text-xs bg-white border border-slate-200 rounded-lg min-w-[140px]"
        >
          <option value="">All plans</option>
          <option value="trial">Trial</option>
          <option value="growth">Growth</option>
          <option value="professional">Professional</option>
          <option value="agency">Agency</option>
          <option value="agency_pro">Agency Pro</option>
          <option value="enterprise">Enterprise</option>
        </select>
        <div className="inline-flex bg-slate-100 rounded-lg p-0.5 ml-auto">
          <button
            onClick={() => setView("list")}
            className={`p-1.5 rounded-md transition-colors ${view === "list" ? "bg-white shadow-sm text-slate-900" : "text-slate-500 hover:text-slate-700"}`}
            title="List view"
          >
            <ListIcon className="w-3.5 h-3.5" />
          </button>
          <button
            onClick={() => setView("grid")}
            className={`p-1.5 rounded-md transition-colors ${view === "grid" ? "bg-white shadow-sm text-slate-900" : "text-slate-500 hover:text-slate-700"}`}
            title="Grid view"
          >
            <LayoutGrid className="w-3.5 h-3.5" />
          </button>
        </div>
      </div>

      {/* Body — list or grid */}
      {loading && !data ? (
        view === "grid" ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            {Array.from({ length: 6 }).map((_, i) => <div key={i} className="h-44 rounded-xl bg-slate-100 animate-pulse" />)}
          </div>
        ) : (
          <TableSkeleton rows={6} cols={7} />
        )
      ) : !data || data.brands.length === 0 ? (
        <Card>
          <EmptyState
            icon={Building2}
            title="No brands match these filters"
            description="Adjust the search or plan filter."
          />
        </Card>
      ) : view === "list" ? (
        <DataTable
          columns={columns}
          rows={data.brands}
          rowKey={(b) => b.id}
          onRowClick={(b) => setSelectedId(b.id)}
          highlightKey={selectedId}
        />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
          {data.brands.map((b) => (
            <BrandCard
              key={b.id}
              brand={b}
              selected={selectedId === b.id}
              onClick={() => setSelectedId(b.id)}
            />
          ))}
        </div>
      )}

      {/* Pagination */}
      {data && data.total > data.limit && (
        <div className="flex items-center justify-between text-xs text-slate-500">
          <span>Page {page} of {totalPages}</span>
          <div className="flex items-center gap-2">
            <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1} className="inline-flex items-center gap-1 px-3 py-1.5 border border-slate-200 rounded-lg bg-white disabled:opacity-40">
              <ChevronLeft className="w-3 h-3" /> Prev
            </button>
            <button onClick={() => setPage((p) => p + 1)} disabled={!data.hasMore} className="inline-flex items-center gap-1 px-3 py-1.5 border border-slate-200 rounded-lg bg-white disabled:opacity-40">
              Next <ChevronRight className="w-3 h-3" />
            </button>
          </div>
        </div>
      )}

      {/* Detail drawer — preserved from prior commit, lightly polished */}
      {selectedId && (
        <div className="fixed inset-0 z-40 flex animate-in fade-in duration-150" onClick={() => setSelectedId(null)}>
          <div className="flex-1 bg-slate-900/50" />
          <aside className="w-[520px] max-w-full bg-white border-l border-slate-200 overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <header className="px-5 py-4 border-b border-slate-200 flex items-center justify-between">
              <h2 className="font-semibold text-slate-900">Brand detail</h2>
              <button onClick={() => setSelectedId(null)} className="p-1.5 rounded-lg hover:bg-slate-100"><X className="w-4 h-4" /></button>
            </header>
            {detailLoading || !detail ? (
              <div className="p-8 text-center text-slate-400 text-sm"><Loader2 className="w-4 h-4 animate-spin mx-auto mb-2" /> Loading…</div>
            ) : (
              <div className="p-5 space-y-5">
                <div className="flex items-start gap-3">
                  {detail.brand.logoUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={detail.brand.logoUrl} alt="" className="w-14 h-14 rounded-xl object-contain bg-slate-50 border border-slate-100" />
                  ) : (
                    <div className="w-14 h-14 rounded-xl bg-gradient-to-br from-slate-200 to-slate-300 flex items-center justify-center text-lg font-semibold text-slate-600">
                      {detail.brand.name[0]?.toUpperCase()}
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-slate-900 truncate">{detail.brand.name}</p>
                    <p className="text-xs text-slate-500 font-mono truncate">{detail.brand.domain}</p>
                    <div className="flex items-center gap-1.5 mt-1.5 flex-wrap">
                      <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${PLAN_BADGE[detail.brand.plan] ?? PLAN_BADGE.growth}`}>
                        {detail.brand.plan.replace("_", " ")}
                      </span>
                      {detail.brand.healthcareMode && (
                        <span className="text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-rose-50 text-rose-700 border border-rose-200">
                          Healthcare mode
                        </span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Action row */}
                <div className="flex items-center gap-2 flex-wrap">
                  <a href={`${APP_URL}?brandId=${detail.brand.id}`} target="_blank" rel="noopener noreferrer"
                     className="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold border border-slate-200 rounded-lg bg-white hover:bg-slate-50">
                    <ExternalLink className="w-3 h-3" /> View as user
                  </a>
                  <button onClick={() => transferBrand(data!.brands.find((b) => b.id === detail.brand.id)!)}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold border border-slate-200 rounded-lg bg-white hover:bg-slate-50">
                    <ArrowRightLeft className="w-3 h-3" /> Transfer
                  </button>
                  <button onClick={() => openDeleteModal(data!.brands.find((b) => b.id === detail.brand.id)!)}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-semibold border border-rose-200 rounded-lg bg-white text-rose-600 hover:bg-rose-50">
                    <Trash2 className="w-3 h-3" /> Delete
                  </button>
                </div>

                {/* Stats grid via shared StatCard */}
                <div className="grid grid-cols-3 gap-2">
                  <StatCard label="Tracked events" value={formatNumber(detail.stats.events)} variant="compact" />
                  <StatCard label="Sessions" value={formatNumber(detail.stats.sessions)} variant="compact" />
                  <StatCard label="Conversions" value={formatNumber(detail.stats.conversions)} variant="compact" valueClass="text-emerald-600" />
                  <StatCard label="GSC clicks 90d" value={formatNumber(detail.stats.gscClicks90d)} variant="compact" valueClass="text-blue-600" />
                  <StatCard label="GSC impr 90d" value={formatNumber(detail.stats.gscImpressions90d)} variant="compact" />
                  <StatCard label="Pages" value={formatNumber(detail.stats.pageRecords)} variant="compact" />
                </div>

                {/* Members + integrations + features (same as before) */}
                <Section icon={UsersIcon} title={`Members (${detail.members.length})`}>
                  <ul className="space-y-1.5">
                    {detail.members.map((m) => (
                      <li key={m.id} className="flex items-center gap-2 text-xs">
                        <span className="text-slate-700 flex-1 truncate">{m.user.name || m.user.email}</span>
                        <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500">{m.role}</span>
                      </li>
                    ))}
                  </ul>
                </Section>
                <Section icon={Globe} title={`Integrations (${detail.integrations.filter(i => i.connected).length} connected)`}>
                  {detail.integrations.length === 0 ? (
                    <p className="text-xs text-slate-400 italic">None yet</p>
                  ) : (
                    <ul className="space-y-1">
                      {detail.integrations.map((i) => (
                        <li key={i.integrationId} className="flex items-center gap-2 text-xs">
                          <Dot on={i.connected} label={i.integrationId} />
                          <span className="font-bold uppercase text-[10px] tracking-wider text-slate-500 w-12">{i.integrationId}</span>
                          <span className="flex-1 text-slate-700">{i.connected ? "Connected" : i.status || "Not connected"}</span>
                          {i.lastSynced && <span className="text-[10px] text-slate-400">{formatDate(i.lastSynced)}</span>}
                          {i.syncError && <AlertTriangle className="w-3 h-3 text-rose-500" />}
                        </li>
                      ))}
                    </ul>
                  )}
                </Section>
                <Section icon={Activity} title={`Feature adoption (${detail.featureAdoption.length})`}>
                  {detail.featureAdoption.length === 0 ? (
                    <p className="text-xs text-slate-400 italic">No telemetry yet</p>
                  ) : (
                    <ul className="space-y-1">
                      {detail.featureAdoption.slice(0, 12).map((f) => (
                        <li key={f.action} className="flex items-center gap-2 text-xs">
                          <span className="text-slate-700 flex-1 truncate">{f.action}</span>
                          <span className="text-slate-500 tabular-nums">{f.count}</span>
                        </li>
                      ))}
                    </ul>
                  )}
                </Section>
              </div>
            )}
          </aside>
        </div>
      )}

      {/* Delete confirmation modal */}
      {deleteTarget && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50" onClick={() => { setDeleteTarget(null); setDeleteConfirmText(""); }}>
          <div className="bg-white rounded-xl border border-slate-200 shadow-xl w-full max-w-md mx-4 p-6" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-xl bg-red-50 flex items-center justify-center shrink-0">
                <Trash2 className="w-5 h-5 text-red-600" />
              </div>
              <div>
                <h3 className="text-base font-bold text-slate-900">Delete brand</h3>
                <p className="text-xs text-slate-500 mt-0.5">This action cannot be undone.</p>
              </div>
            </div>

            <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 mb-4">
              <p className="text-sm text-red-800">
                Are you sure you want to delete <span className="font-bold">{deleteTarget.name}</span>? This will permanently delete all data including events, conversions, GSC history, and analytics.
              </p>
            </div>

            <label className="block text-sm font-semibold text-slate-700 mb-1.5">
              Type <span className="font-mono bg-slate-100 px-1.5 py-0.5 rounded text-red-600">{deleteTarget.name}</span> to confirm
            </label>
            <input
              type="text"
              value={deleteConfirmText}
              onChange={(e) => setDeleteConfirmText(e.target.value)}
              placeholder={deleteTarget.name}
              className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500/40 focus:border-red-500 mb-4"
              autoFocus
            />

            <div className="flex items-center gap-3 justify-end">
              <button
                onClick={() => { setDeleteTarget(null); setDeleteConfirmText(""); }}
                className="px-4 py-2 text-sm font-semibold text-slate-700 border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={confirmDeleteBrand}
                disabled={deleteConfirmText !== deleteTarget.name || deletingBrand}
                className="px-4 py-2 text-sm font-semibold text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {deletingBrand && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
                Delete Brand
              </button>
            </div>
          </div>
        </div>
      )}

      {toast && (
        <div className="fixed top-4 right-4 z-50 px-4 py-2 rounded-lg bg-slate-900 text-white text-xs font-semibold shadow-lg max-w-sm">
          {toast}
        </div>
      )}
    </div>
  );
}

// ─── Brand card (grid view) ──────────────────────────────────────

function BrandCard({ brand: b, selected, onClick }: { brand: BrandRow; selected: boolean; onClick: () => void }) {
  const score = b.lastAuditScore;
  const ringColor = score == null ? "stroke-slate-200" : score >= 80 ? "stroke-emerald-500" : score >= 50 ? "stroke-amber-500" : "stroke-rose-500";
  const ringPct = score ?? 0;
  const C = 2 * Math.PI * 18; // circumference
  return (
    <div
      onClick={onClick}
      className={`bg-white rounded-xl shadow-sm border cursor-pointer transition-all hover:shadow-md ${
        selected ? "border-brand-300 ring-2 ring-brand-500/20" : "border-slate-100"
      }`}
    >
      <div className="p-4">
        <div className="flex items-start gap-3 mb-3">
          {b.logoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={b.logoUrl} alt="" className="w-10 h-10 rounded-lg object-contain bg-slate-50 border border-slate-100" />
          ) : (
            <span className="w-10 h-10 rounded-lg bg-gradient-to-br from-slate-200 to-slate-300 text-slate-600 text-sm font-semibold flex items-center justify-center">
              {b.name[0]?.toUpperCase()}
            </span>
          )}
          <div className="min-w-0 flex-1">
            <p className="text-sm font-semibold text-slate-900 truncate">{b.name}</p>
            <p className="text-[10px] text-slate-500 font-mono truncate">{b.domain}</p>
          </div>
          {/* Health ring — SVG ring, score in the center. */}
          <div className="relative w-12 h-12 shrink-0">
            <svg viewBox="0 0 40 40" className="w-12 h-12 -rotate-90">
              <circle cx="20" cy="20" r="18" stroke="#F1F5F9" strokeWidth="3" fill="none" />
              <circle
                cx="20" cy="20" r="18"
                strokeWidth="3" fill="none"
                strokeLinecap="round"
                className={ringColor}
                strokeDasharray={`${(ringPct / 100) * C} ${C}`}
              />
            </svg>
            <span className="absolute inset-0 flex items-center justify-center text-[11px] font-semibold tabular-nums text-slate-700">
              {score ?? "—"}
            </span>
          </div>
        </div>

        {/* Plan + integration dots */}
        <div className="flex items-center gap-2 mb-3">
          <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${PLAN_BADGE[b.plan] ?? PLAN_BADGE.growth}`}>
            {b.plan.replace("_", " ")}
          </span>
          <div className="flex items-center gap-1 ml-auto" title={`GA4 ${b.ga4Connected ? "✓" : "✗"} · GSC ${b.gscConnected ? "✓" : "✗"} · GBP ${b.gbpConnected ? "✓" : "✗"} · Tag ${b.siteTagInstalled ? "✓" : "✗"}`}>
            <Dot on={b.ga4Connected} label="GA4" />
            <Dot on={b.gscConnected} label="GSC" />
            <Dot on={b.gbpConnected} label="GBP" />
            <Dot on={b.siteTagInstalled} label="Tag" />
          </div>
        </div>

        {/* Quick stats */}
        <div className="grid grid-cols-3 gap-2 text-center">
          <div>
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Events</p>
            <p className="text-xs font-semibold text-slate-800 tabular-nums">{formatNumber(b.totalEvents)}</p>
          </div>
          <div>
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Members</p>
            <p className="text-xs font-semibold text-slate-800 tabular-nums">{b.memberCount}</p>
          </div>
          <div>
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Active</p>
            <p className="text-[11px] font-semibold text-slate-700">{formatRelative(b.lastActivityAt ?? b.siteTagLastEventAt)}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

function Dot({ on, label }: { on: boolean; label: string }) {
  return (
    <span
      className={`w-1.5 h-1.5 rounded-full ${on ? "bg-emerald-500" : "bg-slate-300"}`}
      title={`${label}: ${on ? "Connected" : "Not connected"}`}
    />
  );
}

function Section({ icon: Icon, title, children }: { icon: typeof Globe; title: string; children: React.ReactNode }) {
  return (
    <div>
      <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5 flex items-center gap-1.5">
        <Icon className="w-3 h-3" /> {title}
      </p>
      {children}
    </div>
  );
}

void CardHeader;
