"use client";

/**
 * meSEO Site Tag Management  (/site-tag)
 * ----------------------------------------
 * Setup / configuration area for the Machine Enhancing Tracking ID system.
 *
 * Event data (Recent Events feed, Data Reconciliation, Events Overview,
 * by-type breakdown) now lives on Site Tag Analytics → Overview tab. This
 * page intentionally stays focused on:
 *   1. Header with brand context
 *   2. Setup CTA (if no tag exists yet)
 *   3. Tracking health + status strip
 *   4. Tag controls (pause / regenerate)
 *   5. Allowed domains
 *   6. Install snippet
 *   7. Custom event configuration + observed events
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { useBrand } from "@/context/brand-context";
import { CustomEvents } from "./custom-events";
import { DataMaturityNotice } from "@/components/ui/data-maturity-notice";
import {
  Code2, CheckCircle2, XCircle, Clock, Copy, Loader2, Zap, Activity,
  Globe, Puzzle,
  Eye, BarChart3, Shield, RefreshCw, Power, Plus, Trash2, AlertTriangle,
  HeartPulse, Users, Layers,
  Send, CircleDot,
} from "lucide-react";

interface SiteInfo {
  siteId: string;
  status: string;
  allowedDomains: string[];
  lastEventAt: string | null;
  createdAt: string;
  snippet: string;
}

// Event type config used to be here but now lives on Site Tag Analytics,
// which is the only place in the app that renders individual events.

// ─── Page ────────────────────────────────────────────────────────────────────

export default function SiteTagPage() {
  const { brand } = useBrand();

  const [site, setSite] = useState<SiteInfo | null>(null);
  const [eventsToday, setEventsToday] = useState(0);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [copied, setCopied] = useState(false);
  const [actionMsg, setActionMsg] = useState<string | null>(null);
  const [newDomain, setNewDomain] = useState("");
  const [domainError, setDomainError] = useState<string | null>(null);
  const [showAddDomain, setShowAddDomain] = useState(false);
  const [confirmRegenKey, setConfirmRegenKey] = useState(false);
  const [testStatus, setTestStatus] = useState<"idle" | "sending" | "success" | "error">("idle");
  const [domainStatus, setDomainStatus] = useState<Array<{ domain: string; status: "verified" | "pending" | "mismatch"; eventsToday: number; lastEventAt: string | null }>>([]);
  const [customEventsList, setCustomEventsList] = useState<Array<{ name: string; count: number; lastFired: string }>>([]);
  const [pluginsDetected, setPluginsDetected] = useState<Array<{
    name: string; key: string; firstSeenAt: string; lastSeenAt: string;
    trackingLevel: "full" | "limited"; trackingNote: string;
  }>>([]);
  const [analytics, setAnalytics] = useState<{
    pageViews: number; sessions: number; pagesPerSession: number;
    conversions: number; conversionRate: number; customEvents: number;
    topPages: Array<{ url: string; views: number }>;
    topConvertingPages: Array<{ url: string; conversions: number }>;
  } | null>(null);
  const [sessionsToday, setSessionsToday] = useState(0);
  const [eventsPerHour, setEventsPerHour] = useState<number[]>([]);
  const [health, setHealth] = useState<{
    tagInstalled: boolean;
    tagActive: boolean;
    domainsConfigured: boolean;
    receivingEvents: boolean;
    sessionsToday: number;
    lastEventAge: number | null;
  } | null>(null);
  const [siteTagAge, setSiteTagAge] = useState(0);
  const [siteTagInstalledAt, setSiteTagInstalledAt] = useState<string | null>(null);
  const [pollingStopped, setPollingStopped] = useState(false);
  const pollInFlightRef = useRef(false);
  const pollFailCountRef = useRef(0);
  const stopPollRef = useRef(false);

  const loadSiteTag = useCallback(async () => {
    if (!brand?.id) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/site-tag?brandId=${brand.id}`, { cache: "no-store" });
      if (!res.ok) { setLoading(false); return; }
      const data = await res.json();
      setSite(data.site ?? null);
      setEventsToday(data.eventsToday ?? 0);
      setSessionsToday(data.sessionsToday ?? 0);
      setEventsPerHour(data.eventsPerHour ?? []);
      setHealth(data.health ?? null);
      setDomainStatus(data.domainStatus ?? []);
      setCustomEventsList(data.customEventsList ?? []);
      setPluginsDetected(data.pluginsDetected ?? []);
      setSiteTagAge(data.siteTagAge ?? 0);
      setSiteTagInstalledAt(data.installedAt ?? null);
      setAnalytics(data.analytics ?? null);
    } catch { /* ignore */ }
    setLoading(false);
  }, [brand.id]);

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

  // ── Manual refresh button (re-fetches everything, shows spinner) ──
  const [refreshing, setRefreshing] = useState(false);
  async function handleRefresh() {
    stopPollRef.current = false;
    pollFailCountRef.current = 0;
    setPollingStopped(false);
    setRefreshing(true);
    try { await loadSiteTag(); } finally {
      setTimeout(() => setRefreshing(false), 300);
    }
  }

  // ── Light polling for health/activity indicators ──
  useEffect(() => {
    if (!brand.id || !site) return;
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout>;

    async function pollHealth() {
      if (cancelled) return;
      if (stopPollRef.current) return;
      if (typeof document !== "undefined" && document.visibilityState !== "visible") {
        timer = setTimeout(pollHealth, 30_000);
        return;
      }
      if (pollInFlightRef.current) {
        timer = setTimeout(pollHealth, 30_000);
        return;
      }
      pollInFlightRef.current = true;
      const controller = new AbortController();
      const abortTimer = setTimeout(() => controller.abort(), 45_000);
      try {
        const res = await fetch(`/api/site-tag/heartbeat?brandId=${brand.id}`, { cache: "no-store", signal: controller.signal });
        if (!res.ok) {
          pollFailCountRef.current += 1;
          if (pollFailCountRef.current >= 3) {
            stopPollRef.current = true;
            setPollingStopped(true);
          }
        } else {
          pollFailCountRef.current = 0;
          const data = await res.json();
          setEventsToday(data.eventsToday ?? 0);
          // Merge heartbeat fields into existing health shape — preserves
          // domainsConfigured and sessionsToday from the full mount load.
          setHealth(prev => prev ? {
            ...prev,
            tagActive: data.status === "active",
            tagInstalled: data.installed ?? false,
            receivingEvents: data.eventsToday > 0,
            lastEventAge: data.lastEventAt
              ? Math.floor((Date.now() - new Date(data.lastEventAt).getTime()) / 60000)
              : prev.lastEventAge,
          } : prev);
        }
      } catch {
        pollFailCountRef.current += 1;
        if (pollFailCountRef.current >= 3) {
          stopPollRef.current = true;
          setPollingStopped(true);
        }
      } finally {
        clearTimeout(abortTimer);
        pollInFlightRef.current = false;
        if (!cancelled && !stopPollRef.current) {
          timer = setTimeout(pollHealth, 30_000);
        }
      }
    }

    function onVisibilityChange() {
      if (document.visibilityState === "visible" && !stopPollRef.current && !pollInFlightRef.current) {
        clearTimeout(timer);
        pollHealth();
      }
    }

    timer = setTimeout(pollHealth, 30_000);
    document.addEventListener("visibilitychange", onVisibilityChange);
    return () => {
      cancelled = true;
      clearTimeout(timer);
      document.removeEventListener("visibilitychange", onVisibilityChange);
    };
  }, [brand.id, site]);

  async function createTag() {
    setCreating(true);
    try {
      const res = await fetch("/api/site-tag", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId: brand.id }),
      });
      if (res.ok) {
        const data = await res.json();
        setSite(data.site);
      }
    } catch { /* ignore */ }
    setCreating(false);
  }

  function copySnippet() {
    if (!site?.snippet) return;
    navigator.clipboard.writeText(site.snippet);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  // ── Management actions ──

  function showMsg(msg: string) {
    setActionMsg(msg);
    setTimeout(() => setActionMsg(null), 3000);
  }

  async function patchSite(action: string, domain?: string) {
    try {
      const res = await fetch("/api/site-tag", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId: brand.id, action, domain }),
      });
      const data = await res.json();
      if (data.site) setSite(data.site);
      return data;
    } catch { return null; }
  }

  async function handleToggleStatus() {
    const data = await patchSite("toggle_status");
    if (data?.site) showMsg(`Tag ${data.site.status === "active" ? "activated" : "paused"}`);
  }

  async function handleRegenKey() {
    await patchSite("regenerate_key");
    setConfirmRegenKey(false);
    showMsg("Tracking key regenerated — existing snippet still works");
  }

  function normalizeDomain(input: string): string {
    let s = input.trim();
    s = s.replace(/^https?:\/\//i, "");  // strip protocol only; preserve path and port
    return s.toLowerCase();
  }

  function validateDomain(d: string): string | null {
    const hostname = d.split("/")[0].split(":")[0];
    if (!hostname.includes(".")) return "Please enter a valid domain or URL (e.g., quiz.pbdquiz.com or quiz.pbdquiz.com/landing)";
    if (/\s/.test(hostname)) return "Please enter a valid domain or URL (e.g., quiz.pbdquiz.com or quiz.pbdquiz.com/landing)";
    if (d.length < 4 || d.length > 2048) return "Please enter a valid domain or URL (e.g., quiz.pbdquiz.com or quiz.pbdquiz.com/landing)";
    return null;
  }

  function handleDomainBlur() {
    if (!newDomain.trim()) return;
    const normalized = normalizeDomain(newDomain);
    setNewDomain(normalized);
    setDomainError(validateDomain(normalized));
  }

  async function handleAddDomain() {
    if (!newDomain.trim()) return;
    const normalized = normalizeDomain(newDomain);
    const err = validateDomain(normalized);
    if (err) { setDomainError(err); return; }
    setDomainError(null);
    await patchSite("add_domain", normalized);
    setNewDomain("");
    setShowAddDomain(false);
    showMsg(`Domain "${normalized}" added`);
  }

  async function handleRemoveDomain(domain: string) {
    await patchSite("remove_domain", domain);
    showMsg(`Domain "${domain}" removed`);
  }

  async function sendTestEvent() {
    if (!site) return;
    setTestStatus("sending");
    try {
      const res = await fetch("/api/collect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          site_id: site.siteId,
          event_type: "page_view",
          page_url: `https://${brand.domain}/meseo-test`,
          referrer: "https://app.meseo.io/site-tag",
          timestamp: new Date().toISOString(),
          session_id: "test_" + Date.now().toString(36),
          metadata: { title: "meSEO Test Event", source: "site-tag-dashboard", test: true },
        }),
      });
      const data = await res.json();
      if (data.ok) {
        showMsg("Test event sent — check Recent Events below");
        await loadSiteTag();
        setTestStatus("success");
      } else {
        setTestStatus("error");
        showMsg(data.error || "Test event failed");
      }
    } catch {
      setTestStatus("error");
    }
    setTimeout(() => setTestStatus("idle"), 4000);
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="w-6 h-6 text-brand-500 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-4xl">

      {/* ── Header ── */}
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center">
            <Code2 className="w-5 h-5 text-brand-600" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-slate-900">meSEO Site Tag</h1>
            <p className="text-slate-500 text-sm mt-0.5">
              Machine Enhancing Tracking ID for <span className="font-medium text-slate-700">{brand.name}</span> ({brand.domain})
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {site && (
            <span className={`flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-full border ${
              site.status === "active"
                ? "bg-green-50 text-green-700 border-green-200"
                : "bg-red-50 text-red-700 border-red-200"
            }`}>
              {site.status === "active" ? <CheckCircle2 className="w-3.5 h-3.5" /> : <XCircle className="w-3.5 h-3.5" />}
              {site.status === "active" ? "Tag Active" : "Tag " + site.status}
            </span>
          )}
          <button
            onClick={handleRefresh}
            disabled={refreshing || loading}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 bg-white border border-slate-200 hover:bg-slate-50 disabled:opacity-50 transition-colors"
            title="Refresh event data"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${refreshing ? "animate-spin" : ""}`} />
            Refresh
          </button>
        </div>
      </div>

      {/* ── Action feedback toast ── */}
      {actionMsg && (
        <div className="bg-green-50 border border-green-200 rounded-xl px-4 py-3 flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0" />
          <p className="text-sm font-medium text-green-700">{actionMsg}</p>
        </div>
      )}

      {/* ── Polling stopped banner ── */}
      {pollingStopped && (
        <div className="flex items-start gap-2.5 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3">
          <AlertTriangle className="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
          <div className="flex-1 min-w-0">
            <p className="text-sm font-semibold text-amber-800">Live updates paused</p>
            <p className="text-xs text-amber-700 mt-0.5">Repeated errors from the health check. Use Refresh to retry.</p>
          </div>
          <button
            onClick={handleRefresh}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-amber-700 border border-amber-300 bg-amber-100 hover:bg-amber-200 transition-colors shrink-0"
          >
            <RefreshCw className="w-3.5 h-3.5" />
            Retry
          </button>
        </div>
      )}

      {/* ── No site tag yet ── */}
      {!site && (
        <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
          <div className="w-14 h-14 rounded-2xl bg-brand-50 flex items-center justify-center mx-auto mb-4">
            <Zap className="w-7 h-7 text-brand-600" />
          </div>
          <h2 className="text-lg font-bold text-slate-900 mb-2">Set Up Site Tracking</h2>
          <p className="text-sm text-slate-500 max-w-md mx-auto mb-2">
            Generate a unique tracking tag for {brand.name}. Install it on your website to start
            collecting Machine Enhancing page views, sessions, calls, form submissions, and more.
          </p>
          <p className="text-xs text-slate-400 max-w-sm mx-auto mb-6">
            Machine Enhancing Tracking ID. No personal data captured.
          </p>
          <button
            onClick={createTag}
            disabled={creating}
            className="px-6 py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 disabled:opacity-50 transition-colors"
          >
            {creating ? "Creating..." : "Generate meSEO Site Tag"}
          </button>
        </div>
      )}

      {/* ── Site tag exists ── */}
      {site && (
        <>
          {/* ── Status strip ── */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="bg-white rounded-xl border border-slate-200 px-4 py-4">
              <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">Events Today</p>
              <p className="text-3xl font-bold text-brand-600 mt-1">{eventsToday}</p>
            </div>
            <div className="bg-white rounded-xl border border-slate-200 px-4 py-4">
              <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">Last Event</p>
              <p className="text-lg font-bold text-slate-900 mt-1">
                {site.lastEventAt
                  ? formatRelativeTime(site.lastEventAt)
                  : "Never"}
              </p>
              {site.lastEventAt && (
                <p className="text-[10px] text-slate-400 mt-0.5">
                  {new Date(site.lastEventAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
                </p>
              )}
            </div>
            <div className="bg-white rounded-xl border border-slate-200 px-4 py-4">
              <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">Domains</p>
              <p className="text-lg font-bold text-slate-900 mt-1">{site.allowedDomains.length}</p>
              <p className="text-[10px] text-slate-400 mt-0.5">allowed to send events</p>
            </div>
            <div className="bg-white rounded-xl border border-slate-200 px-4 py-4">
              <p className="text-xs font-semibold text-slate-400 uppercase tracking-wide">
                {siteTagInstalledAt ? "Site Tag installed" : "Awaiting first event"}
              </p>
              <p className="text-lg font-bold text-slate-900 mt-1">
                {siteTagInstalledAt
                  ? new Date(siteTagInstalledAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })
                  : "—"}
              </p>
              <p className="text-[10px] text-slate-400 mt-0.5">
                {siteTagInstalledAt
                  ? new Date(siteTagInstalledAt).toLocaleDateString("en-US", { year: "numeric" })
                  : `Created ${new Date(site.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`}
              </p>
            </div>
          </div>

          {/* ── Tracking Health ── */}
          {health && (
            <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">
                <HeartPulse className="w-4 h-4 text-brand-600" />
                <h2 className="font-bold text-slate-800 text-sm">Tracking Health</h2>
                <span className={`ml-auto text-[10px] font-bold uppercase px-2 py-0.5 rounded-full border ${
                  health.tagActive && health.receivingEvents
                    ? "bg-green-50 text-green-700 border-green-200"
                    : health.tagActive
                      ? "bg-amber-50 text-amber-700 border-amber-200"
                      : "bg-red-50 text-red-700 border-red-200"
                }`}>
                  {health.tagActive && health.receivingEvents ? "Healthy" : health.tagActive ? "Waiting for events" : "Paused"}
                </span>
              </div>

              <div className="px-5 py-4 space-y-4">
                {/* Diagnostic checklist */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {[
                    { label: "Tag active", ok: health.tagActive, detail: health.tagActive ? "Collecting events" : "Tracking is paused — events are rejected" },
                    { label: "Tag installed", ok: health.tagInstalled, detail: health.tagInstalled ? "Events have been received" : "No events received yet — install the snippet below" },
                    { label: "Domains configured", ok: health.domainsConfigured, detail: `${site.allowedDomains.length} domain${site.allowedDomains.length !== 1 ? "s" : ""} allowed` },
                    { label: "Receiving events", ok: health.receivingEvents, detail: health.receivingEvents ? `${eventsToday} events today` : "No events today" },
                  ].map((check) => (
                    <div key={check.label} className="flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-slate-50">
                      {check.ok ? (
                        <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0 mt-0.5" />
                      ) : (
                        <XCircle className="w-4 h-4 text-red-400 shrink-0 mt-0.5" />
                      )}
                      <div>
                        <p className={`text-xs font-semibold ${check.ok ? "text-slate-700" : "text-red-600"}`}>{check.label}</p>
                        <p className="text-[10px] text-slate-400 mt-0.5">{check.detail}</p>
                      </div>
                    </div>
                  ))}
                </div>

                {/* Activity row: sessions + last event age + events/hr sparkline */}
                <div className="flex items-center gap-4 pt-2 border-t border-slate-100">
                  {/* Sessions today */}
                  <div className="flex items-center gap-2">
                    <Users className="w-4 h-4 text-slate-400" />
                    <div>
                      <p className="text-sm font-bold text-slate-900">{sessionsToday}</p>
                      <p className="text-[10px] text-slate-400">sessions today</p>
                    </div>
                  </div>

                  {/* Last event age */}
                  <div className="flex items-center gap-2">
                    <Clock className="w-4 h-4 text-slate-400" />
                    <div>
                      <p className="text-sm font-bold text-slate-900">
                        {health.lastEventAge === null ? "—" : health.lastEventAge < 1 ? "<1 min" : health.lastEventAge < 60 ? `${health.lastEventAge} min` : `${Math.floor(health.lastEventAge / 60)}h ${health.lastEventAge % 60}m`}
                      </p>
                      <p className="text-[10px] text-slate-400">since last event</p>
                    </div>
                  </div>

                  {/* Events per hour sparkline */}
                  {eventsPerHour.length > 1 && (
                    <div className="flex-1 flex items-end gap-0.5 h-8 ml-4">
                      {eventsPerHour.map((count, i) => {
                        const max = Math.max(...eventsPerHour, 1);
                        const pct = (count / max) * 100;
                        return (
                          <div
                            key={i}
                            className="flex-1 rounded-t bg-brand-400 transition-all hover:bg-brand-600"
                            style={{ height: `${Math.max(pct, 4)}%` }}
                            title={`${i}:00 — ${count} event${count !== 1 ? "s" : ""}`}
                          />
                        );
                      })}
                    </div>
                  )}
                  {eventsPerHour.length > 1 && (
                    <p className="text-[10px] text-slate-400 shrink-0 self-end">events/hr</p>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* ── Cookie-free tracking notice ──
              meSEO is a core-differentiator cookieless analytics platform.
              We surface this prominently on the setup page so a brand
              fielding GDPR/cookie-consent questions has the answer right
              there. The Site Tag uses sessionStorage + localStorage for
              identifiers — neither is transmitted with HTTP requests
              and neither is covered by ePrivacy / cookie-consent regs. */}
          {site && (
            <div className="rounded-xl border border-emerald-200 bg-emerald-50/60 px-4 py-3 flex items-start gap-3">
              <span className="w-7 h-7 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0 text-base">
                🍪
              </span>
              <div className="min-w-0">
                <p className="text-sm font-bold text-emerald-900">Cookie-free tracking — no consent banner required for basic analytics</p>
                <p className="text-[11px] text-emerald-800/80 mt-0.5 leading-relaxed">
                  The meSEO Site Tag sets <span className="font-semibold">zero cookies</span>. Session and visitor identifiers live in <code className="font-mono text-[10px] bg-white/70 px-1 py-0.5 rounded">sessionStorage</code> / <code className="font-mono text-[10px] bg-white/70 px-1 py-0.5 rounded">localStorage</code> — they aren&apos;t transmitted with HTTP requests and aren&apos;t covered by GDPR / ePrivacy cookie-consent rules. Your tracking keeps working even when visitors block cookies.
                </p>
              </div>
            </div>
          )}

          {/* ── Data maturity notice (hides itself once ≥30 days of data) ── */}
          {site && <DataMaturityNotice installedDays={siteTagAge} installedAt={siteTagInstalledAt} />}

          {/* ── Management Actions ── */}
          <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">
              <Power className="w-4 h-4 text-brand-600" />
              <h2 className="font-bold text-slate-800 text-sm">Tag Controls</h2>
            </div>
            <div className="px-5 py-4 flex flex-wrap items-center gap-2">
              {/* Toggle active/paused */}
              <button
                onClick={handleToggleStatus}
                className={`inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-semibold border transition-colors ${
                  site.status === "active"
                    ? "border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100"
                    : "border-green-200 bg-green-50 text-green-700 hover:bg-green-100"
                }`}
              >
                <Power className="w-3.5 h-3.5" />
                {site.status === "active" ? "Pause Tracking" : "Activate Tracking"}
              </button>

              {/* Regenerate key */}
              {!confirmRegenKey ? (
                <button
                  onClick={() => setConfirmRegenKey(true)}
                  className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-semibold border border-slate-200 text-slate-600 hover:bg-slate-50 transition-colors"
                >
                  <RefreshCw className="w-3.5 h-3.5" />
                  Regenerate Key
                </button>
              ) : (
                <div className="flex items-center gap-1.5 bg-red-50 border border-red-200 rounded-lg px-3 py-1.5">
                  <AlertTriangle className="w-3.5 h-3.5 text-red-500" />
                  <span className="text-xs text-red-700">Are you sure?</span>
                  <button onClick={handleRegenKey} className="text-xs font-bold text-red-700 underline ml-1">Yes, regenerate</button>
                  <button onClick={() => setConfirmRegenKey(false)} className="text-xs text-slate-500 ml-1">Cancel</button>
                </div>
              )}
            </div>
          </div>

          {/* ── Domain Management ── */}
          <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">
              <Shield className="w-4 h-4 text-brand-600" />
              <h2 className="font-bold text-slate-800 text-sm">Domain Management</h2>
              <span className="ml-auto flex items-center gap-1.5 text-[10px] font-semibold text-slate-400">
                {site.allowedDomains.length} domain{site.allowedDomains.length !== 1 ? "s" : ""} configured
              </span>
            </div>

            {/* Domain table */}
            <div className="divide-y divide-slate-100">
              {site.allowedDomains.map((d) => {
                const ds = domainStatus.find(s => s.domain === d);
                const status = ds?.status ?? "pending";
                return (
                  <div key={d} className="px-5 py-3.5 flex items-center gap-3 group hover:bg-slate-50/50 transition-colors">
                    {/* Icon */}
                    <Globe className="w-4 h-4 text-slate-400 shrink-0" />

                    {/* Domain + meta */}
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-mono font-semibold text-slate-800">{d}</p>
                      <p className="text-[10px] text-slate-400 mt-0.5">
                        {ds?.eventsToday != null && ds.eventsToday > 0
                          ? `${ds.eventsToday} event${ds.eventsToday !== 1 ? "s" : ""} today`
                          : "No events today"}
                        {ds?.lastEventAt
                          ? ` · Last: ${formatRelativeTime(ds.lastEventAt)}`
                          : ""}
                      </p>
                    </div>

                    {/* Status badge */}
                    <span className={`text-[10px] font-bold uppercase px-2 py-0.5 rounded-full border shrink-0 ${
                      status === "verified" ? "bg-green-50 text-green-700 border-green-200" :
                      status === "mismatch" ? "bg-red-50 text-red-600 border-red-200" :
                      "bg-amber-50 text-amber-700 border-amber-200"
                    }`}>
                      {status === "verified" && <CheckCircle2 className="w-3 h-3 inline mr-0.5 -mt-0.5" />}
                      {status === "mismatch" && <XCircle className="w-3 h-3 inline mr-0.5 -mt-0.5" />}
                      {status === "pending" && <Clock className="w-3 h-3 inline mr-0.5 -mt-0.5" />}
                      {status}
                    </span>

                    {/* Remove button (visible on hover, min 1 domain) */}
                    {site.allowedDomains.length > 1 && (
                      <button
                        onClick={() => handleRemoveDomain(d)}
                        className="opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
                        title="Remove domain"
                      >
                        <Trash2 className="w-4 h-4 text-slate-300 hover:text-red-500 transition-colors" />
                      </button>
                    )}
                  </div>
                );
              })}
            </div>

            {/* Add domain */}
            <div className="px-5 py-3.5 border-t border-slate-100 bg-slate-50/50">
              {!showAddDomain ? (
                <button
                  onClick={() => setShowAddDomain(true)}
                  className="flex items-center gap-1.5 text-xs font-semibold text-slate-500 hover:text-brand-600 transition-colors"
                >
                  <Plus className="w-3.5 h-3.5" />
                  Add another domain
                </button>
              ) : (
                <div className="flex flex-col gap-1.5">
                  <div className="flex items-center gap-2">
                    <Globe className="w-4 h-4 text-slate-300 shrink-0" />
                    <input
                      type="text"
                      value={newDomain}
                      onChange={(e) => { setNewDomain(e.target.value); setDomainError(null); }}
                      onBlur={handleDomainBlur}
                      onKeyDown={(e) => { if (e.key === "Enter") handleAddDomain(); if (e.key === "Escape") { setShowAddDomain(false); setNewDomain(""); setDomainError(null); } }}
                      placeholder="e.g., quiz.pbdquiz.com or quiz.pbdquiz.com/sf/2fc04c39"
                      autoFocus
                      className={`flex-1 px-3 py-1.5 text-sm font-mono border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500/30 focus:border-brand-300 ${domainError ? "border-red-300 bg-red-50" : "border-slate-200"}`}
                    />
                    <button onClick={handleAddDomain} disabled={!newDomain.trim()} className="px-3.5 py-1.5 text-xs font-semibold text-white bg-brand-600 rounded-lg hover:bg-brand-700 disabled:opacity-40 transition-colors">Add</button>
                    <button onClick={() => { setShowAddDomain(false); setNewDomain(""); setDomainError(null); }} className="px-2 py-1.5 text-xs text-slate-400 hover:text-slate-600">Cancel</button>
                  </div>
                  {domainError && <p className="text-[11px] text-red-500 ml-6">{domainError}</p>}
                </div>
              )}
              <p className="text-[10px] text-slate-400 mt-2">
                Enter the domain or full URL. All pages on this hostname will be tracked. The full URL helps you identify which funnel or landing page this entry refers to.
              </p>
            </div>
          </div>

          {/* ── Installation Guide ── */}
          <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
            <div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Code2 className="w-4 h-4 text-brand-600" />
                <h2 className="font-bold text-slate-800 text-sm">Installation Guide</h2>
              </div>
              {/* Verification badge */}
              {health?.tagInstalled ? (
                <span className="flex items-center gap-1.5 text-[10px] font-bold bg-green-50 text-green-700 border border-green-200 rounded-full px-2.5 py-1">
                  <CheckCircle2 className="w-3 h-3" /> Verified — receiving events
                </span>
              ) : (
                <span className="flex items-center gap-1.5 text-[10px] font-bold bg-amber-50 text-amber-700 border border-amber-200 rounded-full px-2.5 py-1">
                  <CircleDot className="w-3 h-3" /> Not verified yet
                </span>
              )}
            </div>

            <div className="px-5 py-5 space-y-5">
              {/* Step 1: Copy */}
              <div className="flex items-start gap-3">
                <span className="w-7 h-7 rounded-full bg-brand-100 text-brand-700 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">1</span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-800">Copy the tracking snippet</p>
                  <p className="text-xs text-slate-500 mt-0.5 mb-3">Click the button below to copy the code to your clipboard.</p>
                  <button
                    onClick={copySnippet}
                    className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-semibold transition-colors ${
                      copied ? "bg-green-600 text-white" : "bg-brand-600 text-white hover:bg-brand-700"
                    }`}
                  >
                    {copied ? <CheckCircle2 className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                    {copied ? "Copied to clipboard!" : "Copy Install Snippet"}
                  </button>
                </div>
              </div>

              {/* Step 2: Paste */}
              <div className="flex items-start gap-3">
                <span className="w-7 h-7 rounded-full bg-brand-100 text-brand-700 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">2</span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-800">Paste into your website&apos;s <code className="text-brand-600 bg-brand-50 px-1 rounded text-xs">&lt;head&gt;</code></p>
                  <p className="text-xs text-slate-500 mt-0.5 mb-3">
                    Add the snippet before the closing <code className="text-slate-600 bg-slate-100 px-1 rounded">&lt;/head&gt;</code> tag on every page of <span className="font-semibold text-slate-700">{brand.domain}</span>.
                    It works with WordPress, Shopify, Squarespace, Wix, or any custom site.
                  </p>
                  {/* Expandable code block */}
                  <pre className="bg-slate-900 text-slate-200 text-xs leading-relaxed rounded-xl p-4 overflow-x-auto">
                    {site.snippet}
                  </pre>
                </div>
              </div>

              {/* Step 3: Verify */}
              <div className="flex items-start gap-3">
                <span className="w-7 h-7 rounded-full bg-brand-100 text-brand-700 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">3</span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-800">Verify installation</p>
                  <p className="text-xs text-slate-500 mt-0.5 mb-3">
                    Visit your website in a new tab, then come back here. You should see events appear in the feed below within seconds.
                    Or click the button to send a test event right now.
                  </p>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={sendTestEvent}
                      disabled={testStatus === "sending"}
                      className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-semibold transition-colors ${
                        testStatus === "success" ? "bg-green-600 text-white"
                        : testStatus === "error" ? "bg-red-500 text-white"
                        : testStatus === "sending" ? "bg-slate-200 text-slate-400"
                        : "bg-slate-900 text-white hover:bg-slate-800"
                      }`}
                    >
                      {testStatus === "sending" ? <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        : testStatus === "success" ? <CheckCircle2 className="w-3.5 h-3.5" />
                        : testStatus === "error" ? <XCircle className="w-3.5 h-3.5" />
                        : <Send className="w-3.5 h-3.5" />}
                      {testStatus === "sending" ? "Sending..."
                        : testStatus === "success" ? "Test event received!"
                        : testStatus === "error" ? "Failed — check domain"
                        : "Send Test Event"}
                    </button>
                    <button
                      onClick={loadSiteTag}
                      className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold text-slate-600 border border-slate-200 hover:bg-slate-50 transition-colors"
                    >
                      <RefreshCw className="w-3.5 h-3.5" />
                      Refresh
                    </button>
                  </div>

                  {/* Verification result */}
                  {health?.tagInstalled ? (
                    <div className="mt-3 flex items-start gap-2 bg-green-50 border border-green-200 rounded-lg px-3 py-2.5">
                      <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0 mt-0.5" />
                      <div className="text-xs text-green-700">
                        <p className="font-semibold">Installation verified</p>
                        <p className="mt-0.5">
                          Last event received {site.lastEventAt ? formatRelativeTime(site.lastEventAt) : "recently"}.
                          Your site tag is working correctly.
                        </p>
                      </div>
                    </div>
                  ) : (
                    <div className="mt-3 flex items-start gap-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2.5">
                      <AlertTriangle className="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
                      <div className="text-xs text-amber-700">
                        <p className="font-semibold">Waiting for first event</p>
                        <p className="mt-0.5">
                          No events received yet. Make sure the snippet is installed correctly, then visit your website or click &ldquo;Send Test Event&rdquo; above.
                        </p>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* What gets tracked */}
              <div className="bg-slate-50 rounded-xl px-4 py-3.5 border border-slate-100">
                <div className="flex items-center gap-2 mb-2">
                  <Zap className="w-3.5 h-3.5 text-brand-500" />
                  <p className="text-xs font-semibold text-slate-700">What gets tracked automatically</p>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                  {[
                    { label: "Page Views", desc: "Every page load" },
                    { label: "Sessions", desc: "New visitor sessions" },
                    { label: "Phone Clicks", desc: "tel: link clicks" },
                    { label: "Form Activity", desc: "Field focus + input" },
                    { label: "Form Completions", desc: "Field count + duration" },
                    { label: "Outbound Clicks", desc: "External links" },
                    { label: "SMS Clicks", desc: "sms: link clicks" },
                    { label: "Custom Events", desc: "Via meSEO.track()" },
                  ].map(t => (
                    <div key={t.label} className="text-center py-2 px-2 bg-white rounded-lg border border-slate-100">
                      <p className="text-[10px] font-bold text-slate-700">{t.label}</p>
                      <p className="text-[9px] text-slate-400 mt-0.5">{t.desc}</p>
                    </div>
                  ))}
                </div>
                <p className="text-[10px] text-slate-400 mt-2 text-center">Machine Enhancing Tracking ID. No personal data.</p>
              </div>

              {/* Site ID reference */}
              <div className="flex items-center gap-4 pt-3 border-t border-slate-100">
                <div>
                  <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide">Site ID</p>
                  <code className="text-sm font-mono text-brand-600">{site.siteId}</code>
                </div>
                <div className="ml-auto text-right">
                  <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide">Collect Endpoint</p>
                  <code className="text-sm font-mono text-slate-500">POST /api/collect</code>
                </div>
              </div>
            </div>
          </div>

          {/* ── Detected Integrations ──
              Surfaces booking / form plugins the Site Tag has spotted
              on the brand's site (Amelia, Calendly, NexHealth, etc.).
              Each row shows the plugin name and a tracking-status badge
              so the brand knows whether their specific tech stack is
              being captured fully or only via iframe postMessage. */}
          {pluginsDetected.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">
                <Puzzle className="w-4 h-4 text-indigo-600" />
                <h2 className="font-bold text-slate-800 text-sm">Detected Integrations</h2>
                <span className="ml-auto text-[10px] font-semibold text-slate-400">
                  {pluginsDetected.length} plugin{pluginsDetected.length !== 1 ? "s" : ""} found
                </span>
              </div>
              <div className="divide-y divide-slate-100">
                {pluginsDetected.map((p) => (
                  <div key={p.key} className="px-5 py-3.5 flex items-center gap-3">
                    <span className="inline-flex items-center gap-1.5 text-[11px] font-bold text-indigo-700 bg-indigo-50 border border-indigo-200 px-2 py-0.5 rounded shrink-0 min-w-[140px]">
                      <Puzzle className="w-3 h-3" />
                      {p.name}
                    </span>
                    <div className="flex-1 min-w-0">
                      <p className="text-[11px] text-slate-500 leading-snug">{p.trackingNote}</p>
                    </div>
                    {p.trackingLevel === "full" ? (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wide text-emerald-700 bg-emerald-50 border border-emerald-200 rounded px-2 py-0.5 shrink-0">
                        <CheckCircle2 className="w-3 h-3" />
                        Full tracking
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wide text-amber-700 bg-amber-50 border border-amber-200 rounded px-2 py-0.5 shrink-0">
                        <AlertTriangle className="w-3 h-3" />
                        Limited (iframe)
                      </span>
                    )}
                  </div>
                ))}
              </div>
              <div className="px-5 py-2.5 border-t border-slate-100 bg-slate-50/40 text-[10px] text-slate-500">
                Detection runs automatically — install a new plugin and it&apos;ll appear here within minutes of the next page-load.
              </div>
            </div>
          )}

          {/* ── Custom Events Configuration ── */}
          <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">
              <Code2 className="w-4 h-4 text-violet-600" />
              <h2 className="font-bold text-slate-800 text-sm">Custom Events</h2>
            </div>
            <div className="px-5 py-4">
              <CustomEvents brandId={brand.id} />
            </div>
          </div>

          {/* ── Observed Custom Events (from tracked data) ── */}
          {customEventsList.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">
                <Code2 className="w-4 h-4 text-slate-500" />
                <h2 className="font-bold text-slate-800 text-sm">Observed Events</h2>
                <span className="ml-auto text-[10px] font-semibold text-slate-400">
                  {customEventsList.length} event type{customEventsList.length !== 1 ? "s" : ""} firing
                </span>
              </div>
              <div className="divide-y divide-slate-100">
                {customEventsList.map((ce) => (
                  <div key={ce.name} className="px-5 py-3.5 flex items-center gap-3 hover:bg-slate-50/50 transition-colors">
                    {/* Event name */}
                    <span className="inline-flex items-center gap-1.5 text-[10px] font-bold text-violet-700 bg-violet-50 border border-violet-200 px-2 py-0.5 rounded shrink-0">
                      <Code2 className="w-3 h-3" />
                      {ce.name}
                    </span>

                    {/* Count */}
                    <div className="flex-1 min-w-0">
                      <span className="text-sm font-bold text-slate-800">{ce.count.toLocaleString()}</span>
                      <span className="text-xs text-slate-400 ml-1">event{ce.count !== 1 ? "s" : ""} total</span>
                    </div>

                    {/* Last fired */}
                    <div className="text-right shrink-0">
                      <p className="text-xs font-semibold text-slate-600">{formatRelativeTime(ce.lastFired)}</p>
                      <p className="text-[10px] text-slate-400">last fired</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* ── Platform Connections ── */}
          <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">
              <Layers className="w-4 h-4 text-brand-600" />
              <h2 className="font-bold text-slate-800 text-sm">How Site Tag Powers the Platform</h2>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-slate-100">
              {[
                {
                  title: "Conversion Intelligence",
                  icon: <Zap className="w-4 h-4 text-amber-500" />,
                  bg: "bg-amber-50",
                  feeds: "form_submit, click_to_call, sms_submit",
                  desc: "Tracked conversions flow into attribution models so you can see which pages, channels, and campaigns drive real results.",
                  href: "/site-tag-analytics",
                },
                {
                  title: "Performance Since Launch",
                  icon: <BarChart3 className="w-4 h-4 text-blue-500" />,
                  bg: "bg-blue-50",
                  feeds: "page_view, session_start",
                  desc: "Launched pages get real traffic and conversion data from Site Tag, replacing estimates with actual performance numbers.",
                  href: "/page-launch-tracker",
                },
                {
                  title: "Signals Center",
                  icon: <Activity className="w-4 h-4 text-rose-500" />,
                  bg: "bg-rose-50",
                  feeds: "All events (anomaly detection)",
                  desc: "Site Tag data is scanned for traffic drops, spikes, form abandonment, and call surges — surfaced as real-time signals.",
                  href: "/signals",
                },
                {
                  title: "AI Avatar",
                  icon: <Eye className="w-4 h-4 text-violet-500" />,
                  bg: "bg-violet-50",
                  feeds: "Traffic + conversion summaries",
                  desc: "When you ask the AI Strategist about traffic or conversions, it uses real Site Tag data instead of estimates.",
                  href: "#",
                },
              ].map((mod) => (
                <div key={mod.title} className="px-5 py-4">
                  <div className="flex items-center gap-2 mb-2">
                    <div className={`w-7 h-7 rounded-lg ${mod.bg} flex items-center justify-center shrink-0`}>
                      {mod.icon}
                    </div>
                    <p className="text-sm font-bold text-slate-800">{mod.title}</p>
                  </div>
                  <p className="text-xs text-slate-500 leading-relaxed">{mod.desc}</p>
                  <p className="text-[10px] text-slate-400 mt-2">
                    Events used: <span className="font-mono text-slate-500">{mod.feeds}</span>
                  </p>
                </div>
              ))}
            </div>
          </div>

        </>
      )}
    </div>
  );
}

// Marker: Data Reconciliation, Recent Events, Events Overview, and Event
// Breakdown sections have been moved to Site Tag Analytics (overview-tab).
// See commit history for the original code.

// ─── Helper ──────────────────────────────────────────────────────────────────
// (orphaned sections removed — moved to Site Tag Analytics)
// END_ORPHAN_MARKER
// ─── Helper ──────────────────────────────────────────────────────────────────

function formatRelativeTime(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const secs = Math.floor(diff / 1000);
  if (secs < 5) return "Just now";
  if (secs < 60) return `${secs}s ago`;
  const mins = Math.floor(secs / 60);
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
}
