"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useBrand } from "@/context/brand-context";
import {
  Building2,
  Globe,
  Plug,
  CheckCircle2,
  Clock,
  LayoutDashboard,
  TrendingUp,
  AlertTriangle,
  Zap,
  AlertOctagon,
  TrendingDown,
  Sparkles,
  ListChecks,
  Rocket,
  ArrowUpRight,
  ArrowDownRight,
  DollarSign,
  Target,
  ClipboardList,
  Users,
  Briefcase,
  Factory,
  Loader2,
  Plus,
  Search,
  ArrowUpDown,
  Trash2,
} from "lucide-react";

// ─── Brand Avatar ────────────────────────────────────────────────────────────

function BrandAvatar({ logoUrl, initials, color, size = "w-9 h-9" }: {
  logoUrl: string | null;
  initials: string;
  color: string;
  size?: string;
}) {
  const [imgError, setImgError] = useState(false);
  const hasLogo = !!logoUrl && logoUrl.trim() !== "" && !imgError;

  // Reset error state when logoUrl changes
  useEffect(() => { setImgError(false); }, [logoUrl]);

  if (hasLogo) {
    return (
      <div className={`${size} rounded-lg overflow-hidden bg-white border border-slate-100 shrink-0`}>
        <img
          src={logoUrl!}
          alt={initials}
          className="w-full h-full object-cover"
          onError={() => setImgError(true)}
        />
      </div>
    );
  }

  return (
    <div className={`${size} rounded-lg ${color} flex items-center justify-center shrink-0`}>
      <span className="text-[11px] font-bold text-white">{initials}</span>
    </div>
  );
}

// ─── Types ────────────────────────────────────────────────────────────────────

type Grouping = "none" | "industry";

type SetupState = "setup-needed" | "partially-connected" | "ready" | "needs-attention";

interface BrandEntry {
  id:            string;
  name:          string;
  domain:        string;
  industry:      string;
  status:        "active" | "onboarding" | "paused";
  lastUpdated:   string;
  initials:      string;
  color:         string;
  // Profile data
  logoUrl:       string | null;
  description:   string | null;
  primaryColor:  string | null;
  brandVoice:    string | null;
  // Real integration data
  connectedIntegrations: number;
  totalIntegrations:     number;
  hasWebsite:    boolean;
  hasSiteTag:    boolean;
  hasGa4:       boolean;
  hasGsc:       boolean;
  ga4Stale:     boolean;
  gscStale:     boolean;
  hasExpiredIntegration: boolean;
  siteTagStatus: string | null;
  lastEventAt:   string | null;
  setupState:    SetupState;
}

const GROUPING_OPTIONS: { key: Grouping; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
  { key: "none",     label: "All Brands",  icon: Building2 },
  { key: "industry", label: "By Industry", icon: Factory   },
];

const STATUS_CFG: Record<string, { label: string; cls: string }> = {
  active:     { label: "Active",      cls: "bg-green-50 text-green-700 border-green-200"  },
  onboarding: { label: "Onboarding", cls: "bg-amber-50 text-amber-700 border-amber-200"  },
  paused:     { label: "Paused",      cls: "bg-slate-100 text-slate-500 border-slate-200" },
};

const SETUP_CFG: Record<SetupState, { label: string; cls: string }> = {
  "setup-needed":        { label: "Setup Needed",        cls: "bg-red-50 text-red-700 border-red-200" },
  "partially-connected": { label: "Partially Connected", cls: "bg-amber-50 text-amber-700 border-amber-200" },
  "ready":               { label: "Ready",               cls: "bg-green-50 text-green-700 border-green-200" },
  "needs-attention":     { label: "Needs Attention",     cls: "bg-orange-50 text-orange-700 border-orange-200" },
};

function calcSetupState(b: { hasSiteTag: boolean; hasGa4: boolean; hasGsc: boolean; ga4Stale: boolean; gscStale: boolean }): SetupState {
  // Ready = Site Tag active + at least one non-stale analytics source
  const ga4Live = b.hasGa4 && !b.ga4Stale;
  const gscLive = b.hasGsc && !b.gscStale;
  const hasSources = [b.hasSiteTag, b.hasGa4, b.hasGsc].filter(Boolean).length;
  if (hasSources === 0) return "setup-needed";
  if (b.hasSiteTag && (ga4Live || gscLive)) return "ready";
  return "partially-connected";
}

function capitalizeIndustry(name: string): string {
  return name.split(" ").map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ");
}

type SortKey = "alpha-az" | "alpha-za" | "most-integrations" | "least-integrations" | "recent-activity" | "oldest-activity" | "needs-attention" | "ready-first";

const SORT_OPTIONS: { key: SortKey; label: string }[] = [
  { key: "recent-activity", label: "Recently Active" },
  { key: "oldest-activity", label: "Oldest Activity" },
  { key: "alpha-az", label: "Alphabetical (A-Z)" },
  { key: "alpha-za", label: "Alphabetical (Z-A)" },
  { key: "most-integrations", label: "Most Integrations" },
  { key: "least-integrations", label: "Least Integrations" },
  { key: "needs-attention", label: "Needs Attention First" },
  { key: "ready-first", label: "Ready First" },
];

const SETUP_ORDER: Record<SetupState, number> = { "setup-needed": 0, "needs-attention": 1, "partially-connected": 2, "ready": 3 };

function sortBrands(list: BrandEntry[], sortKey: SortKey): BrandEntry[] {
  const sorted = [...list];
  switch (sortKey) {
    case "alpha-az": return sorted.sort((a, b) => a.name.localeCompare(b.name));
    case "alpha-za": return sorted.sort((a, b) => b.name.localeCompare(a.name));
    case "most-integrations": return sorted.sort((a, b) => b.connectedIntegrations - a.connectedIntegrations);
    case "least-integrations": return sorted.sort((a, b) => a.connectedIntegrations - b.connectedIntegrations);
    case "recent-activity": return sorted.sort((a, b) => b.lastUpdated.localeCompare(a.lastUpdated));
    case "oldest-activity": return sorted.sort((a, b) => a.lastUpdated.localeCompare(b.lastUpdated));
    case "needs-attention": return sorted.sort((a, b) => (SETUP_ORDER[a.setupState] ?? 9) - (SETUP_ORDER[b.setupState] ?? 9));
    case "ready-first": return sorted.sort((a, b) => (SETUP_ORDER[b.setupState] ?? 0) - (SETUP_ORDER[a.setupState] ?? 0));
    default: return sorted;
  }
}

function getGroupKey(brand: BrandEntry, grouping: Grouping): string {
  if (grouping === "industry") return capitalizeIndustry(brand.industry);
  return "all";
}

function groupBrands(brands: BrandEntry[], grouping: Grouping): Map<string, BrandEntry[]> {
  const map = new Map<string, BrandEntry[]>();
  for (const b of brands) {
    const key = getGroupKey(b, grouping);
    if (!map.has(key)) map.set(key, []);
    map.get(key)!.push(b);
  }
  return map;
}

export default function BrandsHubPage() {
  const { orgId } = useBrand();
  const router = useRouter();
  const [grouping, setGrouping] = useState<Grouping>("none");
  const [brands, setBrands] = useState<BrandEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sortKey, setSortKey] = useState<SortKey>(() => {
    if (typeof window !== "undefined") return (localStorage.getItem("meseo_brands_sort") as SortKey) || "recent-activity";
    return "recent-activity";
  });
  const [searchQuery, setSearchQuery] = useState("");
  const [deleteTarget, setDeleteTarget] = useState<BrandEntry | null>(null);
  const [deleteConfirmText, setDeleteConfirmText] = useState("");
  const [deleting, setDeleting] = useState(false);

  // Fetch real brands from the API using shared orgId
  const loadBrands = useCallback(async (orgId: string) => {
    setLoading(true);
    setError(null);
    try {
      if (!orgId) { setError("No organization found"); setLoading(false); return; }

      // Fetch brands for this org
      const res = await fetch(`/api/brands?orgId=${orgId}`, { cache: "no-store" });
      if (!res.ok) { setError("Failed to load brands"); setLoading(false); return; }
      const data = await res.json();

      // Map database brands to the BrandEntry shape
      const mapped: BrandEntry[] = (data as Array<Record<string, unknown>>).map((b) => {
        const profile = b.profile as { logoUrl?: string; primaryColor?: string; shortDescription?: string; brandVoice?: string } | null;
        const integrations = (b.integrations as Array<{ integrationId: string; connected: boolean; status: string; lastSynced: string | null }>) ?? [];
        const trackedSite = b.trackedSite as { siteId: string; status: string; lastEventAt: string | null } | null;
        const siteTagHasData = !!b.siteTagHasData;
        const websites = (b.websites as Array<unknown>) ?? [];

        const STALE_MS = 30 * 86400000; // 30 days
        function isStale(i: { lastSynced: string | null }): boolean {
          if (!i.lastSynced) return false; // no sync yet ≠ stale
          return Date.now() - new Date(i.lastSynced).getTime() > STALE_MS;
        }

        // connected=true is the source of truth (matches /integrations page)
        const connectedIntegrations = integrations.filter(i => i.connected).length;
        const ga4Int = integrations.find(i => i.integrationId === "ga4");
        const gscInt = integrations.find(i => i.integrationId === "gsc");
        const hasGa4 = !!ga4Int && ga4Int.connected;
        const hasGsc = !!gscInt && gscInt.connected;
        const ga4Stale = hasGa4 && isStale(ga4Int!);
        const gscStale = hasGsc && isStale(gscInt!);
        const hasExpiredIntegration = integrations.some(i => i.status === "expired");
        const hasSiteTag = siteTagHasData;
        const hasWebsite = websites.length > 0;

        // Last synced: most recent integration sync or site tag event
        const syncTimes = integrations.filter(i => i.lastSynced).map(i => new Date(i.lastSynced!).getTime());
        if (trackedSite?.lastEventAt) syncTimes.push(new Date(trackedSite.lastEventAt).getTime());
        const lastSync = syncTimes.length > 0 ? new Date(Math.max(...syncTimes)) : null;

        const entry: BrandEntry = {
          id: b.id as string,
          name: b.name as string,
          domain: b.domain as string,
          industry: (b.industry as string) ?? "General",
          status: (b.status as string) === "active" ? "active" : "onboarding",
          lastUpdated: lastSync
            ? lastSync.toLocaleDateString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })
            : new Date(b.createdAt as string).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }),
          initials: (b.initials as string) ?? (b.name as string).slice(0, 2).toUpperCase(),
          color: (b.color as string) ?? "bg-brand-500",
          logoUrl: profile?.logoUrl ?? null,
          description: profile?.shortDescription ?? null,
          primaryColor: profile?.primaryColor ?? null,
          brandVoice: profile?.brandVoice ?? null,
          connectedIntegrations,
          totalIntegrations: integrations.length,
          hasWebsite,
          hasSiteTag,
          hasGa4,
          hasGsc,
          ga4Stale,
          gscStale,
          hasExpiredIntegration,
          siteTagStatus: trackedSite?.status ?? null,
          lastEventAt: trackedSite?.lastEventAt ?? null,
          setupState: "setup-needed",
        };
        entry.setupState = calcSetupState(entry);
        return entry;
      });

      setBrands(mapped);
    } catch {
      setError("Network error — please try again");
    }
    setLoading(false);
  }, []);

  useEffect(() => { if (orgId) loadBrands(orgId); }, [orgId, loadBrands]);

  // Persist sort preference
  function handleSort(key: SortKey) { setSortKey(key); localStorage.setItem("meseo_brands_sort", key); }

  async function handleDeleteBrand() {
    if (!deleteTarget || deleteConfirmText !== deleteTarget.name) return;
    setDeleting(true);
    try {
      const res = await fetch(`/api/brands/${deleteTarget.id}`, { method: "DELETE" });
      if (res.ok) {
        setBrands((prev) => prev.filter((b) => b.id !== deleteTarget.id));
        setDeleteTarget(null);
        setDeleteConfirmText("");
        router.refresh();
      } else {
        const data = await res.json().catch(() => ({}));
        setError(data.error || "Failed to delete brand");
      }
    } catch {
      setError("Network error — please try again");
    }
    setDeleting(false);
  }

  // Filter + sort
  const q = searchQuery.toLowerCase();
  const filtered = q ? brands.filter((b) => b.name.toLowerCase().includes(q) || b.domain.toLowerCase().includes(q)) : brands;
  const sorted = sortBrands(filtered, sortKey);

  const activeBrands = brands.filter((b) => b.status === "active").length;
  const readyBrands = brands.filter(b => b.setupState === "ready").length;
  const needsSetup = brands.filter(b => b.setupState === "setup-needed").length;
  const totalConnected = brands.reduce((s, b) => s + b.connectedIntegrations, 0);
  const grouped = groupBrands(sorted, grouping);

  // Priority brands: needs setup or partially connected
  const priorityBrands = brands.filter(
    (b) =>
      b.setupState === "setup-needed" ||
      b.setupState === "needs-attention" ||
      b.setupState === "partially-connected" ||
      b.hasExpiredIntegration,
  ).map((b) => {
    const reasons: { label: string; cls: string; icon: React.ComponentType<{ className?: string }>; href: string }[] = [];
    if (b.setupState === "setup-needed")
      reasons.push({ label: "Setup Needed", cls: "bg-red-50 text-red-700 border-red-200", icon: AlertOctagon, href: "/integrations" });
    if (!b.hasSiteTag)
      reasons.push({ label: "No Site Tag", cls: "bg-amber-50 text-amber-700 border-amber-200", icon: AlertTriangle, href: "/site-tag" });
    if (!b.hasGa4)
      reasons.push({ label: "GA4 Not Connected", cls: "bg-orange-50 text-orange-700 border-orange-200", icon: AlertTriangle, href: "/integrations" });
    if (!b.hasGsc)
      reasons.push({ label: "GSC Not Connected", cls: "bg-blue-50 text-blue-700 border-blue-200", icon: Zap, href: "/integrations" });
    if (b.hasExpiredIntegration)
      reasons.push({ label: "Token Expired", cls: "bg-amber-50 text-amber-700 border-amber-200", icon: AlertTriangle, href: "/integrations" });
    return { brand: b, reasons };
  });

  return (
    <div className="space-y-6">
      {/* ── Header ── */}
      <div>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
            <Building2 className="w-5 h-5 text-brand-600" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-slate-900">Brands Hub</h1>
            <p className="text-slate-500 text-sm mt-0.5">
              Manage all your brands and client websites in one place.
            </p>
          </div>
          <Link href="/website-upload" className="ml-auto flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors shrink-0">
            <Plus className="w-4 h-4" /> Add Brand
          </Link>
        </div>
      </div>

      {/* ── Loading state ── */}
      {loading && (
        <div className="flex items-center justify-center py-24">
          <Loader2 className="w-6 h-6 text-brand-500 animate-spin" />
        </div>
      )}

      {/* ── Error state ── */}
      {error && !loading && (
        <div className="bg-red-50 border border-red-200 rounded-xl px-6 py-4 text-center">
          <p className="text-sm font-semibold text-red-700">{error}</p>
          <button onClick={() => loadBrands(orgId)} className="mt-2 text-xs font-semibold text-red-600 underline">Try again</button>
        </div>
      )}

      {/* ── Empty state ── */}
      {!loading && !error && brands.length === 0 && (
        <div className="bg-white rounded-xl border border-slate-200 px-6 py-12 text-center">
          <Building2 className="w-10 h-10 text-slate-200 mx-auto mb-3" />
          <h2 className="text-lg font-bold text-slate-900 mb-1">No brands yet</h2>
          <p className="text-sm text-slate-500 mb-4">Add your first brand to start tracking SEO performance.</p>
          <Link href="/website-upload" className="inline-flex items-center gap-1.5 px-5 py-2.5 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors">
            <Plus className="w-4 h-4" /> Add Your First Brand
          </Link>
        </div>
      )}

      {/* ── Main content (only show when brands loaded) ── */}
      {!loading && !error && brands.length > 0 && (<>

      {/* ── Summary cards ── */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
          <p className="text-xs text-slate-400 font-semibold uppercase tracking-wide">Total Brands</p>
          <p className="text-3xl font-bold text-slate-900 mt-1">{brands.length}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
          <p className="text-xs text-slate-400 font-semibold uppercase tracking-wide">Ready</p>
          <p className="text-3xl font-bold text-green-600 mt-1">{readyBrands}</p>
          <p className="text-[10px] text-slate-400 mt-0.5">{needsSetup > 0 ? `${needsSetup} need setup` : "All brands configured"}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
          <p className="text-xs text-slate-400 font-semibold uppercase tracking-wide">Integrations</p>
          <p className="text-3xl font-bold text-brand-600 mt-1">{totalConnected}</p>
          <p className="text-[10px] text-slate-400 mt-0.5">connected across all brands</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
          <p className="text-xs text-slate-400 font-semibold uppercase tracking-wide">Active</p>
          <p className="text-3xl font-bold text-slate-900 mt-1">{activeBrands}</p>
          <p className="text-[10px] text-slate-400 mt-0.5">of {brands.length} brands</p>
        </div>
      </div>

      {/* ── Priority Brands ── */}
      {priorityBrands.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-amber-500" />
            <h2 className="font-semibold text-slate-800 text-sm">Priority Brands</h2>
            <span className="text-[10px] font-semibold text-amber-600 bg-amber-50 border border-amber-200 rounded-full px-2 py-0.5">
              {priorityBrands.length} need{priorityBrands.length === 1 ? "s" : ""} review
            </span>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-5">
            {priorityBrands.map(({ brand, reasons }) => (
              <div key={brand.id} className="rounded-xl border border-slate-200 p-4 hover:border-slate-300 hover:shadow-sm transition-all">
                <div className="flex items-center gap-3 mb-3">
                  <BrandAvatar logoUrl={brand.logoUrl} initials={brand.initials} color={brand.color} />
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-semibold text-slate-800 truncate">{brand.name}</p>
                    <p className="text-[11px] text-slate-400 font-mono truncate">{brand.domain}</p>
                  </div>
                  <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full border ${SETUP_CFG[brand.setupState].cls}`}>
                    {SETUP_CFG[brand.setupState].label}
                  </span>
                </div>

                {/* Reason tags — clickable */}
                <div className="flex flex-wrap gap-1.5">
                  {reasons.map(({ label, cls, icon: ReasonIcon, href }) => (
                    <Link key={label} href={href} className={`inline-flex items-center gap-1 text-[10px] font-semibold rounded-full px-2 py-0.5 border cursor-pointer hover:opacity-80 transition-opacity ${cls}`}>
                      <ReasonIcon className="w-2.5 h-2.5" />
                      {label}
                    </Link>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Controls: grouping + search + sort ── */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex items-center bg-slate-100 rounded-xl p-1 gap-1">
          {GROUPING_OPTIONS.map(({ key, label, icon: Icon }) => (
            <button
              key={key}
              onClick={() => setGrouping(key)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold transition-colors ${
                grouping === key
                  ? "bg-white text-slate-900 shadow-sm"
                  : "text-slate-500 hover:text-slate-700"
              }`}
            >
              <Icon className="w-3.5 h-3.5" />
              {label}
            </button>
          ))}
        </div>

        {/* Search */}
        <div className="relative">
          <Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
          <input
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Filter brands..."
            className="pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg w-52 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500 bg-white"
          />
        </div>
        {searchQuery && (
          <span className="text-xs text-slate-500">{filtered.length} brand{filtered.length !== 1 ? "s" : ""} matching</span>
        )}

        {/* Sort */}
        <div className="flex items-center gap-1.5 ml-auto">
          <ArrowUpDown className="w-3.5 h-3.5 text-slate-400" />
          <select
            value={sortKey}
            onChange={(e) => handleSort(e.target.value as SortKey)}
            className="text-sm border border-slate-200 rounded-lg px-3 py-2 bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/40"
          >
            {SORT_OPTIONS.map((o) => <option key={o.key} value={o.key}>{o.label}</option>)}
          </select>
        </div>
      </div>

      {/* ── Brands list (grouped) ── */}
      {Array.from(grouped.entries()).map(([group, brands]) => (
        <div key={group} className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
            <Building2 className="w-4 h-4 text-brand-600" />
            <h2 className="font-semibold text-slate-800 text-sm">
              {grouping === "none" ? "All Brands" : group}
            </h2>
            <span className="ml-auto text-xs text-slate-400">{brands.length} brand{brands.length !== 1 ? "s" : ""}</span>
          </div>

          {/* Column headers */}
          <div className="grid grid-cols-[minmax(160px,1fr)_minmax(180px,1.2fr)_90px_90px_110px] gap-2 px-6 py-2.5 bg-slate-50 border-b border-slate-100 text-[10px] font-bold uppercase tracking-widest text-slate-400">
            <span>Brand</span>
            <span>Domain</span>
            <span>Setup</span>
            <span>Integrations</span>
            <span>Last Activity</span>
          </div>

          <div className="divide-y divide-slate-100">
            {brands.map((brand) => {
              const status = STATUS_CFG[brand.status] ?? STATUS_CFG.onboarding;
              const setup = SETUP_CFG[brand.setupState];
              return (
                <div key={brand.id} className="hover:bg-slate-50/50 transition-colors" style={brand.primaryColor ? { borderLeft: `3px solid ${brand.primaryColor}` } : undefined}>
                  <div className="grid grid-cols-[minmax(160px,1fr)_minmax(180px,1.2fr)_90px_90px_110px] gap-2 px-6 py-4 items-center">
                    {/* Brand name + status */}
                    <div className="flex items-center gap-3">
                      <BrandAvatar logoUrl={brand.logoUrl} initials={brand.initials} color={brand.color} />
                      <div className="min-w-0">
                        <p className="text-sm font-semibold text-slate-800 truncate">{brand.name}</p>
                        <p className="text-[10px] text-slate-400">{capitalizeIndustry(brand.industry)}</p>
                      </div>
                      <span className={`inline-flex items-center gap-1 text-[10px] font-semibold rounded-full px-2 py-0.5 border shrink-0 ${status.cls}`}>
                        {brand.status === "active" && <CheckCircle2 className="w-3 h-3" />}
                        {status.label}
                      </span>
                    </div>

                    {/* Domain */}
                    <a href={`https://${brand.domain}`} target="_blank" rel="noopener noreferrer" className="text-sm font-mono text-brand-600 truncate hover:underline" title={brand.domain}>{brand.domain}</a>

                    {/* Setup state */}
                    <span className={`inline-flex items-center gap-1 text-[10px] font-semibold rounded-full px-2 py-0.5 border w-fit ${setup.cls}`}>
                      {brand.setupState === "ready" && <CheckCircle2 className="w-3 h-3" />}
                      {brand.setupState === "setup-needed" && <AlertTriangle className="w-3 h-3" />}
                      {setup.label}
                    </span>

                    {/* Integrations */}
                    <div className="flex items-center gap-1.5 flex-wrap">
                      <Plug className={`w-3 h-3 shrink-0 ${brand.hasExpiredIntegration ? "text-amber-500" : "text-slate-400"}`} />
                      <span className="text-xs text-slate-600">{brand.connectedIntegrations} connected</span>
                      {brand.hasExpiredIntegration && (
                        <span title="One or more integrations have expired tokens" className="inline-flex items-center gap-0.5 text-[9px] font-bold text-amber-700 bg-amber-50 border border-amber-200 rounded-full px-1.5 py-0.5 shrink-0">
                          <AlertTriangle className="w-2.5 h-2.5" /> Expired
                        </span>
                      )}
                    </div>

                    {/* Last activity */}
                    <span className="text-xs text-slate-500">{brand.lastUpdated}</span>
                  </div>

                  {/* Setup checklist row — clickable badges */}
                  <div className="px-6 py-2 ml-12 flex items-center gap-3 flex-wrap">
                    {[
                      { label: "Website", ok: brand.hasWebsite, stale: false, hrefOk: `https://${brand.domain}`, hrefMissing: "/website-upload", external: true },
                      { label: "Site Tag", ok: brand.hasSiteTag, stale: false, hrefOk: "/site-tag", hrefMissing: "/site-tag", external: false },
                      { label: "GA4", ok: brand.hasGa4, stale: brand.ga4Stale, hrefOk: "/dashboard", hrefMissing: "/integrations", external: false },
                      { label: "GSC", ok: brand.hasGsc, stale: brand.gscStale, hrefOk: "/dashboard", hrefMissing: "/integrations", external: false },
                    ].map(check => {
                      const href = check.ok ? check.hrefOk : check.hrefMissing;
                      const cls = check.stale ? "bg-amber-50 text-amber-700" : check.ok ? "bg-green-50 text-green-700" : "bg-slate-100 text-slate-400";
                      const inner = (
                        <>
                          {check.stale ? <Clock className="w-3 h-3" /> : check.ok ? <CheckCircle2 className="w-3 h-3" /> : <Clock className="w-3 h-3" />}
                          {check.label}{check.stale ? " (stale)" : ""}
                        </>
                      );
                      return check.external && check.ok ? (
                        <a key={check.label} href={href} target="_blank" rel="noopener noreferrer" className={`inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded cursor-pointer hover:opacity-80 transition-opacity ${cls}`}>{inner}</a>
                      ) : (
                        <Link key={check.label} href={href} className={`inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded cursor-pointer hover:opacity-80 transition-opacity ${cls}`}>{inner}</Link>
                      );
                    })}
                    <div className="flex items-center gap-2 ml-auto">
                      <button
                        onClick={() => { setDeleteTarget(brand); setDeleteConfirmText(""); }}
                        className="text-[10px] font-semibold text-red-500 hover:text-red-700 transition-colors"
                      >
                        Delete
                      </button>
                      <Link href={`/brands/${brand.id}/edit`} className="text-[10px] font-semibold text-slate-600 hover:text-slate-800 transition-colors">
                        Edit
                      </Link>
                      <Link href="/integrations" className="text-[10px] font-semibold text-brand-600 hover:text-brand-700">
                        Manage →
                      </Link>
                    </div>
                  </div>

                  {/* Quick actions */}
                  <div className="px-6 pb-3 flex items-center gap-2 ml-12 flex-wrap">
                    {[
                      { href: "/dashboard",                icon: LayoutDashboard, label: "Dashboard",                requiresData: false },
                      { href: "/execution-hub",            icon: ListChecks,      label: "Execution Hub",            requiresData: false },
                      { href: "/site-tag-analytics",       icon: TrendingUp,      label: "Site Tag Analytics",       requiresData: true },
                      { href: "/page-launch-tracker",      icon: Rocket,          label: "Performance Since Launch",  requiresData: true },
                      { href: "/report-studio",            icon: ClipboardList,   label: "Report Studio",            requiresData: false },
                      { href: "/integrations",             icon: Plug,            label: "Integrations",             requiresData: false },
                    ].map(action => {
                      const disabled = action.requiresData && brand.setupState === "setup-needed";
                      const tooltip = disabled ? (!brand.hasSiteTag ? "Install Site Tag for full tracking" : "Connect GA4 or GSC first") : undefined;
                      const ActionIcon = action.icon;
                      return disabled ? (
                        <span key={action.label} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-100 text-xs font-medium text-slate-300 cursor-not-allowed" title={tooltip}>
                          <ActionIcon className="w-3 h-3" />
                          {action.label}
                        </span>
                      ) : (
                        <Link key={action.label} href={action.href} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-colors">
                          <ActionIcon className="w-3 h-3" />
                          {action.label}
                        </Link>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </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={handleDeleteBrand}
                disabled={deleteConfirmText !== deleteTarget.name || deleting}
                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"
              >
                {deleting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
                Delete Brand
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
