// Admin dashboard — super_admin only
// Full-featured: Dashboard, Customers, Users, Audit Log, Settings

const {
  useState: useAdm,
  useEffect: useAdmEffect,
  useCallback: useAdmCb,
  useMemo: useAdmMemo,
  useRef: useAdmRef,
} = React;

// ─── helpers ─────────────────────────────────────────────────────────────────

function fmtDate(iso) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function fmtRelative(iso) {
  if (!iso) return "Never";
  const mins = Math.floor((Date.now() - new Date(iso)) / 60000);
  if (mins < 2) return "Just now";
  if (mins < 60) return `${mins}m ago`;
  if (mins < 1440) return `${Math.floor(mins / 60)}h ago`;
  if (mins < 10080) return `${Math.floor(mins / 1440)}d ago`;
  return fmtDate(iso);
}

function fmtMRR(cents) {
  if (!cents) return "$0";
  return "$" + (cents / 100).toLocaleString("en-US", { maximumFractionDigits: 0 });
}

const STATUS_STYLE = {
  active:  { bg: "rgba(110,231,183,0.12)", color: "#10b981", label: "Active"   },
  trial:   { bg: "rgba(251,191,36,0.12)",  color: "#d97706", label: "Trial"    },
  churned: { bg: "rgba(248,113,113,0.12)", color: "#ef4444", label: "Churned"  },
  suspended:{ bg: "rgba(248,113,113,0.12)",color: "#ef4444", label: "Suspended"},
};

function StatusBadge({ status }) {
  const s = STATUS_STYLE[status] || STATUS_STYLE.trial;
  return <span className="pc-adm-badge" style={{ background: s.bg, color: s.color }}>{s.label}</span>;
}

const BIZ_MODELS = [
  { v: "services",      l: "Professional Services", icon: "💼", desc: "Consulting, agencies, law, accounting" },
  { v: "saas",          l: "SaaS / Software",        icon: "💻", desc: "Subscription software products" },
  { v: "inventory",     l: "Product / Inventory",    icon: "📦", desc: "Physical goods, wholesale, distribution" },
  { v: "retail",        l: "Retail / Stores",        icon: "🏪", desc: "Multi-location or e-commerce retail" },
  { v: "manufacturing", l: "Manufacturing",          icon: "🏭", desc: "Production, fabrication, processing" },
  { v: "mixed",         l: "Mixed / Other",          icon: "🔀", desc: "Multiple revenue streams" },
];

const COMPANY_TYPES = [
  { v: "llc",        l: "LLC" },
  { v: "s_corp",     l: "S-Corp" },
  { v: "c_corp",     l: "C-Corp" },
  { v: "sole_prop",  l: "Sole Proprietorship" },
  { v: "partnership",l: "Partnership" },
  { v: "nonprofit",  l: "Non-Profit" },
];

const ROLES = ["Owner", "Admin", "Finance", "Viewer"];
const PLAN_OPTIONS = ["trial","starter","growth","pro","enterprise"];

// ─── Notification toast helper (shared) ──────────────────────────────────────
function AdminToast({ msg, type }) {
  const bg = type === "success" ? "#10b981" : type === "error" ? "#ef4444" : "#3b82f6";
  return (
    <div style={{
      position: "fixed", top: 20, right: 20, zIndex: 99999,
      background: bg, color: "#fff", padding: "11px 20px",
      borderRadius: 8, fontSize: 13, fontWeight: 500,
      boxShadow: "0 4px 20px rgba(0,0,0,0.25)", maxWidth: 360,
      animation: "pc-fadein 0.2s ease",
    }}>{msg}</div>
  );
}

function useAdminToast() {
  const [toast, setToast] = useAdm(null);
  const show = (msg, type = "success") => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 3500);
  };
  return [toast, show];
}

const AUDIT_ICONS = {
  "company.created":    { icon: "✦", color: "#10b981" },
  "company.updated":    { icon: "✎", color: "#3b82f6" },
  "company.suspended":  { icon: "⏸", color: "#d97706" },
  "company.deleted":    { icon: "✕", color: "#ef4444" },
  "user.invited":       { icon: "✉", color: "#3b82f6" },
  "user.role_changed":  { icon: "⇄", color: "#6366f1" },
  "user.removed":       { icon: "−", color: "#ef4444" },
  "user.invite_resent": { icon: "↺", color: "#3b82f6" },
  "user.password_reset":{ icon: "⚿", color: "#d97706" },
};

// ─── Edge Function caller ─────────────────────────────────────────────────────

async function callAdmin(path, method, body) {
  const db = window.supabaseClient;
  const { data: { session } } = await db.auth.getSession();
  const token = session?.access_token;
  const base = `${window.SUPABASE_URL}/functions/v1/admin-actions`;
  const res = await fetch(`${base}/${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${token}`,
      "Apikey": window.SUPABASE_ANON_KEY,
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || "Request failed");
  return data;
}

// ─── Shared form components ───────────────────────────────────────────────────

function Field({ label, children, hint, half }) {
  return (
    <div className={`pc-adm-field${half ? " half" : ""}`}>
      <label className="pc-adm-field-label">{label}</label>
      {children}
      {hint && <div className="pc-adm-field-hint">{hint}</div>}
    </div>
  );
}

function AInput({ value, onChange, ...rest }) {
  return <input className="pc-adm-input" value={value} onChange={e => onChange(e.target.value)} {...rest} />;
}

function ASelect({ value, onChange, children, ...rest }) {
  return (
    <select className="pc-adm-input" value={value} onChange={e => onChange(e.target.value)} {...rest}>
      {children}
    </select>
  );
}

// ─── Confirm dialog ───────────────────────────────────────────────────────────

function ConfirmDialog({ message, confirmLabel, danger, onConfirm, onCancel }) {
  return (
    <div className="pc-adm-modal-bg" onClick={onCancel}>
      <div className="pc-adm-modal" style={{ maxWidth: 360 }} onClick={e => e.stopPropagation()}>
        <div className="pc-adm-modal-header">
          <div className="pc-adm-modal-title">Confirm action</div>
          <button className="pc-adm-modal-close" onClick={onCancel}>✕</button>
        </div>
        <p style={{ fontSize: 13.5, color: "var(--text-2)", marginBottom: 20, lineHeight: 1.6 }}>{message}</p>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <button className="pc-adm-btn-ghost" onClick={onCancel}>Cancel</button>
          <button className="pc-adm-btn-primary"
            style={danger ? { background: "#ef4444", color: "#fff", borderColor: "#ef4444" } : {}}
            onClick={onConfirm}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

// ─── Sidebar nav ──────────────────────────────────────────────────────────────

const NAV_GROUPS = [
  {
    label: "Platform",
    items: [
      { id: "dashboard", label: "Dashboard", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
          <rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>
        </svg>
      )},
      { id: "analytics", label: "Analytics", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
        </svg>
      )},
      { id: "billing", label: "Billing & Revenue", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/>
        </svg>
      )},
    ],
  },
  {
    label: "Customers",
    items: [
      { id: "customers", label: "All Customers", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
        </svg>
      )},
      { id: "users", label: "User Management", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
          <path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
        </svg>
      )},
      { id: "onboard", label: "Onboard Customer", sub: "Invite & setup", icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/>
        </svg>
      )},
    ],
  },
  {
    label: "Platform Config",
    items: [
      { id: "pricing", label: "Pricing Plans", sub: "Plans & packaging", icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
        </svg>
      )},
      { id: "documents", label: "Documents", sub: "Contracts & manuals", icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>
          <line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>
        </svg>
      )},
      { id: "integrations", label: "Integrations & APIs", sub: "API credentials", icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
          <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
        </svg>
      )},
      { id: "audit", label: "Audit Log", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
          <polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>
        </svg>
      )},
      { id: "settings", label: "Settings", sub: null, icon: (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
        </svg>
      )},
    ],
  },
];

// ─── Admin Sidebar ────────────────────────────────────────────────────────────

function AdminSidebar({ activeSection, onNav, adminEmail, onLogout, companies, onViewCompany, onQuickInvite }) {
  const [viewAsOpen, setViewAsOpen] = useAdm(false);
  const viewAsRef = useAdmRef(null);
  const initials = adminEmail ? adminEmail.slice(0, 2).toUpperCase() : "SA";

  useAdmEffect(() => {
    if (!viewAsOpen) return;
    const h = (e) => { if (viewAsRef.current && !viewAsRef.current.contains(e.target)) setViewAsOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [viewAsOpen]);

  return (
    <div className="pc-adm-sidebar">
      <div className="pc-adm-sidebar-logo">
        <PerduraMark size={22} />
        <div>
          <div className="pc-adm-sidebar-brand">Perdura</div>
          <div className="pc-adm-sidebar-tagline">Admin Console</div>
        </div>
      </div>

      <button
        className="pc-adm-btn-primary"
        style={{ margin: "0 12px 16px", fontSize: 12.5, padding: "9px 14px", width: "calc(100% - 24px)", justifyContent: "center" }}
        onClick={onQuickInvite}
      >
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: 6 }}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
        Invite Customer
      </button>

      <nav className="pc-adm-sidebar-nav">
        {NAV_GROUPS.map(group => (
          <div key={group.label} className="pc-adm-nav-group">
            <div className="pc-adm-nav-group-label">{group.label}</div>
            {group.items.map(item => (
              <button
                key={item.id}
                className={`pc-adm-nav-item${activeSection === item.id ? " active" : ""}`}
                onClick={() => onNav(item.id)}
              >
                {item.icon}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div>{item.label}</div>
                  {item.sub && <div className="pc-adm-nav-sub">{item.sub}</div>}
                </div>
              </button>
            ))}
          </div>
        ))}
      </nav>

      <div className="pc-adm-sidebar-footer">
        {companies.length > 0 && (
          <div ref={viewAsRef} style={{ position: "relative", marginBottom: 8 }}>
            <button
              className="pc-adm-nav-item"
              style={{ width: "100%", color: "var(--text-3)" }}
              onClick={() => setViewAsOpen(o => !o)}
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
              View as customer
            </button>
            {viewAsOpen && (
              <div className="pc-adm-viewas-popup">
                <div className="pc-adm-viewas-header">Switch to customer</div>
                {companies.map(c => (
                  <button key={c.id} className="pc-adm-viewas-row"
                    onClick={() => { setViewAsOpen(false); onViewCompany(c.id, c); }}>
                    <span className="pc-adm-viewas-avatar">{(c.name||"?").slice(0,2).toUpperCase()}</span>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 12.5 }}>{c.name}</div>
                      <div style={{ fontSize: 11, color: "var(--text-3)" }}>{c.subdomain} · {c.status}</div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
        <div className="pc-adm-sidebar-user">
          <div className="pc-adm-sidebar-avatar">{initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{adminEmail || "Super Admin"}</div>
            <div style={{ fontSize: 10.5, color: "var(--text-3)" }}>Super Admin</div>
          </div>
          <button
            onClick={onLogout}
            title="Sign out"
            style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-3)", padding: 4, borderRadius: 6, flexShrink: 0 }}
            onMouseEnter={e => e.currentTarget.style.color = "#ef4444"}
            onMouseLeave={e => e.currentTarget.style.color = "var(--text-3)"}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── KPI card ─────────────────────────────────────────────────────────────────

function KpiCard({ label, value, sub, accent, trend, icon }) {
  return (
    <div className="pc-adm-kpi">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
        <div className="pc-adm-kpi-label">{label}</div>
        {icon && <div style={{ color: accent || "var(--text-3)", opacity: 0.7 }}>{icon}</div>}
      </div>
      <div className="pc-adm-kpi-value" style={accent ? { color: accent } : {}}>{value}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 6 }}>
        {trend !== undefined && (
          <span style={{ fontSize: 11, fontWeight: 600, color: trend >= 0 ? "#10b981" : "#ef4444" }}>
            {trend >= 0 ? "+" : ""}{trend}%
          </span>
        )}
        {sub && <div className="pc-adm-kpi-sub">{sub}</div>}
      </div>
    </div>
  );
}

// ─── Dashboard section ────────────────────────────────────────────────────────

function DashboardSection({ companies, allUsers }) {
  const mrr = companies.reduce((s, c) => s + (c.mrr || 0), 0);
  const active = companies.filter(c => c.status === "active").length;
  const trial = companies.filter(c => c.status === "trial").length;
  const churned = companies.filter(c => c.status === "churned").length;
  const totalUsers = allUsers.length;
  const activeUsers = allUsers.filter(u => u.last_sign_in_at && (Date.now() - new Date(u.last_sign_in_at)) < 7 * 86400000).length;
  const pendingUsers = allUsers.filter(u => u.cu_status === "Pending").length;

  // Recent signups (last 30 days)
  const recentCompanies = [...companies]
    .filter(c => c.created_at && (Date.now() - new Date(c.created_at)) < 30 * 86400000)
    .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
    .slice(0, 5);

  // Recently active users
  const recentUsers = [...allUsers]
    .filter(u => u.last_sign_in_at)
    .sort((a, b) => new Date(b.last_sign_in_at) - new Date(a.last_sign_in_at))
    .slice(0, 8);

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Platform Overview</h2>
        <div style={{ fontSize: 12, color: "var(--text-3)" }}>Updated just now</div>
      </div>

      <div className="pc-adm-kpi-row" style={{ gridTemplateColumns: "repeat(4,1fr)" }}>
        <KpiCard label="Total Customers" value={companies.length}
          sub={`${active} active · ${trial} trial`}
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>} />
        <KpiCard label="Monthly Recurring Revenue" value={fmtMRR(mrr)} accent="#10b981"
          sub="Across active plans"
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>} />
        <KpiCard label="Active Rate" value={`${Math.round(active / Math.max(companies.length, 1) * 100)}%`}
          accent={active / Math.max(companies.length, 1) > 0.6 ? "#10b981" : "#d97706"}
          sub={`${churned} churned`}
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>} />
        <KpiCard label="Total Users" value={totalUsers}
          sub={`${activeUsers} active this week · ${pendingUsers} pending`}
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginTop: 8 }}>
        {/* Recent customers */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">New Customers (30 days)</div>
            <span style={{ fontSize: 11, background: "rgba(16,185,129,0.1)", color: "#10b981", padding: "2px 8px", borderRadius: 99, fontWeight: 600 }}>{recentCompanies.length}</span>
          </div>
          {recentCompanies.length === 0 ? (
            <div className="pc-adm-empty-sm">No new customers this month</div>
          ) : (
            <div className="pc-adm-card-list">
              {recentCompanies.map(c => (
                <div key={c.id} className="pc-adm-card-row">
                  <div className="pc-adm-avatar-sm">{(c.name||"?").slice(0,2).toUpperCase()}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: "var(--text-3)" }}>{c.subdomain} · {c.plan || "trial"}</div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <StatusBadge status={c.status} />
                    <div style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap" }}>{fmtRelative(c.created_at)}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Recent logins */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">Recent User Logins</div>
            <span style={{ fontSize: 11, background: "rgba(59,130,246,0.1)", color: "#3b82f6", padding: "2px 8px", borderRadius: 99, fontWeight: 600 }}>{activeUsers} this week</span>
          </div>
          {recentUsers.length === 0 ? (
            <div className="pc-adm-empty-sm">No logins recorded</div>
          ) : (
            <div className="pc-adm-card-list">
              {recentUsers.map(u => (
                <div key={u.id} className="pc-adm-card-row">
                  <div className="pc-adm-avatar-sm" style={{ background: "rgba(59,130,246,0.12)", color: "#3b82f6" }}>
                    {(u.email||"?").slice(0,2).toUpperCase()}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 13, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{u.email}</div>
                    <div style={{ fontSize: 11, color: "var(--text-3)" }}>{u.company_name || "—"} · {u.role || "—"}</div>
                  </div>
                  <div style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap" }}>{fmtRelative(u.last_sign_in_at)}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Plan breakdown */}
      <div className="pc-adm-card" style={{ marginTop: 20 }}>
        <div className="pc-adm-card-header">
          <div className="pc-adm-card-title">Customer Status Breakdown</div>
        </div>
        <div style={{ display: "flex", gap: 0, alignItems: "stretch" }}>
          {[
            { label: "Active", count: active, color: "#10b981", pct: active / Math.max(companies.length, 1) },
            { label: "Trial", count: trial, color: "#d97706", pct: trial / Math.max(companies.length, 1) },
            { label: "Churned", count: churned, color: "#ef4444", pct: churned / Math.max(companies.length, 1) },
          ].map(row => (
            <div key={row.label} style={{ flex: 1, padding: "16px 20px", borderRight: "1px solid var(--border)", textAlign: "center" }}>
              <div style={{ fontSize: 28, fontWeight: 700, color: row.color, letterSpacing: -0.04 }}>{row.count}</div>
              <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4 }}>{row.label}</div>
              <div style={{ height: 4, background: "var(--border)", borderRadius: 2, marginTop: 8, overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${row.pct * 100}%`, background: row.color, borderRadius: 2, transition: "width 0.6s" }} />
              </div>
            </div>
          ))}
          <div style={{ flex: 1, padding: "16px 20px", textAlign: "center" }}>
            <div style={{ fontSize: 28, fontWeight: 700, color: "var(--text)", letterSpacing: -0.04 }}>{companies.length}</div>
            <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4 }}>Total</div>
            <div style={{ height: 4, background: "var(--accent)", borderRadius: 2, marginTop: 8 }} />
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── New Customer Wizard ──────────────────────────────────────────────────────

function NewCustomerWizard({ onClose, onCreated }) {
  const [step, setStep] = useAdm(0);
  const [loading, setLoading] = useAdm(false);
  const [error, setError] = useAdm("");
  const [bizModel, setBizModel] = useAdm("");
  const [name, setName] = useAdm("");
  const [subdomain, setSubdomain] = useAdm("");
  const [companyType, setCompanyType] = useAdm("");
  const [industry, setIndustry] = useAdm("");
  const [phone, setPhone] = useAdm("");
  const [website, setWebsite] = useAdm("");
  const [plan, setPlan] = useAdm("trial");
  const [timezone, setTimezone] = useAdm("");
  const [revBand, setRevBand] = useAdm("");
  const [empCount, setEmpCount] = useAdm("");
  const [notes, setNotes] = useAdm("");
  const [ownerName, setOwnerName] = useAdm("");
  const [ownerEmail, setOwnerEmail] = useAdm("");

  useAdmEffect(() => {
    if (name) {
      setSubdomain(name.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, ""));
    }
  }, [name]);

  async function handleSubmit() {
    setError("");
    setLoading(true);
    try {
      const result = await callAdmin("invite", "POST", {
        companyName: name, subdomain, ownerName, ownerEmail,
        businessModel: bizModel, companyType, industry, plan,
        phone, website, timezone, notes,
        revenue_band: revBand, employee_count: empCount ? parseInt(empCount) : null,
      });
      onCreated(result.company);
      onClose();
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  }

  const steps = ["Business type", "Company profile", "Admin user", "Confirm"];

  return (
    <div className="pc-adm-modal-bg" onClick={onClose}>
      <div className="pc-adm-wizard" onClick={e => e.stopPropagation()}>
        <div className="pc-adm-wizard-header">
          <div>
            <div className="pc-adm-modal-title">New customer</div>
            <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>Step {step + 1} of {steps.length} — {steps[step]}</div>
          </div>
          <button className="pc-adm-modal-close" onClick={onClose}>✕</button>
        </div>

        <div className="pc-adm-wizard-dots">
          {steps.map((s, i) => (
            <div key={i} className={`pc-adm-wdot${i === step ? " active" : i < step ? " done" : ""}`}>
              <div className="pc-adm-wdot-dot">{i < step ? "✓" : i + 1}</div>
              <div className="pc-adm-wdot-label">{s}</div>
            </div>
          ))}
        </div>

        {error && <div className="pc-auth-error-banner" style={{ margin: "0 0 16px" }}>{error}</div>}

        {step === 0 && (
          <div>
            <p style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 16 }}>Select the primary business model for this customer.</p>
            <div className="pc-adm-biz-grid">
              {BIZ_MODELS.map(b => (
                <button key={b.v} className={`pc-adm-biz-card${bizModel === b.v ? " selected" : ""}`} onClick={() => setBizModel(b.v)}>
                  <div className="pc-adm-biz-icon">{b.icon}</div>
                  <div className="pc-adm-biz-name">{b.l}</div>
                  <div className="pc-adm-biz-desc">{b.desc}</div>
                </button>
              ))}
            </div>
            <div className="pc-adm-wizard-footer">
              <button className="pc-adm-btn-ghost" onClick={onClose}>Cancel</button>
              <button className="pc-adm-btn-primary" disabled={!bizModel} onClick={() => setStep(1)}>Next →</button>
            </div>
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="pc-adm-form-grid">
              <Field label="Company name"><AInput value={name} onChange={setName} placeholder="Acme Inc." required /></Field>
              <Field label="Subdomain" hint="Auto-generated · must be unique">
                <div className="pc-adm-subdomain-row">
                  <span className="pc-adm-subdomain-pre">https://</span>
                  <input className="pc-adm-input pc-adm-subdomain-mid" value={subdomain}
                    onChange={e => setSubdomain(e.target.value.toLowerCase().replace(/\s/g, "-"))} placeholder="acme" />
                  <span className="pc-adm-subdomain-suf">.cfodash.app</span>
                </div>
              </Field>
              <Field label="Entity type" half>
                <ASelect value={companyType} onChange={setCompanyType}>
                  <option value="">Select…</option>
                  {COMPANY_TYPES.map(t => <option key={t.v} value={t.v}>{t.l}</option>)}
                </ASelect>
              </Field>
              <Field label="Industry" half><AInput value={industry} onChange={setIndustry} placeholder="e.g. Healthcare" /></Field>
              <Field label="Revenue band" half>
                <ASelect value={revBand} onChange={setRevBand}>
                  <option value="">Select…</option>
                  {["Under $500K","$500K – $1M","$1M – $3M","$3M – $8M","$8M – $15M","$15M – $30M","$30M+"].map(r =>
                    <option key={r} value={r}>{r}</option>)}
                </ASelect>
              </Field>
              <Field label="Employees" half><AInput value={empCount} onChange={setEmpCount} type="number" min="1" placeholder="50" /></Field>
              <Field label="Phone" half><AInput value={phone} onChange={setPhone} placeholder="+1 (555) 000-0000" /></Field>
              <Field label="Website" half><AInput value={website} onChange={setWebsite} placeholder="https://acme.com" /></Field>
              <Field label="Plan" half>
                <ASelect value={plan} onChange={setPlan}>
                  {PLAN_OPTIONS.map(p => <option key={p} value={p}>{p[0].toUpperCase() + p.slice(1)}</option>)}
                </ASelect>
              </Field>
              <Field label="Timezone" half>
                <ASelect value={timezone} onChange={setTimezone}>
                  <option value="">Select…</option>
                  {["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Australia/Sydney"].map(tz =>
                    <option key={tz} value={tz}>{tz.replace("_"," ")}</option>)}
                </ASelect>
              </Field>
              <Field label="Internal notes">
                <textarea className="pc-adm-input" rows={3} value={notes} onChange={e => setNotes(e.target.value)} placeholder="Notes visible only to admins…" />
              </Field>
            </div>
            <div className="pc-adm-wizard-footer">
              <button className="pc-adm-btn-ghost" onClick={() => setStep(0)}>← Back</button>
              <button className="pc-adm-btn-primary" disabled={!name || !subdomain} onClick={() => setStep(2)}>Next →</button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <p style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 16 }}>This person will be the Owner and will receive the invite email.</p>
            <div className="pc-adm-form-grid">
              <Field label="Full name" half><AInput value={ownerName} onChange={setOwnerName} placeholder="Jane Smith" /></Field>
              <Field label="Email address" half><AInput value={ownerEmail} onChange={setOwnerEmail} type="email" placeholder="jane@acme.com" required /></Field>
            </div>
            <div className="pc-adm-wizard-footer">
              <button className="pc-adm-btn-ghost" onClick={() => setStep(1)}>← Back</button>
              <button className="pc-adm-btn-primary" disabled={!ownerEmail} onClick={() => setStep(3)}>Next →</button>
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <div className="pc-adm-confirm-grid">
              {[
                ["Company", name],
                ["Subdomain", subdomain + ".cfodash.app"],
                ["Business model", BIZ_MODELS.find(b => b.v === bizModel)?.l || bizModel],
                ["Entity type", COMPANY_TYPES.find(t => t.v === companyType)?.l || companyType],
                industry && ["Industry", industry],
                revBand && ["Revenue band", revBand],
                ["Plan", plan[0].toUpperCase() + plan.slice(1)],
                ["Owner", ownerName ? `${ownerName} (${ownerEmail})` : ownerEmail],
              ].filter(Boolean).map(([label, value]) => (
                <div key={label} className="pc-adm-confirm-row">
                  <span className="pc-adm-confirm-label">{label}</span>
                  <span className="pc-adm-confirm-value">{value || "—"}</span>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--text-3)", marginTop: 16, padding: "12px 14px", background: "var(--bg-elev-2)", borderRadius: 8 }}>
              An invite email will be sent to <strong style={{ color: "var(--text-2)" }}>{ownerEmail}</strong>.
            </div>
            <div className="pc-adm-wizard-footer">
              <button className="pc-adm-btn-ghost" onClick={() => setStep(2)}>← Back</button>
              <button className="pc-adm-btn-primary" disabled={loading} onClick={handleSubmit}>
                {loading ? "Creating…" : "Create & send invite"}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Company Detail Drawer ────────────────────────────────────────────────────

function CompanyDrawer({ company, onClose, onUpdated, onViewDashboard }) {
  const [tab, setTab] = useAdm("profile");
  const [users, setUsers] = useAdm(null);
  const [auditLogs, setAuditLogs] = useAdm(null);
  const [saving, setSaving] = useAdm(false);
  const [saveErr, setSaveErr] = useAdm("");
  const [addingUser, setAddingUser] = useAdm(false);

  const [name, setName] = useAdm(company.name || "");
  const [status, setStatus] = useAdm(company.status || "trial");
  const [plan, setPlan] = useAdm(company.plan || "trial");
  const [mrr, setMrr] = useAdm(company.mrr ? String(company.mrr / 100) : "");
  const [bizModel, setBizModel] = useAdm(company.business_model || company.business_type || "");
  const [companyType, setCompanyType] = useAdm(company.company_type || "");
  const [industry, setIndustry] = useAdm(company.industry || "");
  const [phone, setPhone] = useAdm(company.phone || "");
  const [website, setWebsite] = useAdm(company.website || "");
  const [timezone, setTimezone] = useAdm(company.timezone || "America/New_York");
  const [revBand, setRevBand] = useAdm(company.revenue_band || "");
  const [empCount, setEmpCount] = useAdm(company.employee_count ? String(company.employee_count) : "");
  const [fiscalEnd, setFiscalEnd] = useAdm(company.fiscal_year_end || "December");
  const [notes, setNotes] = useAdm(company.notes || "");

  useAdmEffect(() => {
    if (tab === "users" && !users) loadUsers();
    if (tab === "audit" && !auditLogs) loadAudit();
  }, [tab]);

  async function loadUsers() {
    const res = await callAdmin(`company-users?companyId=${company.id}`, "GET");
    setUsers(res.users || []);
  }

  async function loadAudit() {
    const res = await callAdmin(`audit-log?companyId=${company.id}&limit=100`, "GET");
    setAuditLogs(res.logs || []);
  }

  async function handleSave() {
    setSaving(true); setSaveErr("");
    try {
      const result = await callAdmin("update-company", "POST", {
        companyId: company.id,
        name, status, plan,
        mrr: mrr !== "" ? Math.round(parseFloat(mrr) * 100) : 0,
        business_model: bizModel, business_type: bizModel,
        company_type: companyType, industry, phone, website, timezone,
        revenue_band: revBand,
        employee_count: empCount ? parseInt(empCount) : null,
        fiscal_year_end: fiscalEnd, notes,
      });
      onUpdated({ ...company, ...result.company });
    } catch (err) { setSaveErr(err.message); }
    finally { setSaving(false); }
  }

  return (
    <div className="pc-adm-drawer-bg" onClick={onClose}>
      <div className="pc-adm-drawer" onClick={e => e.stopPropagation()}>
        <div className="pc-adm-drawer-header">
          <div>
            <div className="pc-adm-drawer-title">{company.name}</div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 4 }}>
              <StatusBadge status={company.status} />
              <span style={{ fontSize: 11.5, color: "var(--text-3)", fontFamily: "ui-monospace,monospace" }}>{company.subdomain}.cfodash.app</span>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <button className="pc-adm-btn-primary" style={{ fontSize: 12, padding: "6px 14px" }} onClick={() => onViewDashboard(company)}>
              Open dashboard ↗
            </button>
            <button className="pc-adm-modal-close" onClick={onClose}>✕</button>
          </div>
        </div>

        <div className="pc-adm-drawer-tabs">
          {[["profile","Profile"],["users","Users"],["audit","Audit trail"]].map(([v,l]) => (
            <button key={v} className={`pc-adm-drawer-tab${tab === v ? " active" : ""}`} onClick={() => setTab(v)}>{l}</button>
          ))}
        </div>

        <div className="pc-adm-drawer-body">
          {tab === "profile" && (
            <div>
              {saveErr && <div className="pc-auth-error-banner" style={{ marginBottom: 14 }}>{saveErr}</div>}

              <div className="pc-adm-drawer-section-title">Business model</div>
              <div className="pc-adm-biz-grid compact">
                {BIZ_MODELS.map(b => (
                  <button key={b.v} className={`pc-adm-biz-card${bizModel === b.v ? " selected" : ""}`} onClick={() => setBizModel(b.v)}>
                    <div className="pc-adm-biz-icon">{b.icon}</div>
                    <div className="pc-adm-biz-name">{b.l}</div>
                  </button>
                ))}
              </div>

              <div className="pc-adm-drawer-section-title" style={{ marginTop: 20 }}>Company details</div>
              <div className="pc-adm-form-grid">
                <Field label="Company name"><AInput value={name} onChange={setName} placeholder="Acme Inc." /></Field>
                <Field label="Entity type" half>
                  <ASelect value={companyType} onChange={setCompanyType}>
                    <option value="">Select…</option>
                    {COMPANY_TYPES.map(t => <option key={t.v} value={t.v}>{t.l}</option>)}
                  </ASelect>
                </Field>
                <Field label="Industry" half><AInput value={industry} onChange={setIndustry} placeholder="e.g. Healthcare" /></Field>
                <Field label="Revenue band" half>
                  <ASelect value={revBand} onChange={setRevBand}>
                    <option value="">Select…</option>
                    {["Under $500K","$500K – $1M","$1M – $3M","$3M – $8M","$8M – $15M","$15M – $30M","$30M+"].map(r =>
                      <option key={r} value={r}>{r}</option>)}
                  </ASelect>
                </Field>
                <Field label="Employees" half><AInput value={empCount} onChange={setEmpCount} type="number" min="1" placeholder="50" /></Field>
                <Field label="Phone" half><AInput value={phone} onChange={setPhone} placeholder="+1 (555) 000-0000" /></Field>
                <Field label="Website" half><AInput value={website} onChange={setWebsite} placeholder="https://acme.com" /></Field>
                <Field label="Fiscal year end" half>
                  <ASelect value={fiscalEnd} onChange={setFiscalEnd}>
                    {["January","February","March","April","May","June","July","August","September","October","November","December"].map(m =>
                      <option key={m} value={m}>{m}</option>)}
                  </ASelect>
                </Field>
                <Field label="Timezone" half>
                  <ASelect value={timezone} onChange={setTimezone}>
                    {["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Australia/Sydney"].map(tz =>
                      <option key={tz} value={tz}>{tz.replace("_"," ")}</option>)}
                  </ASelect>
                </Field>
              </div>

              <div className="pc-adm-drawer-section-title" style={{ marginTop: 20 }}>Billing & status</div>
              <div className="pc-adm-form-grid">
                <Field label="Status" half>
                  <ASelect value={status} onChange={setStatus}>
                    <option value="trial">Trial</option>
                    <option value="active">Active</option>
                    <option value="churned">Churned</option>
                  </ASelect>
                </Field>
                <Field label="Plan" half>
                  <ASelect value={plan} onChange={setPlan}>
                    {PLAN_OPTIONS.map(p => <option key={p} value={p}>{p[0].toUpperCase() + p.slice(1)}</option>)}
                  </ASelect>
                </Field>
                <Field label="MRR (USD)" half hint="Monthly recurring revenue">
                  <AInput value={mrr} onChange={setMrr} type="number" min="0" step="0.01" placeholder="0.00" />
                </Field>
              </div>

              <div className="pc-adm-drawer-section-title" style={{ marginTop: 20 }}>Internal notes</div>
              <Field label="">
                <textarea className="pc-adm-input" rows={4} value={notes}
                  onChange={e => setNotes(e.target.value)} placeholder="Notes visible only to Perdura admins…" />
              </Field>

              <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 20 }}>
                <button className="pc-adm-btn-primary" disabled={saving} onClick={handleSave}>
                  {saving ? "Saving…" : "Save changes"}
                </button>
              </div>
            </div>
          )}

          {tab === "users" && (
            <div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                <div className="pc-adm-drawer-section-title" style={{ margin: 0 }}>Team members {users ? `(${users.length})` : ""}</div>
                <button className="pc-adm-btn-primary" style={{ fontSize: 12, padding: "6px 14px" }} onClick={() => setAddingUser(true)}>+ Add user</button>
              </div>
              {!users && <div className="pc-adm-loading">Loading users…</div>}
              {users && users.length === 0 && <div className="pc-adm-empty">No users yet.</div>}
              {users && users.length > 0 && (
                <table className="pc-adm-table">
                  <thead><tr><th>User</th><th>Role</th><th>Status</th><th>Last login</th><th>Actions</th></tr></thead>
                  <tbody>
                    {users.map(u => (
                      <UserRow key={u.user_id} user={u} companyId={company.id} onUpdated={loadUsers} onRemoved={loadUsers} />
                    ))}
                  </tbody>
                </table>
              )}
              {addingUser && (
                <AddUserModal companyId={company.id} onClose={() => setAddingUser(false)}
                  onAdded={() => { setAddingUser(false); loadUsers(); }} />
              )}
            </div>
          )}

          {tab === "audit" && (
            <div>
              <div className="pc-adm-drawer-section-title" style={{ marginBottom: 14 }}>Activity log {auditLogs ? `(${auditLogs.length} events)` : ""}</div>
              {!auditLogs && <div className="pc-adm-loading">Loading…</div>}
              {auditLogs && auditLogs.length === 0 && <div className="pc-adm-empty">No activity recorded yet.</div>}
              {auditLogs && auditLogs.length > 0 && (
                <div className="pc-adm-audit-list">
                  {auditLogs.map(log => {
                    const ic = AUDIT_ICONS[log.action] || { icon: "·", color: "var(--text-3)" };
                    return (
                      <div key={log.id} className="pc-adm-audit-row">
                        <div className="pc-adm-audit-icon" style={{ color: ic.color }}>{ic.icon}</div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 500 }}>{log.action.replace(".", " · ")}</div>
                          {log.payload && Object.keys(log.payload).length > 0 && (
                            <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 2, fontFamily: "ui-monospace,monospace", wordBreak: "break-all" }}>
                              {JSON.stringify(log.payload).slice(0, 120)}
                            </div>
                          )}
                        </div>
                        <div style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap", paddingLeft: 12 }}>{fmtRelative(log.created_at)}</div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── User row in company drawer ───────────────────────────────────────────────

function UserRow({ user, companyId, onUpdated, onRemoved }) {
  const [role, setRole] = useAdm(user.role);
  const [saving, setSaving] = useAdm(false);
  const [confirm, setConfirm] = useAdm(false);

  async function handleRoleChange(newRole) {
    setRole(newRole); setSaving(true);
    try { await callAdmin("update-user", "POST", { companyId, userId: user.user_id, role: newRole }); onUpdated(); }
    catch (_) {}
    setSaving(false);
  }

  async function handleResend() { await callAdmin("resend-invite", "POST", { companyId, userId: user.user_id }); }

  async function handleRemove() {
    await callAdmin("remove-user", "DELETE", { companyId, userId: user.user_id });
    setConfirm(false);
    onRemoved();
  }

  return (
    <tr>
      <td style={{ paddingLeft: 14 }}>
        <div style={{ fontWeight: 500, fontSize: 13 }}>{user.name || "—"}</div>
        <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{user.email}</div>
      </td>
      <td>
        <select className="pc-adm-input" style={{ fontSize: 12, padding: "3px 6px", width: "auto" }}
          value={role} onChange={e => handleRoleChange(e.target.value)} disabled={saving}>
          {ROLES.map(r => <option key={r} value={r}>{r}</option>)}
        </select>
      </td>
      <td>
        <span className="pc-adm-badge" style={{
          background: user.status === "Active" ? "rgba(110,231,183,0.12)" : "rgba(251,191,36,0.12)",
          color: user.status === "Active" ? "#10b981" : "#d97706",
        }}>{user.status || "Pending"}</span>
      </td>
      <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtRelative(user.last_sign_in)}</td>
      <td>
        <div style={{ display: "flex", gap: 6 }}>
          {user.status === "Pending" && <button className="pc-adm-act-btn" onClick={handleResend}>Resend</button>}
          <button className="pc-adm-act-btn pc-adm-act-danger" onClick={() => setConfirm(true)}>Remove</button>
        </div>
        {confirm && (
          <ConfirmDialog message={`Remove ${user.email} from this company?`} confirmLabel="Remove" danger
            onConfirm={handleRemove} onCancel={() => setConfirm(false)} />
        )}
      </td>
    </tr>
  );
}

// ─── Add User Modal ───────────────────────────────────────────────────────────

function AddUserModal({ companyId, onClose, onAdded }) {
  const [email, setEmail] = useAdm("");
  const [name, setName] = useAdm("");
  const [role, setRole] = useAdm("Viewer");
  const [loading, setLoading] = useAdm(false);
  const [error, setError] = useAdm("");

  async function handleSubmit(e) {
    e.preventDefault(); setLoading(true); setError("");
    try { await callAdmin("add-user", "POST", { companyId, email, name, role }); onAdded(); }
    catch (err) { setError(err.message); setLoading(false); }
  }

  return (
    <div className="pc-adm-modal-bg" onClick={onClose}>
      <div className="pc-adm-modal" onClick={e => e.stopPropagation()}>
        <div className="pc-adm-modal-header">
          <div className="pc-adm-modal-title">Add user</div>
          <button className="pc-adm-modal-close" onClick={onClose}>✕</button>
        </div>
        {error && <div className="pc-auth-error-banner" style={{ marginBottom: 14 }}>{error}</div>}
        <form onSubmit={handleSubmit}>
          <div className="pc-adm-form-grid">
            <Field label="Full name" half><AInput value={name} onChange={setName} placeholder="Jane Smith" /></Field>
            <Field label="Email address" half><AInput value={email} onChange={setEmail} type="email" placeholder="jane@company.com" required /></Field>
            <Field label="Role" half>
              <ASelect value={role} onChange={setRole}>
                {ROLES.map(r => <option key={r} value={r}>{r}</option>)}
              </ASelect>
            </Field>
          </div>
          <div className="pc-adm-form-hint">Owner = full access · Admin = all except billing · Finance = read + export · Viewer = read only</div>
          <div style={{ display: "flex", gap: 10, marginTop: 20 }}>
            <button type="button" className="pc-adm-btn-ghost" style={{ flex: 1 }} onClick={onClose}>Cancel</button>
            <button type="submit" className="pc-adm-btn-primary" style={{ flex: 2 }} disabled={loading}>
              {loading ? "Sending invite…" : "Send invite"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─── Customers section ────────────────────────────────────────────────────────

function CustomersSection({ companies, setCompanies, onViewDashboard, onNewCustomer }) {
  const [drawer, setDrawer] = useAdm(null);
  const [confirm, setConfirm] = useAdm(null);
  const [actionErr, setActionErr] = useAdm("");
  const [search, setSearch] = useAdm("");
  const [filterStatus, setFilterStatus] = useAdm("all");
  const [copiedId, setCopiedId] = useAdm(null);

  const filtered = useAdmMemo(() => {
    return companies.filter(c => {
      if (filterStatus !== "all" && c.status !== filterStatus) return false;
      if (search) {
        const q = search.toLowerCase();
        return c.name.toLowerCase().includes(q) || c.subdomain.toLowerCase().includes(q) || (c.industry || "").toLowerCase().includes(q);
      }
      return true;
    });
  }, [companies, search, filterStatus]);

  function getCustomerUrl(subdomain) {
    const base = window.location.hostname === "localhost"
      ? `http://localhost:${window.location.port}`
      : `https://project-ivigd.vercel.app`;
    return `${base}/?subdomain=${subdomain}`;
  }

  async function handleCopyLink(e, company) {
    e.stopPropagation();
    try {
      await navigator.clipboard.writeText(getCustomerUrl(company.subdomain));
      setCopiedId(company.id);
      setTimeout(() => setCopiedId(null), 2000);
    } catch {}
  }

  async function handleSuspend(company) {
    try {
      await callAdmin("suspend", "POST", { companyId: company.id });
      setCompanies(prev => prev.map(c => c.id === company.id ? { ...c, status: "churned" } : c));
      if (drawer?.id === company.id) setDrawer(prev => ({ ...prev, status: "churned" }));
    } catch (err) { setActionErr(err.message); }
    setConfirm(null);
  }

  async function handleDelete(company) {
    try {
      await callAdmin("delete", "DELETE", { companyId: company.id });
      setCompanies(prev => prev.filter(c => c.id !== company.id));
      if (drawer?.id === company.id) setDrawer(null);
    } catch (err) { setActionErr(err.message); }
    setConfirm(null);
  }

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Customers</h2>
        <button className="pc-adm-btn-primary" onClick={onNewCustomer}>+ New customer</button>
      </div>

      {actionErr && (
        <div className="pc-auth-error-banner" style={{ marginBottom: 16 }}>
          {actionErr}
          <button style={{ float: "right", background: "none", border: "none", color: "inherit", cursor: "pointer" }} onClick={() => setActionErr("")}>✕</button>
        </div>
      )}

      <div className="pc-adm-filters">
        <input className="pc-adm-search" placeholder="Search company name, subdomain, industry…"
          value={search} onChange={e => setSearch(e.target.value)} />
        <div className="pc-adm-filter-tabs">
          {[["all","All"],["active","Active"],["trial","Trial"],["churned","Churned"]].map(([v,l]) => (
            <button key={v} className={`pc-adm-filter-tab${filterStatus === v ? " active" : ""}`}
              onClick={() => setFilterStatus(v)}>{l}</button>
          ))}
        </div>
      </div>

      <div className="pc-adm-table-wrap">
        <table className="pc-adm-table">
          <thead>
            <tr>
              <th>Company</th>
              <th>Business model</th>
              <th>Plan</th>
              <th>Status</th>
              <th style={{ textAlign: "right" }}>MRR</th>
              <th>Users</th>
              <th>Last sync</th>
              <th>Created</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 && (
              <tr><td colSpan={9} style={{ textAlign: "center", padding: "40px", color: "var(--text-3)" }}>
                {search || filterStatus !== "all" ? "No matches." : "No companies yet."}
              </td></tr>
            )}
            {filtered.map(c => {
              const biz = BIZ_MODELS.find(b => b.v === (c.business_model || c.business_type));
              return (
                <tr key={c.id} className="pc-adm-tr-hover" onClick={() => setDrawer(c)}>
                  <td className="pc-adm-td-name">
                    <div style={{ fontWeight: 600 }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: "var(--text-3)", display: "flex", alignItems: "center", gap: 4, marginTop: 2 }}>
                      <a href={getCustomerUrl(c.subdomain)} target="_blank" rel="noopener noreferrer"
                        className="pc-adm-subdomain-link" onClick={e => e.stopPropagation()}>
                        {c.subdomain}
                        <svg width="9" height="9" viewBox="0 0 12 12" fill="none" style={{ marginLeft: 3, opacity: 0.5 }}>
                          <path d="M5 1H1v10h10V7M7 1h4v4M11 1L5.5 6.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </a>
                      <button title="Copy link" onClick={e => handleCopyLink(e, c)}
                        style={{ background: "none", border: "none", cursor: "pointer", padding: "0 2px", color: copiedId === c.id ? "#10b981" : "var(--text-4)", lineHeight: 1 }}>
                        {copiedId === c.id
                          ? <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                          : <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                        }
                      </button>
                    </div>
                  </td>
                  <td>{biz ? <span style={{ fontSize: 12 }}>{biz.icon} {biz.l}</span> : <span style={{ fontSize: 12, color: "var(--text-3)" }}>Not set</span>}</td>
                  <td style={{ textTransform: "capitalize", fontSize: 12.5 }}>{c.plan || "trial"}</td>
                  <td><StatusBadge status={c.status} /></td>
                  <td style={{ fontFamily: "ui-monospace,monospace", fontSize: 12.5, textAlign: "right" }}>{fmtMRR(c.mrr)}</td>
                  <td style={{ fontSize: 12.5 }}>{c.userCount}</td>
                  <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtRelative(c.lastSync)}</td>
                  <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtDate(c.created_at)}</td>
                  <td onClick={e => e.stopPropagation()}>
                    <div className="pc-adm-actions">
                      <button className="pc-adm-act-btn" onClick={() => setDrawer(c)}>Manage</button>
                      <button className="pc-adm-act-btn" onClick={() => onViewDashboard(c)}>Open</button>
                      {c.status !== "churned" && (
                        <button className="pc-adm-act-btn pc-adm-act-warn"
                          onClick={() => setConfirm({ type: "suspend", company: c })}>Suspend</button>
                      )}
                      <button className="pc-adm-act-btn pc-adm-act-danger"
                        onClick={() => setConfirm({ type: "delete", company: c })}>Delete</button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {drawer && (
        <CompanyDrawer company={drawer} onClose={() => setDrawer(null)}
          onUpdated={(updated) => { setCompanies(prev => prev.map(c => c.id === updated.id ? { ...c, ...updated } : c)); setDrawer(updated); }}
          onViewDashboard={onViewDashboard} />
      )}

      {confirm?.type === "suspend" && (
        <ConfirmDialog message={`Suspend ${confirm.company.name}? They will lose access.`}
          confirmLabel="Suspend" danger
          onConfirm={() => handleSuspend(confirm.company)} onCancel={() => setConfirm(null)} />
      )}
      {confirm?.type === "delete" && (
        <ConfirmDialog message={`Permanently delete ${confirm.company.name}? This cannot be undone.`}
          confirmLabel="Delete permanently" danger
          onConfirm={() => handleDelete(confirm.company)} onCancel={() => setConfirm(null)} />
      )}
    </div>
  );
}

// ─── All Users section ────────────────────────────────────────────────────────

function UsersSection({ allUsers, companies, onRefresh }) {
  const [search, setSearch] = useAdm("");
  const [filterCompany, setFilterCompany] = useAdm("all");

  const filtered = useAdmMemo(() => {
    return allUsers.filter(u => {
      if (filterCompany !== "all" && u.company_id !== filterCompany) return false;
      if (search) {
        const q = search.toLowerCase();
        return (u.email || "").toLowerCase().includes(q) || (u.name || "").toLowerCase().includes(q) || (u.company_name || "").toLowerCase().includes(q);
      }
      return true;
    });
  }, [allUsers, search, filterCompany]);

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">All Users</h2>
        <div style={{ fontSize: 12, color: "var(--text-3)" }}>{allUsers.length} total users across {companies.length} companies</div>
      </div>

      <div className="pc-adm-filters">
        <input className="pc-adm-search" placeholder="Search by email, name, or company…"
          value={search} onChange={e => setSearch(e.target.value)} />
        <ASelect value={filterCompany} onChange={setFilterCompany}
          style={{ minWidth: 180, padding: "7px 10px", fontSize: 12.5 }}>
          <option value="all">All companies</option>
          {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </ASelect>
      </div>

      <div className="pc-adm-table-wrap">
        <table className="pc-adm-table">
          <thead>
            <tr>
              <th>User</th>
              <th>Company</th>
              <th>Role</th>
              <th>Status</th>
              <th>Last login</th>
              <th>Joined</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 && (
              <tr><td colSpan={6} style={{ textAlign: "center", padding: "40px", color: "var(--text-3)" }}>No users found.</td></tr>
            )}
            {filtered.map(u => (
              <tr key={u.id}>
                <td style={{ paddingLeft: 14 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div className="pc-adm-avatar-sm" style={{ flexShrink: 0 }}>
                      {(u.email||"?").slice(0,2).toUpperCase()}
                    </div>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{u.name || u.email}</div>
                      {u.name && <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{u.email}</div>}
                    </div>
                  </div>
                </td>
                <td>
                  <div style={{ fontSize: 13 }}>{u.company_name || "—"}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "ui-monospace,monospace" }}>{u.subdomain || ""}</div>
                </td>
                <td style={{ fontSize: 12.5 }}>{u.role || "—"}</td>
                <td>
                  <span className="pc-adm-badge" style={{
                    background: u.cu_status === "Active" ? "rgba(110,231,183,0.12)" : "rgba(251,191,36,0.12)",
                    color: u.cu_status === "Active" ? "#10b981" : "#d97706",
                  }}>{u.cu_status || "—"}</span>
                </td>
                <td style={{ fontSize: 12, color: u.last_sign_in_at ? "var(--text)" : "var(--text-3)" }}>
                  {fmtRelative(u.last_sign_in_at)}
                </td>
                <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtDate(u.joined_at || u.created_at)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── Global Audit Log section ─────────────────────────────────────────────────

function AuditLogSection() {
  const [logs, setLogs] = useAdm(null);
  const [loading, setLoading] = useAdm(false);
  const [search, setSearch] = useAdm("");
  const [page, setPage] = useAdm(0);
  const PAGE_SIZE = 50;

  useAdmEffect(() => {
    loadLogs();
  }, []);

  async function loadLogs() {
    setLoading(true);
    try {
      const res = await callAdmin("audit-log?limit=500", "GET");
      setLogs(res.logs || []);
    } catch (_) { setLogs([]); }
    finally { setLoading(false); }
  }

  const filtered = useAdmMemo(() => {
    if (!logs) return [];
    if (!search) return logs;
    const q = search.toLowerCase();
    return logs.filter(l =>
      (l.action || "").toLowerCase().includes(q) ||
      JSON.stringify(l.payload || {}).toLowerCase().includes(q)
    );
  }, [logs, search]);

  const paged = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Audit Log</h2>
        <button className="pc-adm-btn-ghost" style={{ fontSize: 12, padding: "6px 12px" }} onClick={loadLogs}>
          Refresh
        </button>
      </div>

      <div className="pc-adm-filters" style={{ marginBottom: 16 }}>
        <input className="pc-adm-search" placeholder="Filter by action or payload…"
          value={search} onChange={e => { setSearch(e.target.value); setPage(0); }} />
        {logs && <div style={{ fontSize: 12, color: "var(--text-3)" }}>{filtered.length} events</div>}
      </div>

      {loading && <div className="pc-adm-loading">Loading audit log…</div>}
      {!loading && logs !== null && logs.length === 0 && (
        <div className="pc-adm-empty">No audit events recorded yet.</div>
      )}
      {!loading && paged.length > 0 && (
        <>
          <div className="pc-adm-audit-list">
            {paged.map(log => {
              const ic = AUDIT_ICONS[log.action] || { icon: "·", color: "var(--text-3)" };
              return (
                <div key={log.id} className="pc-adm-audit-row">
                  <div className="pc-adm-audit-icon" style={{ color: ic.color, fontSize: 14 }}>{ic.icon}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{log.action}</span>
                      {log.company_name && (
                        <span style={{ fontSize: 11, background: "var(--bg-elev-3)", padding: "1px 7px", borderRadius: 99, color: "var(--text-3)" }}>
                          {log.company_name}
                        </span>
                      )}
                    </div>
                    {log.payload && Object.keys(log.payload).length > 0 && (
                      <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 3, fontFamily: "ui-monospace,monospace", wordBreak: "break-all" }}>
                        {JSON.stringify(log.payload).slice(0, 200)}
                      </div>
                    )}
                  </div>
                  <div style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap", paddingLeft: 12 }}>
                    {fmtRelative(log.created_at)}
                  </div>
                </div>
              );
            })}
          </div>
          {totalPages > 1 && (
            <div style={{ display: "flex", justifyContent: "center", gap: 8, marginTop: 16 }}>
              <button className="pc-adm-btn-ghost" style={{ fontSize: 12, padding: "5px 12px" }} disabled={page === 0} onClick={() => setPage(p => p - 1)}>← Prev</button>
              <span style={{ fontSize: 12, color: "var(--text-3)", lineHeight: "32px" }}>Page {page + 1} of {totalPages}</span>
              <button className="pc-adm-btn-ghost" style={{ fontSize: 12, padding: "5px 12px" }} disabled={page >= totalPages - 1} onClick={() => setPage(p => p + 1)}>Next →</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ─── Settings section ─────────────────────────────────────────────────────────

const PLATFORM_SETTING_GROUPS = [
  {
    id: "contact",
    label: "Contact & Support",
    icon: `<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/>`,
    fields: [
      { key: "support_email", label: "Support Email", type: "email", placeholder: "support@example.com" },
      { key: "contact_email", label: "Contact / Sales Email", type: "email", placeholder: "hello@example.com" },
      { key: "billing_email", label: "Billing Email", type: "email", placeholder: "billing@example.com" },
      { key: "support_phone", label: "Support Phone", type: "text", placeholder: "+1 (555) 000-0000" },
      { key: "support_hours", label: "Support Hours", type: "text", placeholder: "Mon – Fri, 9am – 6pm ET" },
      { key: "calendly_url", label: "Calendly / Booking URL", type: "url", placeholder: "https://calendly.com/..." },
    ],
  },
  {
    id: "branding",
    label: "Branding",
    icon: `<circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/>`,
    fields: [
      { key: "brand_name", label: "Brand / Product Name", type: "text", placeholder: "PerduraCFO" },
      { key: "company_name", label: "Legal Company Name", type: "text", placeholder: "Perdura Capital LLC" },
      { key: "company_address", label: "Address", type: "text", placeholder: "123 Main St, New York, NY 10001" },
      { key: "company_website", label: "Website", type: "url", placeholder: "https://perduracapital.com" },
    ],
  },
  {
    id: "notifications",
    label: "Notifications",
    icon: `<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>`,
    fields: [
      { key: "notify_new_signup", label: "Notify on new signup", type: "toggle" },
      { key: "notify_payment_received", label: "Notify on payment received", type: "toggle" },
      { key: "notify_email", label: "Notification Recipient Email", type: "email", placeholder: "admin@example.com" },
    ],
  },
];

function PlatformSettingsCard({ toast }) {
  const [settings, setSettings] = useAdm({});
  const [dirty, setDirty] = useAdm({});
  const [loading, setLoading] = useAdm(true);
  const [saving, setSaving] = useAdm(false);

  useAdmEffect(() => {
    (async () => {
      const db = window.supabaseClient;
      const { data } = await db.from("platform_settings").select("key,value");
      const map = {};
      (data || []).forEach(r => { map[r.key] = r.value; });
      setSettings(map);
      setLoading(false);
    })();
  }, []);

  function setValue(key, val) {
    setSettings(s => ({ ...s, [key]: val }));
    setDirty(d => ({ ...d, [key]: true }));
  }

  async function handleSave(groupId) {
    const group = PLATFORM_SETTING_GROUPS.find(g => g.id === groupId);
    if (!group) return;
    const payload = {};
    group.fields.forEach(f => { payload[f.key] = settings[f.key] ?? ""; });
    setSaving(true);
    try {
      const db = window.supabaseClient;
      const { data: { session } } = await db.auth.getSession();
      const token = session?.access_token;
      const url = `${window.SUPABASE_URL}/functions/v1/admin-actions/update-settings`;
      const res = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, "Apikey": window.SUPABASE_ANON_KEY },
        body: JSON.stringify({ settings: payload }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || "Save failed");
      setDirty(d => {
        const next = { ...d };
        group.fields.forEach(f => { delete next[f.key]; });
        return next;
      });
      toast("Platform settings saved", "success");
    } catch (err) {
      toast(err.message || "Save failed", "error");
    } finally {
      setSaving(false);
    }
  }

  if (loading) return (
    <div style={{ textAlign: "center", padding: 40, color: "var(--text-3)", fontSize: 13 }}>Loading settings…</div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20, marginTop: 20 }}>
      {PLATFORM_SETTING_GROUPS.map(group => {
        const groupDirty = group.fields.some(f => dirty[f.key]);
        return (
          <div key={group.id} className="pc-adm-card">
            <div className="pc-adm-card-header" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: "var(--text-3)" }} dangerouslySetInnerHTML={{ __html: group.icon }} />
                <div className="pc-adm-card-title">{group.label}</div>
              </div>
              <button
                className={groupDirty ? "pc-adm-btn-primary" : "pc-adm-btn"}
                onClick={() => handleSave(group.id)}
                disabled={saving || !groupDirty}
                style={{ padding: "6px 16px", fontSize: 12 }}
              >
                {saving ? "Saving…" : "Save"}
              </button>
            </div>
            <div style={{ padding: "20px 20px 8px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 20px" }}>
              {group.fields.map(field => {
                if (field.type === "toggle") {
                  const isOn = settings[field.key] === "true" || settings[field.key] === true;
                  return (
                    <div key={field.key} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border)", gridColumn: "1 / -1" }}>
                      <span style={{ fontSize: 13, color: "var(--text-2)" }}>{field.label}</span>
                      <button
                        onClick={() => setValue(field.key, String(!isOn))}
                        style={{
                          width: 40, height: 22, borderRadius: 11, border: "none", cursor: "pointer",
                          background: isOn ? "#10b981" : "var(--border)",
                          position: "relative", transition: "background 0.2s", flexShrink: 0,
                        }}
                      >
                        <span style={{
                          position: "absolute", top: 3, left: isOn ? 21 : 3,
                          width: 16, height: 16, borderRadius: "50%",
                          background: "#fff", transition: "left 0.2s",
                          boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
                        }} />
                      </button>
                    </div>
                  );
                }
                return (
                  <div key={field.key} style={{ display: "flex", flexDirection: "column", gap: 5, paddingBottom: 6 }}>
                    <label style={{ fontSize: 11, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{field.label}</label>
                    <input
                      type={field.type === "toggle" ? "text" : field.type}
                      value={settings[field.key] ?? ""}
                      onChange={e => setValue(field.key, e.target.value)}
                      placeholder={field.placeholder}
                      style={{
                        background: "var(--bg-elev-2)", border: `1px solid ${dirty[field.key] ? "var(--accent)" : "var(--border)"}`,
                        borderRadius: 6, padding: "8px 10px", fontSize: 13,
                        color: "var(--text)", outline: "none", transition: "border-color 0.15s",
                      }}
                    />
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function SettingsSection({ adminEmail }) {
  const [currentPw, setCurrentPw] = useAdm("");
  const [newPw, setNewPw] = useAdm("");
  const [confirmPw, setConfirmPw] = useAdm("");
  const [pwLoading, setPwLoading] = useAdm(false);
  const [pwError, setPwError] = useAdm("");
  const [pwSuccess, setPwSuccess] = useAdm(false);
  const [toast, showToast] = useAdminToast();

  async function handleChangePassword(e) {
    e.preventDefault();
    setPwError(""); setPwSuccess(false);
    if (newPw.length < 8) { setPwError("Password must be at least 8 characters."); return; }
    if (newPw !== confirmPw) { setPwError("Passwords do not match."); return; }
    setPwLoading(true);
    try {
      const db = window.supabaseClient;
      const { error } = await db.auth.updateUser({ password: newPw });
      if (error) throw error;
      setPwSuccess(true);
      setCurrentPw(""); setNewPw(""); setConfirmPw("");
    } catch (err) {
      setPwError(err.message || "Failed to update password.");
    } finally {
      setPwLoading(false);
    }
  }

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Settings</h2>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, alignItems: "start" }}>
        {/* Account info */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">My Account</div>
          </div>
          <div style={{ padding: "20px 20px 16px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, paddingBottom: 16, marginBottom: 16, borderBottom: "1px solid var(--border)" }}>
              <div style={{
                width: 48, height: 48, borderRadius: "50%", flexShrink: 0,
                background: "linear-gradient(135deg, #0284c7, #0891b2)",
                color: "#fff", fontSize: 16, fontWeight: 700,
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>{adminEmail ? adminEmail.slice(0,2).toUpperCase() : "SA"}</div>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14, color: "var(--text)" }}>{adminEmail || "Super Admin"}</div>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 3 }}>Super Administrator</div>
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13, color: "var(--text-2)" }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: "var(--text-3)", flexShrink: 0 }}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                {adminEmail}
              </div>
              <div style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13, color: "var(--text-2)" }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: "var(--text-3)", flexShrink: 0 }}><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                Full platform access
              </div>
            </div>
          </div>
        </div>

        {/* Change password */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">Change Password</div>
          </div>
          <div style={{ padding: "20px 20px 20px" }}>
            {pwSuccess && (
              <div style={{ background: "rgba(16,185,129,0.1)", border: "1px solid rgba(16,185,129,0.2)", color: "#10b981", borderRadius: 8, padding: "10px 14px", fontSize: 13, marginBottom: 18, display: "flex", alignItems: "center", gap: 8 }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                Password updated successfully.
              </div>
            )}
            {pwError && <div className="pc-auth-error-banner" style={{ marginBottom: 16 }}>{pwError}</div>}
            <form onSubmit={handleChangePassword}>
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <Field label="New password">
                  <AInput value={newPw} onChange={setNewPw} type="password" placeholder="8+ characters" />
                </Field>
                <Field label="Confirm new password">
                  <AInput value={confirmPw} onChange={setConfirmPw} type="password" placeholder="Re-enter new password" />
                </Field>
              </div>
              <button type="submit" className="pc-adm-btn-primary" disabled={pwLoading} style={{ marginTop: 20, width: "100%" }}>
                {pwLoading ? "Updating…" : "Update password"}
              </button>
            </form>
          </div>
        </div>
      </div>

      {/* Platform info */}
      <div className="pc-adm-card" style={{ marginTop: 20 }}>
        <div className="pc-adm-card-header">
          <div className="pc-adm-card-title">Platform Information</div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)" }}>
          {[
            ["Product", "PerduraCFO"],
            ["Version", "1.0.0"],
            ["Environment", window.location.hostname.includes("localhost") ? "Development" : "Production"],
            ["Backend", "Supabase"],
            ["Auth", "Email / Password"],
            ["Hosting", "Vercel"],
          ].map(([label, value], i) => (
            <div key={label} style={{
              padding: "14px 18px",
              borderRight: (i + 1) % 3 !== 0 ? "1px solid var(--border)" : "none",
              borderBottom: i < 3 ? "1px solid var(--border)" : "none",
            }}>
              <div style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.08, marginBottom: 5, fontWeight: 600 }}>{label}</div>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text)" }}>{value}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Platform settings */}
      <div style={{ marginTop: 32, paddingTop: 28, borderTop: "1px solid var(--border)" }}>
        <div style={{ marginBottom: 4 }}>
          <h3 style={{ fontSize: 15, fontWeight: 700, color: "var(--text)", margin: 0 }}>Platform Settings</h3>
          <p style={{ fontSize: 12.5, color: "var(--text-3)", margin: "4px 0 0" }}>Configure emails, branding, and notifications used across the platform.</p>
        </div>
        <PlatformSettingsCard toast={showToast} />
      </div>

      {toast && <AdminToast msg={toast.msg} type={toast.type} />}
    </div>
  );
}

// ─── Documents section ────────────────────────────────────────────────────────

const DOC_CATEGORIES = [
  { v: "contract",   l: "Contract",     color: "#3b82f6" },
  { v: "manual",     l: "Manual",       color: "#10b981" },
  { v: "policy",     l: "Policy",       color: "#d97706" },
  { v: "guide",      l: "Guide",        color: "#8b5cf6" },
  { v: "onboarding", l: "Onboarding",   color: "#059669" },
];

const DOC_STATUS = {
  draft:     { label: "Draft",     bg: "rgba(148,163,184,0.12)", color: "#94a3b8" },
  published: { label: "Published", bg: "rgba(16,185,129,0.12)",  color: "#10b981" },
  signed:    { label: "Signed",    bg: "rgba(59,130,246,0.12)",  color: "#3b82f6" },
  archived:  { label: "Archived",  bg: "rgba(239,68,68,0.12)",   color: "#ef4444" },
};

function TemplateVariablesHelp() {
  return (
    <details style={{ marginTop: 10 }}>
      <summary style={{ fontSize: 12, color: "var(--text-3)", cursor: "pointer", userSelect: "none" }}>
        Available template variables
      </summary>
      <div style={{ marginTop: 8, background: "var(--bg-elev-2)", borderRadius: 6, padding: "10px 12px", fontSize: 12, color: "var(--text-2)", lineHeight: 1.7 }}>
        {[
          ["{{company_name}}", "Customer company name"],
          ["{{owner_name}}", "Owner / primary contact name"],
          ["{{plan_name}}", "Subscribed plan name"],
          ["{{monthly_fee}}", "Monthly subscription fee"],
          ["{{start_date}}", "Agreement start date (today)"],
          ["{{support_email}}", "Support email address"],
          ["{{support_hours}}", "Support availability hours"],
          ["{{brand_name}}", "Platform brand name (PerduraCFO)"],
          ["{{company_legal_name}}", "Provider legal entity name"],
        ].map(([v, d]) => (
          <div key={v} style={{ display: "flex", gap: 12 }}>
            <code style={{ color: "var(--accent)", minWidth: 190, fontFamily: "monospace" }}>{v}</code>
            <span style={{ color: "var(--text-3)" }}>{d}</span>
          </div>
        ))}
      </div>
    </details>
  );
}

function DocumentsSection({ companies }) {
  const [tab, setTab] = useAdm("templates");
  const [templates, setTemplates] = useAdm([]);
  const [companyDocs, setCompanyDocs] = useAdm([]);
  const [loadingT, setLoadingT] = useAdm(true);
  const [loadingD, setLoadingD] = useAdm(false);
  const [selectedCompany, setSelectedCompany] = useAdm("");
  const [editTpl, setEditTpl] = useAdm(null);
  const [showTplModal, setShowTplModal] = useAdm(false);
  const [previewDoc, setPreviewDoc] = useAdm(null);
  const [genModal, setGenModal] = useAdm(null);
  const [genLoading, setGenLoading] = useAdm(false);
  const [toast, showToast] = useAdminToast();

  // Template form state
  const [tplForm, setTplForm] = useAdm({ name: "", slug: "", category: "contract", version: "1.0", body_html: "", applies_to: "", is_active: true });

  async function loadTemplates() {
    setLoadingT(true);
    const db = window.supabaseClient;
    // Super admin needs service-role visibility — fetch all (including inactive)
    const { data } = await db.from("document_templates").select("*").order("sort_order");
    setTemplates(data || []);
    setLoadingT(false);
  }

  async function loadCompanyDocs(companyId) {
    if (!companyId) { setCompanyDocs([]); return; }
    setLoadingD(true);
    const db = window.supabaseClient;
    const { data } = await db.from("company_documents").select("*").eq("company_id", companyId).order("created_at", { ascending: false });
    setCompanyDocs(data || []);
    setLoadingD(false);
  }

  useAdmEffect(() => { loadTemplates(); }, []);
  useAdmEffect(() => { if (tab === "company") loadCompanyDocs(selectedCompany); }, [tab, selectedCompany]);

  function openNewTemplate() {
    setTplForm({ name: "", slug: "", category: "contract", version: "1.0", body_html: "", applies_to: "", is_active: true });
    setEditTpl(null);
    setShowTplModal(true);
  }

  function openEditTemplate(t) {
    setTplForm({
      name: t.name, slug: t.slug, category: t.category,
      version: t.version, body_html: t.body_html,
      applies_to: (t.applies_to || []).join(", "), is_active: t.is_active,
    });
    setEditTpl(t);
    setShowTplModal(true);
  }

  async function saveTpl() {
    const db = window.supabaseClient;
    const payload = {
      ...tplForm,
      applies_to: tplForm.applies_to ? tplForm.applies_to.split(",").map(s => s.trim()).filter(Boolean) : [],
      updated_at: new Date().toISOString(),
    };
    if (editTpl) {
      const { error } = await db.from("document_templates").update(payload).eq("id", editTpl.id);
      if (error) { showToast(error.message, "error"); return; }
    } else {
      const { error } = await db.from("document_templates").insert({ ...payload, created_at: new Date().toISOString() });
      if (error) { showToast(error.message, "error"); return; }
    }
    setShowTplModal(false);
    showToast(editTpl ? "Template updated" : "Template created", "success");
    loadTemplates();
  }

  async function toggleTplActive(t) {
    const db = window.supabaseClient;
    await db.from("document_templates").update({ is_active: !t.is_active }).eq("id", t.id);
    loadTemplates();
  }

  async function deleteTpl(id) {
    const db = window.supabaseClient;
    await db.from("document_templates").delete().eq("id", id);
    showToast("Template deleted", "success");
    loadTemplates();
  }

  // Generate a document for a company from a template
  async function generateDoc(template, company) {
    setGenLoading(true);
    const db = window.supabaseClient;

    // Load platform settings for variable substitution
    const { data: ps } = await db.from("platform_settings").select("key,value");
    const settings = {};
    (ps || []).forEach(r => { settings[r.key] = r.value; });

    // Load plan name
    let planName = company.plan || "Trial";
    if (company.plan) {
      const { data: pp } = await db.from("pricing_plans").select("name,price_cents").eq("slug", company.plan).maybeSingle();
      if (pp) {
        planName = pp.name;
        settings.monthly_fee = `$${(pp.price_cents / 100).toFixed(0)}/mo`;
      }
    }

    const vars = {
      company_name: company.name || "",
      owner_name: company.owner_name || "",
      plan_name: planName,
      monthly_fee: settings.monthly_fee || "",
      start_date: new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }),
      support_email: settings.support_email || "craig@perduracapital.com",
      support_hours: settings.support_hours || "Mon – Fri, 9am – 6pm ET",
      brand_name: settings.brand_name || "PerduraCFO",
      company_legal_name: settings.company_name || "Perdura Capital LLC",
    };

    let body = template.body_html;
    Object.entries(vars).forEach(([k, v]) => {
      body = body.replace(new RegExp(`\\{\\{${k}\\}\\}`, "g"), v);
    });

    const { error } = await db.from("company_documents").insert({
      company_id: company.id,
      template_id: template.id,
      name: `${template.name} — ${company.name}`,
      category: template.category,
      body_html: body,
      status: "published",
      version: template.version,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    });

    if (error) {
      showToast(error.message, "error");
    } else {
      showToast(`"${template.name}" published for ${company.name}`, "success");
      if (selectedCompany === company.id) loadCompanyDocs(company.id);
    }
    setGenLoading(false);
    setGenModal(null);
  }

  async function updateDocStatus(docId, status) {
    const db = window.supabaseClient;
    await db.from("company_documents").update({ status, updated_at: new Date().toISOString() }).eq("id", docId);
    loadCompanyDocs(selectedCompany);
    showToast("Document status updated", "success");
  }

  const catStyle = (cat) => DOC_CATEGORIES.find(c => c.v === cat) || { color: "#94a3b8" };

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <div>
          <h2 className="pc-adm-section-title">Document Repository</h2>
          <p style={{ fontSize: 12.5, color: "var(--text-3)", margin: "2px 0 0" }}>Manage templates, generate contracts, and publish docs to customers.</p>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", gap: 4, borderBottom: "1px solid var(--border)", marginBottom: 20 }}>
        {[
          { k: "templates", l: "Templates" },
          { k: "company",   l: "Customer Documents" },
          { k: "generate",  l: "Generate & Send" },
        ].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            padding: "8px 14px", fontSize: 13, fontWeight: tab === t.k ? 600 : 400,
            color: tab === t.k ? "var(--text)" : "var(--text-3)",
            background: "none", border: "none", cursor: "pointer",
            borderBottom: tab === t.k ? "2px solid var(--accent)" : "2px solid transparent",
            marginBottom: -1, transition: "color 0.15s",
          }}>{t.l}</button>
        ))}
      </div>

      {/* ── Templates tab ── */}
      {tab === "templates" && (
        <div>
          <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 16 }}>
            <button className="pc-adm-btn-primary" onClick={openNewTemplate} style={{ display: "flex", alignItems: "center", gap: 7 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
              New Template
            </button>
          </div>

          {loadingT ? (
            <div style={{ textAlign: "center", padding: 40, color: "var(--text-3)", fontSize: 13 }}>Loading…</div>
          ) : templates.length === 0 ? (
            <div style={{ textAlign: "center", padding: 60, color: "var(--text-3)", fontSize: 13 }}>No templates yet. Create your first template above.</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {templates.map(t => (
                <div key={t.id} className="pc-adm-card" style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 14 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 8, flexShrink: 0,
                    background: `${catStyle(t.category).color}18`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={catStyle(t.category).color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>
                    </svg>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--text)" }}>{t.name}</div>
                    <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2, display: "flex", gap: 10, flexWrap: "wrap" }}>
                      <span style={{ color: catStyle(t.category).color, textTransform: "capitalize" }}>{t.category}</span>
                      <span>v{t.version}</span>
                      {t.applies_to?.length > 0 && <span>Applies to: {t.applies_to.join(", ")}</span>}
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{
                      fontSize: 11, padding: "2px 8px", borderRadius: 99, fontWeight: 500,
                      background: t.is_active ? "rgba(16,185,129,0.12)" : "rgba(148,163,184,0.12)",
                      color: t.is_active ? "#10b981" : "#94a3b8",
                    }}>{t.is_active ? "Active" : "Hidden"}</span>
                    <button className="pc-adm-btn" style={{ padding: "5px 10px", fontSize: 12 }} onClick={() => setPreviewDoc(t)}>Preview</button>
                    <button className="pc-adm-btn" style={{ padding: "5px 10px", fontSize: 12 }} onClick={() => openEditTemplate(t)}>Edit</button>
                    <button
                      className="pc-adm-btn"
                      style={{ padding: "5px 10px", fontSize: 12, color: t.is_active ? "#d97706" : "#10b981" }}
                      onClick={() => toggleTplActive(t)}
                    >{t.is_active ? "Hide" : "Activate"}</button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* ── Company documents tab ── */}
      {tab === "company" && (
        <div>
          <div style={{ display: "flex", gap: 12, marginBottom: 20, alignItems: "center" }}>
            <div style={{ flex: 1, maxWidth: 320 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", display: "block", marginBottom: 5 }}>Select Customer</label>
              <select
                value={selectedCompany}
                onChange={e => setSelectedCompany(e.target.value)}
                style={{ width: "100%", background: "var(--bg-elev-2)", border: "1px solid var(--border)", borderRadius: 6, padding: "8px 10px", fontSize: 13, color: "var(--text)", outline: "none" }}
              >
                <option value="">— Choose a customer —</option>
                {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
          </div>

          {!selectedCompany ? (
            <div style={{ textAlign: "center", padding: 60, color: "var(--text-3)", fontSize: 13 }}>Select a customer above to view their documents.</div>
          ) : loadingD ? (
            <div style={{ textAlign: "center", padding: 40, color: "var(--text-3)", fontSize: 13 }}>Loading…</div>
          ) : companyDocs.length === 0 ? (
            <div style={{ textAlign: "center", padding: 60 }}>
              <div style={{ color: "var(--text-3)", fontSize: 13, marginBottom: 12 }}>No documents for this customer yet.</div>
              <button className="pc-adm-btn-primary" onClick={() => setTab("generate")}>Generate a document</button>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {companyDocs.map(d => {
                const st = DOC_STATUS[d.status] || DOC_STATUS.draft;
                return (
                  <div key={d.id} className="pc-adm-card" style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 14 }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 8, flexShrink: 0,
                      background: `${catStyle(d.category).color}18`,
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={catStyle(d.category).color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>
                      </svg>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--text)" }}>{d.name}</div>
                      <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>
                        {d.category} · v{d.version} · Created {fmtDate(d.created_at)}
                        {d.signed_at && ` · Signed ${fmtDate(d.signed_at)}`}
                      </div>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 99, fontWeight: 500, background: st.bg, color: st.color }}>{st.label}</span>
                      <button className="pc-adm-btn" style={{ padding: "5px 10px", fontSize: 12 }} onClick={() => setPreviewDoc(d)}>View</button>
                      {d.status === "draft" && (
                        <button className="pc-adm-btn-primary" style={{ padding: "5px 10px", fontSize: 12 }} onClick={() => updateDocStatus(d.id, "published")}>Publish</button>
                      )}
                      {d.status === "published" && (
                        <button className="pc-adm-btn" style={{ padding: "5px 10px", fontSize: 12, color: "#94a3b8" }} onClick={() => updateDocStatus(d.id, "archived")}>Archive</button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* ── Generate & Send tab ── */}
      {tab === "generate" && (
        <div>
          <p style={{ fontSize: 13, color: "var(--text-3)", marginBottom: 20 }}>
            Select a template and a customer to generate a personalised document with their details substituted automatically.
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 16 }}>
            {templates.filter(t => t.is_active).map(t => (
              <div key={t.id} className="pc-adm-plan-card" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 8, flexShrink: 0,
                    background: `${catStyle(t.category).color}18`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke={catStyle(t.category).color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>
                    </svg>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--text)" }}>{t.name}</div>
                    <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 3, textTransform: "capitalize" }}>{t.category} · v{t.version}</div>
                    {t.applies_to?.length > 0 && (
                      <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 3 }}>
                        For: {t.applies_to.map(a => a.charAt(0).toUpperCase() + a.slice(1)).join(", ")}
                      </div>
                    )}
                  </div>
                </div>
                <button
                  className="pc-adm-btn-primary"
                  style={{ width: "100%", fontSize: 12.5, padding: "8px 0" }}
                  onClick={() => setGenModal({ template: t, companyId: "" })}
                >
                  Generate for customer →
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Preview / View Modal ── */}
      {previewDoc && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)", zIndex: 9999, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
          <div style={{ background: "var(--bg-card-solid)", borderRadius: 12, width: "100%", maxWidth: 780, maxHeight: "90vh", display: "flex", flexDirection: "column", overflow: "hidden", border: "1px solid var(--border)" }}>
            <div style={{ padding: "18px 24px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontWeight: 700, fontSize: 15, color: "var(--text)" }}>{previewDoc.name || previewDoc.name}</div>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>
                  {previewDoc.category} · v{previewDoc.version}
                </div>
              </div>
              <button onClick={() => setPreviewDoc(null)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-3)", padding: 6 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <div style={{ flex: 1, overflow: "auto", padding: "28px 36px", background: "#fff", color: "#1e293b", fontSize: 14, lineHeight: 1.7 }}
              dangerouslySetInnerHTML={{ __html: previewDoc.body_html }}
            />
          </div>
        </div>
      )}

      {/* ── Template edit modal ── */}
      {showTplModal && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)", zIndex: 9999, display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "40px 24px", overflowY: "auto" }}>
          <div style={{ background: "var(--bg-card-solid)", borderRadius: 12, width: "100%", maxWidth: 700, border: "1px solid var(--border)" }}>
            <div style={{ padding: "18px 24px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ fontWeight: 700, fontSize: 15, color: "var(--text)" }}>{editTpl ? "Edit Template" : "New Template"}</div>
              <button onClick={() => setShowTplModal(false)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-3)", padding: 6 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <div style={{ padding: "24px 24px 8px", display: "flex", flexDirection: "column", gap: 18 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <Field label="Template Name">
                  <AInput value={tplForm.name} onChange={v => setTplForm(f => ({ ...f, name: v }))} placeholder="e.g. Service Agreement" />
                </Field>
                <Field label="Slug (unique identifier)">
                  <AInput value={tplForm.slug} onChange={v => setTplForm(f => ({ ...f, slug: v.toLowerCase().replace(/\s+/g, "-") }))} placeholder="service-agreement" />
                </Field>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
                <Field label="Category">
                  <select value={tplForm.category} onChange={e => setTplForm(f => ({ ...f, category: e.target.value }))} style={{ width: "100%", background: "var(--bg-elev-2)", border: "1px solid var(--border)", borderRadius: 6, padding: "8px 10px", fontSize: 13, color: "var(--text)", outline: "none" }}>
                    {DOC_CATEGORIES.map(c => <option key={c.v} value={c.v}>{c.l}</option>)}
                  </select>
                </Field>
                <Field label="Version">
                  <AInput value={tplForm.version} onChange={v => setTplForm(f => ({ ...f, version: v }))} placeholder="1.0" />
                </Field>
                <Field label="Applies to (business types)">
                  <AInput value={tplForm.applies_to} onChange={v => setTplForm(f => ({ ...f, applies_to: v }))} placeholder="saas, retail (or blank = all)" />
                </Field>
              </div>
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                  <label style={{ fontSize: 11, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Body HTML</label>
                  <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", fontSize: 12.5, color: "var(--text-3)" }}>
                    <input type="checkbox" checked={tplForm.is_active} onChange={e => setTplForm(f => ({ ...f, is_active: e.target.checked }))} style={{ accentColor: "var(--accent)" }} />
                    Active (visible to customers)
                  </label>
                </div>
                <textarea
                  value={tplForm.body_html}
                  onChange={e => setTplForm(f => ({ ...f, body_html: e.target.value }))}
                  rows={16}
                  placeholder="<h1>Document Title</h1><p>Content with {{company_name}} variables...</p>"
                  style={{ width: "100%", background: "var(--bg-elev-2)", border: "1px solid var(--border)", borderRadius: 6, padding: "10px 12px", fontSize: 12.5, color: "var(--text)", outline: "none", fontFamily: "monospace", resize: "vertical", boxSizing: "border-box" }}
                />
                <TemplateVariablesHelp />
              </div>
            </div>
            <div style={{ padding: "16px 24px 24px", display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <button className="pc-adm-btn" onClick={() => setShowTplModal(false)}>Cancel</button>
              <button className="pc-adm-btn-primary" onClick={saveTpl}>{editTpl ? "Save changes" : "Create template"}</button>
            </div>
          </div>
        </div>
      )}

      {/* ── Generate for customer modal ── */}
      {genModal && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)", zIndex: 9999, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
          <div style={{ background: "var(--bg-card-solid)", borderRadius: 12, width: "100%", maxWidth: 440, border: "1px solid var(--border)" }}>
            <div style={{ padding: "18px 24px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ fontWeight: 700, fontSize: 15, color: "var(--text)" }}>Generate: {genModal.template.name}</div>
              <button onClick={() => setGenModal(null)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--text-3)", padding: 6 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <div style={{ padding: 24 }}>
              <Field label="Select customer">
                <select
                  value={genModal.companyId}
                  onChange={e => setGenModal(m => ({ ...m, companyId: e.target.value }))}
                  style={{ width: "100%", background: "var(--bg-elev-2)", border: "1px solid var(--border)", borderRadius: 6, padding: "8px 10px", fontSize: 13, color: "var(--text)", outline: "none" }}
                >
                  <option value="">— Select customer —</option>
                  {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </Field>
              {genModal.companyId && (
                <div style={{ marginTop: 14, padding: "12px 14px", background: "var(--bg-elev-2)", borderRadius: 8, fontSize: 12.5, color: "var(--text-2)" }}>
                  Will substitute: company name, owner name, plan details, and platform branding automatically.
                </div>
              )}
            </div>
            <div style={{ padding: "0 24px 24px", display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <button className="pc-adm-btn" onClick={() => setGenModal(null)}>Cancel</button>
              <button
                className="pc-adm-btn-primary"
                disabled={!genModal.companyId || genLoading}
                onClick={() => {
                  const co = companies.find(c => c.id === genModal.companyId);
                  if (co) generateDoc(genModal.template, co);
                }}
              >
                {genLoading ? "Generating…" : "Generate & Publish"}
              </button>
            </div>
          </div>
        </div>
      )}

      {toast && <AdminToast msg={toast.msg} type={toast.type} />}
    </div>
  );
}

// ─── Analytics section ────────────────────────────────────────────────────────

function AnalyticsSection({ companies, allUsers }) {
  const active  = companies.filter(c => c.status === "active");
  const trial   = companies.filter(c => c.status === "trial");
  const churned = companies.filter(c => c.status === "churned");

  const mrr = companies.reduce((s, c) => s + (c.mrr || 0), 0);
  const activeMrr = active.reduce((s, c) => s + (c.mrr || 0), 0);

  // Trial → Active conversion
  const conversionRate = (active.length / Math.max(active.length + trial.length, 1) * 100).toFixed(0);

  // Churn rate
  const churnRate = (churned.length / Math.max(companies.length, 1) * 100).toFixed(0);

  // Users active in last 7 days
  const activeUsers7d = allUsers.filter(u => u.last_sign_in_at && (Date.now() - new Date(u.last_sign_in_at)) < 7 * 86400000).length;
  const activeUsers30d = allUsers.filter(u => u.last_sign_in_at && (Date.now() - new Date(u.last_sign_in_at)) < 30 * 86400000).length;

  // Plan breakdown
  const planCounts = PLAN_OPTIONS.reduce((acc, p) => {
    acc[p] = companies.filter(c => (c.plan || "trial") === p).length;
    return acc;
  }, {});
  const maxPlan = Math.max(...Object.values(planCounts), 1);

  // Business model breakdown
  const modelCounts = BIZ_MODELS.reduce((acc, b) => {
    acc[b.v] = companies.filter(c => (c.business_model || c.business_type) === b.v).length;
    return acc;
  }, {});
  const maxModel = Math.max(...Object.values(modelCounts), 1);

  // Revenue band breakdown
  const revBands = ["Under $500K","$500K – $1M","$1M – $3M","$3M – $8M","$8M – $15M","$15M – $30M","$30M+"];
  const bandCounts = revBands.reduce((acc, b) => {
    acc[b] = companies.filter(c => c.revenue_band === b).length;
    return acc;
  }, {});

  // Monthly growth (created_at by month, last 6 months)
  const now = new Date();
  const months = Array.from({ length: 6 }, (_, i) => {
    const d = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1);
    return { label: d.toLocaleDateString("en-US", { month: "short" }), year: d.getFullYear(), month: d.getMonth() };
  });
  const growthData = months.map(m => ({
    label: m.label,
    count: companies.filter(c => {
      const d = new Date(c.created_at);
      return d.getFullYear() === m.year && d.getMonth() === m.month;
    }).length,
  }));
  const maxGrowth = Math.max(...growthData.map(d => d.count), 1);

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Analytics</h2>
        <div style={{ fontSize: 12, color: "var(--text-3)" }}>Platform-wide metrics</div>
      </div>

      {/* Top KPIs */}
      <div className="pc-adm-kpi-row" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: 20 }}>
        <KpiCard label="Trial → Active Rate" value={`${conversionRate}%`}
          accent={conversionRate >= 50 ? "#10b981" : "#d97706"}
          sub={`${active.length} active of ${active.length + trial.length} qualified`} />
        <KpiCard label="Churn Rate" value={`${churnRate}%`}
          accent={churnRate <= 10 ? "#10b981" : "#ef4444"}
          sub={`${churned.length} churned total`} />
        <KpiCard label="DAU / WAU" value={`${activeUsers7d}`}
          sub={`Active users this week`} />
        <KpiCard label="Monthly Active Users" value={`${activeUsers30d}`}
          sub={`Logged in within 30 days`} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        {/* Customer growth */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">New Customers by Month</div>
            <div style={{ fontSize: 11, color: "var(--text-3)" }}>Last 6 months</div>
          </div>
          <div style={{ padding: "20px 18px", display: "flex", alignItems: "flex-end", gap: 8, height: 140 }}>
            {growthData.map((d, i) => (
              <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <div style={{ fontSize: 10, color: "var(--text-3)", fontWeight: 600 }}>{d.count || ""}</div>
                <div style={{
                  width: "100%", borderRadius: "4px 4px 0 0",
                  height: `${Math.max((d.count / maxGrowth) * 80, d.count > 0 ? 6 : 2)}px`,
                  background: d.count > 0 ? "var(--accent)" : "var(--border-strong)",
                  transition: "height 0.4s",
                }} />
                <div style={{ fontSize: 10, color: "var(--text-3)" }}>{d.label}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Plan distribution */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">Plan Distribution</div>
          </div>
          <div style={{ padding: "12px 18px" }}>
            {PLAN_OPTIONS.map(p => (
              <div key={p} style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                <div style={{ width: 64, fontSize: 12, color: "var(--text-2)", textTransform: "capitalize", flexShrink: 0 }}>{p}</div>
                <div style={{ flex: 1, height: 8, background: "var(--border)", borderRadius: 4, overflow: "hidden" }}>
                  <div style={{
                    height: "100%", borderRadius: 4, transition: "width 0.5s",
                    width: `${(planCounts[p] / maxPlan) * 100}%`,
                    background: p === "enterprise" ? "#7c3aed" : p === "pro" ? "#2563eb" : p === "growth" ? "#10b981" : p === "starter" ? "#0891b2" : "var(--border-strong)",
                  }} />
                </div>
                <div style={{ width: 20, fontSize: 12, color: "var(--text-3)", textAlign: "right" }}>{planCounts[p]}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Business model mix */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">Business Model Mix</div>
          </div>
          <div style={{ padding: "12px 18px" }}>
            {BIZ_MODELS.map(b => (
              <div key={b.v} style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                <div style={{ width: 160, fontSize: 12, color: "var(--text-2)", flexShrink: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {b.icon} {b.l}
                </div>
                <div style={{ flex: 1, height: 8, background: "var(--border)", borderRadius: 4, overflow: "hidden" }}>
                  <div style={{
                    height: "100%", borderRadius: 4, width: `${(modelCounts[b.v] / maxModel) * 100}%`,
                    background: "var(--accent)", transition: "width 0.5s",
                  }} />
                </div>
                <div style={{ width: 20, fontSize: 12, color: "var(--text-3)", textAlign: "right" }}>{modelCounts[b.v]}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Revenue band */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">Customer Revenue Bands</div>
            <div style={{ fontSize: 11, color: "var(--text-3)" }}>Self-reported ARR</div>
          </div>
          <div style={{ padding: "12px 18px" }}>
            {revBands.map(b => {
              const count = bandCounts[b] || 0;
              const maxBand = Math.max(...Object.values(bandCounts), 1);
              return (
                <div key={b} style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                  <div style={{ width: 110, fontSize: 11, color: "var(--text-2)", flexShrink: 0 }}>{b}</div>
                  <div style={{ flex: 1, height: 8, background: "var(--border)", borderRadius: 4, overflow: "hidden" }}>
                    <div style={{ height: "100%", borderRadius: 4, width: `${(count / maxBand) * 100}%`, background: "#2563eb", transition: "width 0.5s" }} />
                  </div>
                  <div style={{ width: 20, fontSize: 12, color: "var(--text-3)", textAlign: "right" }}>{count}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Pricing Plans section ────────────────────────────────────────────────────

function PricingPlansSection() {
  const [plans, setPlans] = useAdm([]);
  const [loading, setLoading] = useAdm(true);
  const [editing, setEditing] = useAdm(null); // plan object or null for new
  const [saving, setSaving] = useAdm(false);
  const [confirmDel, setConfirmDel] = useAdm(null);
  const [toast, showToast] = useAdminToast();

  const loadPlans = async () => {
    const db = window.supabaseClient;
    const { data } = await db.from("pricing_plans").select("*").order("sort_order");
    setPlans(data || []);
    setLoading(false);
  };

  useAdmEffect(() => { loadPlans(); }, []);

  const newPlan = () => setEditing({
    id: null, name: "", slug: "", price_cents: 0,
    description: "", features: [], is_active: true, sort_order: plans.length,
  });

  const savePlan = async () => {
    if (!editing.name.trim() || !editing.slug.trim()) return;
    setSaving(true);
    const db = window.supabaseClient;
    const payload = {
      name: editing.name.trim(),
      slug: editing.slug.trim(),
      price_cents: Math.round(parseFloat(editing.price_cents || 0) * 100),
      description: editing.description || "",
      features: Array.isArray(editing.features) ? editing.features : (editing.features || "").split("\n").map(s => s.trim()).filter(Boolean),
      is_active: editing.is_active,
      sort_order: editing.sort_order || 0,
      updated_at: new Date().toISOString(),
    };
    if (editing.id) {
      await db.from("pricing_plans").update(payload).eq("id", editing.id);
    } else {
      payload.created_at = new Date().toISOString();
      await db.from("pricing_plans").insert(payload);
    }
    await loadPlans();
    setSaving(false);
    setEditing(null);
    showToast(editing.id ? "Plan updated." : "Plan created.");
  };

  const deletePlan = async (id) => {
    const db = window.supabaseClient;
    await db.from("pricing_plans").delete().eq("id", id);
    setPlans(prev => prev.filter(p => p.id !== id));
    setConfirmDel(null);
    showToast("Plan deleted.", "error");
  };

  const toggleActive = async (plan) => {
    const db = window.supabaseClient;
    await db.from("pricing_plans").update({ is_active: !plan.is_active }).eq("id", plan.id);
    setPlans(prev => prev.map(p => p.id === plan.id ? { ...p, is_active: !p.is_active } : p));
  };

  const PLAN_COLORS = { trial: "#94a3b8", starter: "#0891b2", growth: "#10b981", pro: "#2563eb", enterprise: "#d97706" };

  return (
    <div className="pc-adm-section">
      {toast && <AdminToast {...toast} />}
      <div className="pc-adm-section-header">
        <div>
          <h2 className="pc-adm-section-title">Pricing Plans</h2>
          <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>Manage the packages shown on your pricing page and selected during onboarding</div>
        </div>
        <button className="pc-adm-btn-primary" onClick={newPlan} style={{ fontSize: 13, padding: "9px 18px" }}>
          + New Plan
        </button>
      </div>

      {loading ? (
        <div style={{ display: "flex", justifyContent: "center", padding: 60 }}>
          <div style={{ width: 28, height: 28, border: "2px solid var(--border-strong)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "pc-spin 0.7s linear infinite" }} />
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 16, marginBottom: 24 }}>
          {plans.map(plan => {
            const color = PLAN_COLORS[plan.slug] || "var(--accent)";
            const priceDollars = plan.price_cents / 100;
            const features = Array.isArray(plan.features) ? plan.features : [];
            return (
              <div key={plan.id} className="pc-adm-plan-card" style={{ opacity: plan.is_active ? 1 : 0.5 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color, textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 4 }}>{plan.name}</div>
                    <div style={{ fontSize: 26, fontWeight: 700, color: "var(--text)", letterSpacing: -0.04 }}>
                      {plan.price_cents === 0 ? (plan.slug === "enterprise" ? "Custom" : "Free") : `$${priceDollars % 1 === 0 ? priceDollars.toFixed(0) : priceDollars.toFixed(2)}`}
                      {plan.price_cents > 0 && <span style={{ fontSize: 13, fontWeight: 400, color: "var(--text-3)" }}>/mo</span>}
                    </div>
                  </div>
                  <div style={{ display: "flex", gap: 4 }}>
                    <button
                      className="pc-adm-btn-ghost"
                      style={{ fontSize: 11, padding: "4px 10px" }}
                      onClick={() => setEditing({ ...plan, price_cents: plan.price_cents / 100, features: features.join("\n") })}
                    >Edit</button>
                    <button
                      className="pc-adm-btn-ghost"
                      style={{ fontSize: 11, padding: "4px 10px", color: plan.is_active ? "var(--text-3)" : "#10b981" }}
                      onClick={() => toggleActive(plan)}
                    >{plan.is_active ? "Hide" : "Show"}</button>
                  </div>
                </div>

                <div style={{ fontSize: 12, color: "var(--text-2)", lineHeight: 1.5, marginBottom: 14, minHeight: 34 }}>{plan.description}</div>

                <div style={{ borderTop: "1px solid var(--border)", paddingTop: 12, display: "flex", flexDirection: "column", gap: 7 }}>
                  {features.slice(0, 5).map((f, i) => (
                    <div key={i} style={{ display: "flex", gap: 8, fontSize: 12, color: "var(--text-2)", alignItems: "flex-start" }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}><polyline points="20 6 9 17 4 12"/></svg>
                      {f}
                    </div>
                  ))}
                  {features.length > 5 && (
                    <div style={{ fontSize: 11, color: "var(--text-3)" }}>+ {features.length - 5} more features</div>
                  )}
                </div>

                <div style={{ marginTop: 14, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="pc-adm-badge" style={plan.is_active ? { background: "rgba(16,185,129,0.1)", color: "#10b981" } : { background: "var(--bg-elev-2)", color: "var(--text-3)" }}>
                    {plan.is_active ? "Active" : "Hidden"}
                  </span>
                  <button
                    style={{ background: "none", border: "none", color: "var(--text-4)", cursor: "pointer", fontSize: 11, padding: 4 }}
                    onMouseEnter={e => e.currentTarget.style.color = "#ef4444"}
                    onMouseLeave={e => e.currentTarget.style.color = "var(--text-4)"}
                    onClick={() => setConfirmDel(plan)}
                  >Delete</button>
                </div>
              </div>
            );
          })}

          {/* Add new card */}
          <button
            onClick={newPlan}
            className="pc-adm-plan-card"
            style={{ border: "2px dashed var(--border-strong)", background: "transparent", cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, minHeight: 200, color: "var(--text-3)" }}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
            <div style={{ fontSize: 12.5, fontWeight: 500 }}>Add pricing plan</div>
          </button>
        </div>
      )}

      <div className="pc-adm-card">
        <div className="pc-adm-card-header">
          <div className="pc-adm-card-title">Plan Reference Table</div>
          <div style={{ fontSize: 11, color: "var(--text-3)" }}>Summary of all active plans</div>
        </div>
        <div className="pc-adm-table-wrap">
          <table className="pc-adm-table">
            <thead>
              <tr>
                <th>Plan</th>
                <th>Slug</th>
                <th style={{ textAlign: "right" }}>Monthly Price</th>
                <th style={{ textAlign: "right" }}>Annual</th>
                <th>Status</th>
                <th>Description</th>
              </tr>
            </thead>
            <tbody>
              {plans.map(p => (
                <tr key={p.id}>
                  <td style={{ paddingLeft: 14, fontWeight: 600 }}>{p.name}</td>
                  <td style={{ fontFamily: "ui-monospace,monospace", fontSize: 12, color: "var(--text-3)" }}>{p.slug}</td>
                  <td style={{ textAlign: "right", fontFamily: "ui-monospace,monospace" }}>
                    {p.price_cents === 0 ? (p.slug === "enterprise" ? "Custom" : "$0") : `$${(p.price_cents / 100).toFixed(0)}/mo`}
                  </td>
                  <td style={{ textAlign: "right", fontFamily: "ui-monospace,monospace", color: "var(--text-3)" }}>
                    {p.price_cents > 0 ? `$${(p.price_cents * 12 / 100).toFixed(0)}/yr` : "—"}
                  </td>
                  <td><span className="pc-adm-badge" style={p.is_active ? { background: "rgba(16,185,129,0.1)", color: "#10b981" } : { background: "var(--bg-elev-2)", color: "var(--text-3)" }}>{p.is_active ? "Active" : "Hidden"}</span></td>
                  <td style={{ fontSize: 12, color: "var(--text-2)" }}>{p.description}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Edit / New Plan Modal */}
      {editing && (
        <div className="pc-adm-modal-bg" onClick={() => setEditing(null)}>
          <div className="pc-adm-modal" style={{ maxWidth: 560 }} onClick={e => e.stopPropagation()}>
            <div className="pc-adm-modal-header">
              <div className="pc-adm-modal-title">{editing.id ? "Edit Plan" : "New Pricing Plan"}</div>
              <button className="pc-adm-modal-close" onClick={() => setEditing(null)}>✕</button>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 14, padding: "4px 0 4px" }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <Field label="Plan name">
                  <AInput value={editing.name} onChange={v => setEditing(p => ({ ...p, name: v, slug: p.id ? p.slug : v.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "") }))} placeholder="e.g. Starter" />
                </Field>
                <Field label="Slug (machine key)">
                  <AInput value={editing.slug} onChange={v => setEditing(p => ({ ...p, slug: v.toLowerCase().replace(/[^a-z0-9-]/g, "") }))} placeholder="e.g. starter" />
                </Field>
              </div>
              <Field label="Monthly price (USD — enter 0 for free/custom)">
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{ color: "var(--text-3)", fontSize: 14 }}>$</span>
                  <input
                    type="number" min="0" step="1"
                    className="pc-adm-input"
                    style={{ flex: 1 }}
                    value={editing.price_cents}
                    onChange={e => setEditing(p => ({ ...p, price_cents: e.target.value }))}
                  />
                  <span style={{ color: "var(--text-3)", fontSize: 12 }}>/month</span>
                </div>
              </Field>
              <Field label="Description (one-liner shown on plan card)">
                <AInput value={editing.description} onChange={v => setEditing(p => ({ ...p, description: v }))} placeholder="For growing businesses…" />
              </Field>
              <Field label="Features (one per line — shown as bullet points)">
                <textarea
                  className="pc-adm-input"
                  style={{ minHeight: 110, resize: "vertical", fontFamily: "inherit", lineHeight: 1.6 }}
                  value={Array.isArray(editing.features) ? editing.features.join("\n") : editing.features}
                  onChange={e => setEditing(p => ({ ...p, features: e.target.value }))}
                  placeholder={"All dashboards unlocked\nUp to 5 users\n3 integrations\nEmail support"}
                />
              </Field>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <input type="checkbox" id="plan-active" checked={editing.is_active} onChange={e => setEditing(p => ({ ...p, is_active: e.target.checked })} style={{ cursor: "pointer" }} />
                <label htmlFor="plan-active" style={{ fontSize: 13, cursor: "pointer", color: "var(--text-2)" }}>Plan is active (shown during onboarding and on pricing page)</label>
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", paddingTop: 16, borderTop: "1px solid var(--border)", marginTop: 16 }}>
              <button className="pc-adm-btn-ghost" onClick={() => setEditing(null)}>Cancel</button>
              <button
                className="pc-adm-btn-primary"
                disabled={saving || !editing.name.trim() || !editing.slug.trim()}
                onClick={savePlan}
              >{saving ? "Saving…" : editing.id ? "Save changes" : "Create plan"}</button>
            </div>
          </div>
        </div>
      )}

      {confirmDel && (
        <ConfirmDialog
          message={`Delete the "${confirmDel.name}" plan? This won't affect existing customers already on this plan.`}
          confirmLabel="Delete plan"
          danger
          onConfirm={() => deletePlan(confirmDel.id)}
          onCancel={() => setConfirmDel(null)}
        />
      )}
    </div>
  );
}

// ─── Quick Invite Modal ───────────────────────────────────────────────────────

function QuickInviteModal({ onClose, plans, onCreated }) {
  const [step, setStep] = useAdm(0); // 0 = form, 1 = success
  const [loading, setLoading] = useAdm(false);
  const [error, setError] = useAdm("");
  const [companyName, setCompanyName] = useAdm("");
  const [ownerName, setOwnerName] = useAdm("");
  const [ownerEmail, setOwnerEmail] = useAdm("");
  const [planSlug, setPlanSlug] = useAdm("trial");
  const [subdomain, setSubdomain] = useAdm("");
  const [createdCompany, setCreatedCompany] = useAdm(null);

  useAdmEffect(() => {
    if (companyName) {
      setSubdomain(companyName.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, ""));
    }
  }, [companyName]);

  const activePlans = (plans || []).filter(p => p.is_active);
  const canSubmit = companyName.trim() && ownerEmail.trim() && subdomain.trim() && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(ownerEmail);

  const handleInvite = async () => {
    setError("");
    setLoading(true);
    try {
      const result = await callAdmin("invite", "POST", {
        companyName: companyName.trim(),
        subdomain: subdomain.trim(),
        ownerName: ownerName.trim(),
        ownerEmail: ownerEmail.trim(),
        plan: planSlug,
      });
      setCreatedCompany(result.company);
      if (onCreated) onCreated(result.company);
      setStep(1);
    } catch (err) {
      setError(err.message);
    }
    setLoading(false);
  };

  const planColor = { trial: "#94a3b8", starter: "#0891b2", growth: "#10b981", pro: "#2563eb", enterprise: "#d97706" };

  return (
    <div className="pc-adm-modal-bg" onClick={step === 0 ? onClose : undefined}>
      <div className="pc-adm-modal" style={{ maxWidth: 520, padding: 0, overflow: "hidden" }} onClick={e => e.stopPropagation()}>

        {step === 0 ? (
          <>
            {/* Header with gradient */}
            <div style={{
              background: "linear-gradient(135deg, #0c1220 0%, #1a2744 100%)",
              padding: "28px 28px 24px",
              position: "relative",
            }}>
              <button className="pc-adm-modal-close" onClick={onClose} style={{ position: "absolute", top: 16, right: 16 }}>✕</button>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
                <div style={{
                  width: 42, height: 42, borderRadius: 12,
                  background: "rgba(16,185,129,0.15)", border: "1px solid rgba(16,185,129,0.25)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                </div>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: "#fff", letterSpacing: -0.3 }}>Invite a Customer</div>
                  <div style={{ fontSize: 12, color: "rgba(255,255,255,0.5)", marginTop: 2 }}>Creates their account and sends a personalised activation email</div>
                </div>
              </div>

              {/* Email preview badge */}
              <div style={{
                background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.1)",
                borderRadius: 8, padding: "10px 14px",
                display: "flex", alignItems: "center", gap: 10,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                <div style={{ flex: 1, fontSize: 12, color: "rgba(255,255,255,0.6)", lineHeight: 1.4 }}>
                  They'll receive a branded invite email with a one-click activation link — no password required to start.
                </div>
              </div>
            </div>

            <div style={{ padding: "22px 28px" }}>
              {error && <div className="pc-auth-error-banner" style={{ marginBottom: 16 }}>{error}</div>}

              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <Field label="Company name">
                  <AInput value={companyName} onChange={setCompanyName} placeholder="Acme Corp" autoFocus />
                </Field>

                <Field label="Subdomain" hint={subdomain ? `Dashboard at: ${subdomain}.cfodash.app` : "Auto-generated from company name"}>
                  <div style={{ display: "flex", alignItems: "center", gap: 0, border: "1px solid var(--border-strong)", borderRadius: 8, overflow: "hidden", background: "var(--bg-elev-1)" }}>
                    <AInput
                      value={subdomain}
                      onChange={v => setSubdomain(v.toLowerCase().replace(/[^a-z0-9-]/g, ""))}
                      placeholder="acme-corp"
                      style={{ border: "none", borderRadius: 0, background: "transparent", flex: 1 }}
                    />
                    <div style={{ padding: "0 12px", fontSize: 12, color: "var(--text-3)", borderLeft: "1px solid var(--border)", height: "100%", display: "flex", alignItems: "center", background: "var(--bg-elev-2)", whiteSpace: "nowrap" }}>
                      .cfodash.app
                    </div>
                  </div>
                </Field>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <Field label="Owner name">
                    <AInput value={ownerName} onChange={setOwnerName} placeholder="Jane Smith" />
                  </Field>
                  <Field label="Owner email">
                    <AInput type="email" value={ownerEmail} onChange={setOwnerEmail} placeholder="jane@acme.com" />
                  </Field>
                </div>

                <Field label="Starting plan">
                  <ASelect value={planSlug} onChange={setPlanSlug}>
                    {activePlans.length > 0
                      ? activePlans.map(p => <option key={p.slug} value={p.slug}>{p.name} — {p.price_cents === 0 ? (p.slug === "enterprise" ? "Custom" : "Free") : `$${p.price_cents / 100}/mo`}</option>)
                      : PLAN_OPTIONS.map(p => <option key={p} value={p}>{p[0].toUpperCase() + p.slice(1)}</option>)
                    }
                  </ASelect>
                </Field>

                {/* Plan preview chip */}
                {planSlug && (
                  <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 12px", background: "var(--bg-elev-1)", borderRadius: 8, border: "1px solid var(--border)" }}>
                    <div style={{ width: 8, height: 8, borderRadius: "50%", background: planColor[planSlug] || "var(--accent)", flexShrink: 0 }} />
                    <div style={{ fontSize: 12, color: "var(--text-2)" }}>
                      Customer will be onboarded on the <strong>{(activePlans.find(p => p.slug === planSlug) || {}).name || planSlug}</strong> plan and can upgrade from the billing portal.
                    </div>
                  </div>
                )}
              </div>

              <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
                <button className="pc-adm-btn-ghost" onClick={onClose}>Cancel</button>
                <button
                  className="pc-adm-btn-primary"
                  style={{ padding: "10px 22px" }}
                  disabled={loading || !canSubmit}
                  onClick={handleInvite}
                >
                  {loading ? "Sending invite…" : "Send invite email →"}
                </button>
              </div>
            </div>
          </>
        ) : (
          /* Success state */
          <div style={{ padding: "40px 32px", textAlign: "center" }}>
            <div style={{
              width: 64, height: 64, borderRadius: "50%",
              background: "rgba(16,185,129,0.12)", border: "2px solid rgba(16,185,129,0.3)",
              display: "flex", alignItems: "center", justifyContent: "center",
              margin: "0 auto 20px",
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 8, letterSpacing: -0.3 }}>Invite sent!</div>
            <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.65, marginBottom: 6 }}>
              <strong>{ownerName || ownerEmail}</strong> has been invited to access the <strong>{companyName}</strong> dashboard.
            </div>
            <div style={{ fontSize: 12.5, color: "var(--text-3)", lineHeight: 1.6, marginBottom: 28 }}>
              They'll receive an activation email at <strong>{ownerEmail}</strong>. The link is valid for 24 hours and takes them directly to their personalised dashboard setup.
            </div>

            <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border)", borderRadius: 8, padding: "14px 16px", marginBottom: 24, textAlign: "left" }}>
              <div style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 8 }}>Account details</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {[
                  ["Company", createdCompany?.name],
                  ["Subdomain", createdCompany?.subdomain + ".cfodash.app"],
                  ["Plan", (createdCompany?.plan || "trial")[0].toUpperCase() + (createdCompany?.plan || "trial").slice(1)],
                  ["Status", "Pending activation"],
                ].map(([k, v]) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
                    <span style={{ color: "var(--text-3)" }}>{k}</span>
                    <span style={{ fontWeight: 500 }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>

            <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
              <button className="pc-adm-btn-ghost" onClick={onClose}>Close</button>
              <button className="pc-adm-btn-primary" onClick={() => {
                setStep(0); setCompanyName(""); setOwnerName(""); setOwnerEmail(""); setSubdomain(""); setPlanSlug("trial"); setCreatedCompany(null);
              }}>Invite another</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Billing & Revenue section ────────────────────────────────────────────────

function BillingSection({ companies, setCompanies }) {
  const [saving, setSaving] = useAdm(null);
  const [editMrr, setEditMrr] = useAdm({});
  const [editPlan, setEditPlan] = useAdm({});
  const [search, setSearch] = useAdm("");
  const [plans, setPlans] = useAdm([]);
  const [invoices, setInvoices] = useAdm([]);
  const [invoicesLoading, setInvoicesLoading] = useAdm(true);
  const [activeTab, setActiveTab] = useAdm("overview"); // overview | invoices
  const [genInvoice, setGenInvoice] = useAdm(null); // company to generate invoice for
  const [invoiceFilter, setInvoiceFilter] = useAdm("all");
  const [toast, showToast] = useAdminToast();

  const totalMrr = companies.reduce((s, c) => s + (c.mrr || 0), 0);
  const arr = totalMrr * 12;
  const activeMrr = companies.filter(c => c.status === "active").reduce((s, c) => s + (c.mrr || 0), 0);
  const avgMrr = companies.filter(c => (c.mrr || 0) > 0).length
    ? Math.round(activeMrr / companies.filter(c => (c.mrr || 0) > 0).length)
    : 0;

  useAdmEffect(() => {
    const db = window.supabaseClient;
    if (!db) return;
    Promise.all([
      db.from("pricing_plans").select("id,name,slug,price_cents,is_active").order("sort_order"),
      db.from("invoices").select("*").order("created_at", { ascending: false }).limit(200),
    ]).then(([{ data: p }, { data: i }]) => {
      setPlans(p || []);
      setInvoices(i || []);
      setInvoicesLoading(false);
    });
  }, []);

  const planMap = {};
  plans.forEach(p => { planMap[p.slug] = p; });
  const companyMap = {};
  companies.forEach(c => { companyMap[c.id] = c; });

  const filtered = companies.filter(c => {
    if (!search) return true;
    const q = search.toLowerCase();
    return c.name.toLowerCase().includes(q) || (c.plan || "").toLowerCase().includes(q);
  }).sort((a, b) => (b.mrr || 0) - (a.mrr || 0));

  async function saveBilling(company) {
    setSaving(company.id);
    try {
      const mrrVal = editMrr[company.id] !== undefined ? Math.round(parseFloat(editMrr[company.id]) * 100) : company.mrr;
      const planVal = editPlan[company.id] !== undefined ? editPlan[company.id] : company.plan;
      await callAdmin("update-company", "POST", { companyId: company.id, mrr: mrrVal, plan: planVal });
      setCompanies(prev => prev.map(c => c.id === company.id ? { ...c, mrr: mrrVal, plan: planVal } : c));
      setEditMrr(prev => { const n = { ...prev }; delete n[company.id]; return n; });
      setEditPlan(prev => { const n = { ...prev }; delete n[company.id]; return n; });
      showToast("Billing updated.");
    } catch (err) { showToast(err.message, "error"); }
    setSaving(null);
  }

  async function generateInvoice(company) {
    const plan = planMap[company.plan] || planMap.trial || { name: company.plan, slug: company.plan, price_cents: company.mrr || 0 };
    const now = new Date();
    const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
    const periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    const dueDate = new Date(periodEnd);
    dueDate.setDate(dueDate.getDate() + 15);

    // Generate invoice number
    const db = window.supabaseClient;
    const { count } = await db.from("invoices").select("*", { count: "exact", head: true });
    const invNum = `INV-${now.getFullYear()}-${String((count || 0) + 1).padStart(4, "0")}`;

    const payload = {
      company_id: company.id,
      plan_slug: plan.slug,
      plan_name: plan.name,
      amount_cents: plan.price_cents || company.mrr || 0,
      currency: "USD",
      status: "open",
      period_start: periodStart.toISOString().slice(0, 10),
      period_end: periodEnd.toISOString().slice(0, 10),
      due_date: dueDate.toISOString().slice(0, 10),
      invoice_number: invNum,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };
    const { data: inv } = await db.from("invoices").insert(payload).select().single();
    if (inv) {
      setInvoices(prev => [inv, ...prev]);
      showToast(`Invoice ${invNum} created.`);
    }
    setGenInvoice(null);
    setActiveTab("invoices");
  }

  async function updateInvoiceStatus(invoiceId, status) {
    const db = window.supabaseClient;
    const updates = { status, updated_at: new Date().toISOString() };
    if (status === "paid") updates.paid_at = new Date().toISOString();
    await db.from("invoices").update(updates).eq("id", invoiceId);
    setInvoices(prev => prev.map(i => i.id === invoiceId ? { ...i, ...updates } : i));
    showToast(status === "paid" ? "Invoice marked as paid." : "Invoice updated.");
  }

  async function voidInvoice(invoiceId) {
    await updateInvoiceStatus(invoiceId, "void");
  }

  const statusStyle = {
    open:  { bg: "rgba(251,191,36,0.12)", color: "#d97706" },
    paid:  { bg: "rgba(16,185,129,0.12)", color: "#10b981" },
    void:  { bg: "rgba(148,163,184,0.1)", color: "#64748b" },
    draft: { bg: "rgba(148,163,184,0.1)", color: "#64748b" },
  };

  const filteredInvoices = invoices.filter(i => {
    if (invoiceFilter === "all") return true;
    return i.status === invoiceFilter;
  });

  const invoiceTotals = {
    open: invoices.filter(i => i.status === "open").reduce((s, i) => s + (i.amount_cents || 0), 0),
    paid: invoices.filter(i => i.status === "paid").reduce((s, i) => s + (i.amount_cents || 0), 0),
    total: invoices.reduce((s, i) => s + (i.status !== "void" ? (i.amount_cents || 0) : 0), 0),
  };

  return (
    <div className="pc-adm-section">
      {toast && <AdminToast {...toast} />}
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Billing & Revenue</h2>
        <div style={{ display: "flex", gap: 8 }}>
          <button
            className="pc-adm-btn-ghost"
            style={{ fontSize: 12 }}
            onClick={() => setActiveTab(activeTab === "invoices" ? "overview" : "invoices")}
          >
            {activeTab === "invoices" ? "← Back to overview" : "View all invoices"}
          </button>
        </div>
      </div>

      <div className="pc-adm-kpi-row" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: 20 }}>
        <KpiCard label="Total MRR" value={fmtMRR(totalMrr)} accent="#10b981" sub="All plans combined" />
        <KpiCard label="ARR" value={fmtMRR(arr)} sub="Annualised" />
        <KpiCard label="Outstanding" value={fmtMRR(invoiceTotals.open)} accent="#d97706" sub={`${invoices.filter(i => i.status === "open").length} open invoices`} />
        <KpiCard label="Collected (all time)" value={fmtMRR(invoiceTotals.paid)} accent="#10b981" sub="Paid invoices" />
      </div>

      {/* Tabs */}
      <div className="pc-section-tabs" style={{ marginBottom: 20, borderBottom: "1px solid var(--border)", paddingBottom: 0 }}>
        {[{ k: "overview", l: "Customer Plans" }, { k: "invoices", l: "Invoices" }].map(t => (
          <button
            key={t.k}
            className={activeTab === t.k ? "active" : ""}
            onClick={() => setActiveTab(t.k)}
            style={{ paddingBottom: 12 }}
          >{t.l}</button>
        ))}
      </div>

      {activeTab === "overview" && (
        <>
          <div className="pc-adm-filters" style={{ marginBottom: 16 }}>
            <input className="pc-adm-search" placeholder="Search customers…"
              value={search} onChange={e => setSearch(e.target.value)} />
          </div>

          <div className="pc-adm-table-wrap">
            <table className="pc-adm-table">
              <thead>
                <tr>
                  <th>Customer</th>
                  <th>Status</th>
                  <th>Plan</th>
                  <th style={{ textAlign: "right" }}>MRR (USD)</th>
                  <th style={{ textAlign: "right" }}>ARR</th>
                  <th>Joined</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(c => {
                  const isDirty = editMrr[c.id] !== undefined || editPlan[c.id] !== undefined;
                  const displayPlan = editPlan[c.id] !== undefined ? editPlan[c.id] : (c.plan || "trial");
                  const displayMrr = editMrr[c.id] !== undefined ? editMrr[c.id] : (c.mrr ? (c.mrr / 100).toString() : "0");
                  return (
                    <tr key={c.id} style={isDirty ? { background: "rgba(59,130,246,0.04)" } : {}}>
                      <td style={{ paddingLeft: 14 }}>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</div>
                        <div style={{ fontSize: 11, color: "var(--text-3)" }}>{c.subdomain}</div>
                      </td>
                      <td><StatusBadge status={c.status} /></td>
                      <td>
                        <ASelect value={displayPlan} onChange={v => setEditPlan(prev => ({ ...prev, [c.id]: v }))}
                          style={{ fontSize: 12, padding: "4px 8px", width: "auto" }}>
                          {plans.filter(p => p.is_active).map(p => <option key={p.slug} value={p.slug}>{p.name}</option>)}
                          {PLAN_OPTIONS.filter(p => !plans.find(pl => pl.slug === p)).map(p => <option key={p} value={p}>{p[0].toUpperCase() + p.slice(1)}</option>)}
                        </ASelect>
                      </td>
                      <td style={{ textAlign: "right" }}>
                        <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 4 }}>
                          <span style={{ color: "var(--text-3)", fontSize: 12 }}>$</span>
                          <input type="number" min="0" step="1"
                            className="pc-adm-input"
                            style={{ width: 80, textAlign: "right", padding: "4px 6px", fontSize: 12 }}
                            value={displayMrr}
                            onChange={e => setEditMrr(prev => ({ ...prev, [c.id]: e.target.value }))} />
                        </div>
                      </td>
                      <td style={{ textAlign: "right", fontSize: 12, color: "var(--text-3)", fontFamily: "ui-monospace,monospace" }}>
                        {fmtMRR((c.mrr || 0) * 12)}
                      </td>
                      <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtDate(c.created_at)}</td>
                      <td>
                        <div style={{ display: "flex", gap: 4 }}>
                          {isDirty && (
                            <button className="pc-adm-btn-primary"
                              style={{ fontSize: 11, padding: "4px 12px" }}
                              disabled={saving === c.id}
                              onClick={() => saveBilling(c)}>
                              {saving === c.id ? "…" : "Save"}
                            </button>
                          )}
                          {!isDirty && c.plan && c.plan !== "trial" && (
                            <button className="pc-adm-btn-ghost"
                              style={{ fontSize: 11, padding: "4px 10px" }}
                              onClick={() => setGenInvoice(c)}>
                              Generate invoice
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </>
      )}

      {activeTab === "invoices" && (
        <>
          <div className="pc-adm-filters" style={{ marginBottom: 16, display: "flex", gap: 10, alignItems: "center" }}>
            <div style={{ display: "flex", gap: 4 }}>
              {[
                { k: "all", l: "All" },
                { k: "open", l: "Open" },
                { k: "paid", l: "Paid" },
                { k: "void", l: "Void" },
              ].map(f => (
                <button
                  key={f.k}
                  onClick={() => setInvoiceFilter(f.k)}
                  style={{
                    padding: "5px 12px", fontSize: 12, borderRadius: 6, cursor: "pointer",
                    border: "1px solid var(--border)",
                    background: invoiceFilter === f.k ? "var(--accent)" : "transparent",
                    color: invoiceFilter === f.k ? "#fff" : "var(--text-2)",
                    fontWeight: invoiceFilter === f.k ? 600 : 400,
                  }}
                >{f.l}</button>
              ))}
            </div>
            <div style={{ flex: 1 }} />
            <div style={{ fontSize: 12, color: "var(--text-3)" }}>{filteredInvoices.length} invoices</div>
          </div>

          {invoicesLoading ? (
            <div style={{ display: "flex", justifyContent: "center", padding: 40 }}>
              <div style={{ width: 24, height: 24, border: "2px solid var(--border-strong)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "pc-spin 0.7s linear infinite" }} />
            </div>
          ) : filteredInvoices.length === 0 ? (
            <div className="pc-adm-card">
              <div style={{ padding: "40px 24px", textAlign: "center" }}>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 8 }}>No invoices yet</div>
                <div style={{ fontSize: 13, color: "var(--text-2)", maxWidth: 360, margin: "0 auto 20px", lineHeight: 1.6 }}>
                  Invoices are generated per customer per billing period. Go to Customer Plans and click "Generate invoice" on any paying customer.
                </div>
                <button className="pc-adm-btn-primary" style={{ fontSize: 12 }} onClick={() => setActiveTab("overview")}>
                  Go to Customer Plans
                </button>
              </div>
            </div>
          ) : (
            <div className="pc-adm-table-wrap">
              <table className="pc-adm-table">
                <thead>
                  <tr>
                    <th>Invoice #</th>
                    <th>Customer</th>
                    <th>Plan</th>
                    <th>Period</th>
                    <th>Due</th>
                    <th style={{ textAlign: "right" }}>Amount</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredInvoices.map(inv => {
                    const co = companyMap[inv.company_id] || {};
                    const st = statusStyle[inv.status] || statusStyle.open;
                    const isOverdue = inv.status === "open" && inv.due_date && new Date(inv.due_date) < new Date();
                    return (
                      <tr key={inv.id}>
                        <td style={{ paddingLeft: 14 }}>
                          <div style={{ fontFamily: "ui-monospace,monospace", fontSize: 12, fontWeight: 600, color: "var(--accent)" }}>{inv.invoice_number || "—"}</div>
                          <div style={{ fontSize: 10.5, color: "var(--text-4)" }}>{fmtDate(inv.created_at)}</div>
                        </td>
                        <td>
                          <div style={{ fontWeight: 500, fontSize: 13 }}>{co.name || "—"}</div>
                          <div style={{ fontSize: 11, color: "var(--text-3)" }}>{co.subdomain}</div>
                        </td>
                        <td>
                          <span className="pc-adm-badge" style={{ background: "var(--bg-elev-2)", color: "var(--text-2)" }}>
                            {inv.plan_name || inv.plan_slug || "—"}
                          </span>
                        </td>
                        <td style={{ fontSize: 12, color: "var(--text-2)" }}>
                          {inv.period_start ? new Date(inv.period_start).toLocaleDateString("en-US", { month: "short", year: "numeric" }) : "—"}
                        </td>
                        <td style={{ fontSize: 12, color: isOverdue ? "#ef4444" : "var(--text-2)" }}>
                          {fmtDate(inv.due_date)}
                          {isOverdue && <div style={{ fontSize: 10, color: "#ef4444" }}>Overdue</div>}
                        </td>
                        <td style={{ textAlign: "right", fontFamily: "ui-monospace,monospace", fontWeight: 600, fontSize: 13 }}>
                          {fmtMRR(inv.amount_cents)}
                        </td>
                        <td>
                          <span className="pc-adm-badge" style={{ background: st.bg, color: st.color }}>
                            {inv.status[0].toUpperCase() + inv.status.slice(1)}
                          </span>
                        </td>
                        <td>
                          <div style={{ display: "flex", gap: 4 }}>
                            {inv.status === "open" && (
                              <button
                                className="pc-adm-btn-ghost"
                                style={{ fontSize: 11, padding: "3px 8px", color: "#10b981", borderColor: "rgba(16,185,129,0.3)" }}
                                onClick={() => updateInvoiceStatus(inv.id, "paid")}
                              >Mark paid</button>
                            )}
                            {inv.status !== "void" && inv.status !== "paid" && (
                              <button
                                className="pc-adm-btn-ghost"
                                style={{ fontSize: 11, padding: "3px 8px", color: "var(--text-3)" }}
                                onClick={() => voidInvoice(inv.id)}
                              >Void</button>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}

      {/* Generate invoice confirm modal */}
      {genInvoice && (
        <div className="pc-adm-modal-bg" onClick={() => setGenInvoice(null)}>
          <div className="pc-adm-modal" style={{ maxWidth: 420 }} onClick={e => e.stopPropagation()}>
            <div className="pc-adm-modal-header">
              <div className="pc-adm-modal-title">Generate Invoice</div>
              <button className="pc-adm-modal-close" onClick={() => setGenInvoice(null)}>✕</button>
            </div>
            <div style={{ fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.6, marginBottom: 20 }}>
              Generate a monthly invoice for <strong>{genInvoice.name}</strong> on the <strong>{(genInvoice.plan || "trial")[0].toUpperCase() + (genInvoice.plan || "trial").slice(1)}</strong> plan for the current billing period?
            </div>
            <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border)", borderRadius: 8, padding: "12px 14px", marginBottom: 20 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                <span style={{ color: "var(--text-3)" }}>Amount</span>
                <span style={{ fontWeight: 700, color: "var(--accent)" }}>
                  {fmtMRR(planMap[genInvoice.plan]?.price_cents || genInvoice.mrr || 0)}
                </span>
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button className="pc-adm-btn-ghost" onClick={() => setGenInvoice(null)}>Cancel</button>
              <button className="pc-adm-btn-primary" onClick={() => generateInvoice(genInvoice)}>
                Generate invoice
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Integrations & APIs section ──────────────────────────────────────────────

function IntegrationsAPISection({ companies }) {
  const [integrations, setIntegrations] = useAdm(null);
  const [loading, setLoading] = useAdm(true);
  const [activeTab, setActiveTab] = useAdm("integrations");
  const [copied, setCopied] = useAdm(null);
  const [syncingId, setSyncingId] = useAdm(null);
  const [toast, showToast] = useAdminToast();

  useAdmEffect(() => {
    loadIntegrations();
  }, []);

  async function loadIntegrations() {
    setLoading(true);
    try {
      const db = window.supabaseClient;
      const { data } = await db
        .from("integrations")
        .select("id,company_id,provider,status,last_sync_at,connected_at,error_message,scope")
        .order("connected_at", { ascending: false });

      const companyById = {};
      companies.forEach(c => { companyById[c.id] = c; });

      setIntegrations((data || []).map(i => ({
        ...i,
        company_name: companyById[i.company_id]?.name || "Unknown",
        subdomain: companyById[i.company_id]?.subdomain || "",
      })));
    } catch (_) { setIntegrations([]); }
    finally { setLoading(false); }
  }

  const PROVIDER_LABELS = {
    qbo: "QuickBooks Online",
    quickbooks: "QuickBooks Online",
    xero: "Xero",
    netsuite: "NetSuite",
    sage: "Sage Intacct",
    shopify: "Shopify",
    stripe: "Stripe",
    hubspot: "HubSpot",
    wave: "Wave",
    freshbooks: "FreshBooks",
  };

  const PROVIDER_ICONS = {
    qbo: "🟢", quickbooks: "🟢", xero: "🔵", netsuite: "🟠",
    sage: "🟣", shopify: "🟡", stripe: "🔷", hubspot: "🟧",
    wave: "🌊", freshbooks: "📗",
  };

  const SYNCABLE = ["shopify", "stripe"];

  const statusCounts = integrations ? {
    connected: integrations.filter(i => i.status === "connected" || i.status === "active").length,
    error: integrations.filter(i => i.status === "error").length,
    pending: integrations.filter(i => i.status === "pending" || i.status === "disconnected").length,
  } : { connected: 0, error: 0, pending: 0 };

  async function copyText(text, key) {
    try { await navigator.clipboard.writeText(text); setCopied(key); setTimeout(() => setCopied(null), 2000); } catch {}
  }

  async function handleAdminSync(integration) {
    const syncFns = { shopify: "sync-shopify", stripe: "sync-stripe" };
    const fnSlug = syncFns[integration.provider];
    if (!fnSlug) {
      showToast(`No direct sync available for ${integration.provider} — syncs via scheduled job.`, "info");
      return;
    }
    setSyncingId(integration.id);
    try {
      const db = window.supabaseClient;
      const { data: { session } } = await db.auth.getSession();
      const res = await fetch(`${window.SUPABASE_URL}/functions/v1/${fnSlug}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${session?.access_token}`,
          "Apikey": window.SUPABASE_ANON_KEY,
        },
        body: JSON.stringify({ companyId: integration.company_id }),
      });
      const result = await res.json();
      if (!res.ok) throw new Error(result.error || "Sync failed");
      const parts = [];
      if (result.ordersCreated) parts.push(`${result.ordersCreated} orders`);
      if (result.productsUpserted) parts.push(`${result.productsUpserted} products`);
      if (result.subscriptionsUpserted) parts.push(`${result.subscriptionsUpserted} subscriptions`);
      if (result.customersUpserted) parts.push(`${result.customersUpserted} customers`);
      showToast(`Synced ${integration.company_name}${parts.length ? ": " + parts.join(", ") : ""}`, "success");
      loadIntegrations();
    } catch (err) {
      showToast(err.message || "Sync failed", "error");
    } finally {
      setSyncingId(null);
    }
  }

  const supabaseUrl = window.SUPABASE_URL || "";
  const anonKey = window.SUPABASE_ANON_KEY || "";
  const functionsBase = `${supabaseUrl}/functions/v1`;

  const WEBHOOK_EVENTS = [
    { event: "company.created", description: "Fired when a new customer is onboarded" },
    { event: "company.updated", description: "Fired when company profile or plan changes" },
    { event: "company.suspended", description: "Fired when a customer is suspended" },
    { event: "user.invited", description: "Fired when a new user is invited" },
    { event: "user.role_changed", description: "Fired when a user's role is modified" },
    { event: "integration.connected", description: "Fired when a GL integration is connected" },
    { event: "integration.error", description: "Fired when an integration sync fails" },
  ];

  const API_ENDPOINTS = [
    { method: "POST", path: "/admin-actions/invite", description: "Create & invite a new customer company" },
    { method: "POST", path: "/admin-actions/update-company", description: "Update company profile, plan, or MRR" },
    { method: "GET",  path: "/admin-actions/company-users", description: "List all users for a company" },
    { method: "POST", path: "/admin-actions/add-user", description: "Invite a user to a company" },
    { method: "POST", path: "/admin-actions/update-user", description: "Change a user's role" },
    { method: "DELETE", path: "/admin-actions/remove-user", description: "Remove a user from a company" },
    { method: "GET",  path: "/admin-actions/audit-log", description: "Retrieve audit events" },
    { method: "GET",  path: "/admin-actions/list-users", description: "List all platform users (auth)" },
    { method: "POST", path: "/admin-actions/suspend", description: "Suspend a customer account" },
    { method: "DELETE", path: "/admin-actions/delete", description: "Permanently delete a company" },
    { method: "POST", path: "/admin-actions/set-password", description: "Reset a user's password" },
    { method: "POST", path: "/admin-actions/generate-invoices", description: "Bulk-generate monthly invoices for active customers" },
    { method: "POST", path: "/admin-actions/update-invoice", description: "Update invoice status (open → paid / void)" },
    { method: "POST", path: "/admin-actions/update-settings", description: "Update platform settings key-value pairs" },
    { method: "POST", path: "/sync-shopify", description: "Sync Shopify orders, products & customers for a company" },
    { method: "POST", path: "/sync-stripe", description: "Sync Stripe subscriptions, MRR events & charges for a company" },
    { method: "POST", path: "/oauth-connect/initiate", description: "Initiate OAuth flow for QBO, Xero, Stripe, HubSpot" },
    { method: "POST", path: "/oauth-connect/shopify", description: "Initiate Shopify OAuth flow (requires shop domain)" },
    { method: "GET",  path: "/oauth-connect/callback", description: "OAuth redirect callback (handled by provider)" },
  ];

  const METHOD_COLORS = { GET: "#10b981", POST: "#2563eb", DELETE: "#ef4444", PUT: "#d97706" };

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Integrations & APIs</h2>
      </div>

      <div className="pc-adm-drawer-tabs" style={{ background: "none", padding: 0, marginBottom: 20 }}>
        {[["integrations","Customer Integrations"],["api","API Reference"],["webhooks","Webhook Events"]].map(([v,l]) => (
          <button key={v} className={`pc-adm-drawer-tab${activeTab === v ? " active" : ""}`} onClick={() => setActiveTab(v)}>{l}</button>
        ))}
      </div>

      {activeTab === "integrations" && (
        <>
          <div className="pc-adm-kpi-row" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 20 }}>
            <KpiCard label="Connected" value={statusCounts.connected} accent="#10b981" sub="Active GL integrations" />
            <KpiCard label="Errors" value={statusCounts.error} accent={statusCounts.error > 0 ? "#ef4444" : undefined} sub="Need attention" />
            <KpiCard label="Total Integrations" value={integrations?.length || 0} sub="Across all companies" />
          </div>

          {loading && <div className="pc-adm-loading">Loading integrations…</div>}
          {!loading && integrations?.length === 0 && (
            <div className="pc-adm-empty">No integrations connected yet. Customers connect their GL from their dashboard settings.</div>
          )}
          {!loading && integrations && integrations.length > 0 && (
            <div className="pc-adm-table-wrap">
              <table className="pc-adm-table">
                <thead>
                  <tr><th>Customer</th><th>Provider</th><th>Status</th><th>Last Sync</th><th>Connected</th><th>Actions</th></tr>
                </thead>
                <tbody>
                  {integrations.map(i => {
                    const canSync = SYNCABLE.includes(i.provider) && (i.status === "active" || i.status === "connected");
                    return (
                    <tr key={i.id}>
                      <td style={{ paddingLeft: 14 }}>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{i.company_name}</div>
                        <div style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "ui-monospace,monospace" }}>{i.subdomain}</div>
                      </td>
                      <td>
                        <span style={{ fontSize: 13 }}>{PROVIDER_ICONS[i.provider] || "🔌"} {PROVIDER_LABELS[i.provider] || i.provider}</span>
                      </td>
                      <td>
                        <span className="pc-adm-badge" style={{
                          background: i.status === "connected" || i.status === "active" ? "rgba(16,185,129,0.12)" :
                                      i.status === "error" ? "rgba(239,68,68,0.12)" : "rgba(251,191,36,0.12)",
                          color: i.status === "connected" || i.status === "active" ? "#10b981" :
                                 i.status === "error" ? "#ef4444" : "#d97706",
                        }}>
                          {i.status || "unknown"}
                        </span>
                      </td>
                      <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtRelative(i.last_sync_at)}</td>
                      <td style={{ fontSize: 12, color: "var(--text-3)" }}>{fmtDate(i.connected_at)}</td>
                      <td>
                        {canSync && (
                          <button
                            className="pc-adm-btn"
                            style={{ padding: "4px 10px", fontSize: 11.5 }}
                            disabled={syncingId === i.id}
                            onClick={() => handleAdminSync(i)}
                          >
                            {syncingId === i.id ? "Syncing…" : "Sync now"}
                          </button>
                        )}
                        {!canSync && <span style={{ fontSize: 11, color: "var(--text-4)" }}>—</span>}
                      </td>
                    </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}

      {activeTab === "api" && (
        <div>
          <div className="pc-adm-card" style={{ marginBottom: 16 }}>
            <div className="pc-adm-card-header">
              <div className="pc-adm-card-title">Connection Details</div>
            </div>
            <div style={{ padding: "12px 0" }}>
              {[
                { label: "Supabase URL", value: supabaseUrl, key: "url" },
                { label: "Anon Key (public)", value: anonKey ? anonKey.slice(0, 40) + "…" : "—", full: anonKey, key: "anon" },
                { label: "Functions Base URL", value: functionsBase, key: "fnbase" },
                { label: "Auth", value: "Bearer <access_token> in Authorization header", key: "auth" },
              ].map(row => (
                <div key={row.key} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 18px", borderBottom: "1px solid var(--border)" }}>
                  <div style={{ width: 160, flexShrink: 0, fontSize: 12, color: "var(--text-3)", fontWeight: 600 }}>{row.label}</div>
                  <code style={{ flex: 1, fontSize: 11.5, color: "var(--text)", fontFamily: "ui-monospace,monospace", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {row.value}
                  </code>
                  {(row.full || row.value !== "—") && (
                    <button onClick={() => copyText(row.full || row.value, row.key)}
                      style={{ background: "none", border: "1px solid var(--border-strong)", borderRadius: 5, padding: "3px 8px", cursor: "pointer", fontSize: 11, color: copied === row.key ? "#10b981" : "var(--text-3)", transition: "color 0.2s", flexShrink: 0 }}>
                      {copied === row.key ? "Copied!" : "Copy"}
                    </button>
                  )}
                </div>
              ))}
            </div>
          </div>

          <div className="pc-adm-card">
            <div className="pc-adm-card-header">
              <div className="pc-adm-card-title">Admin API Endpoints</div>
              <div style={{ fontSize: 11, color: "var(--text-3)" }}>All require super_admin JWT</div>
            </div>
            <div>
              {API_ENDPOINTS.map((ep, i) => (
                <div key={i} style={{
                  display: "flex", alignItems: "center", gap: 12, padding: "10px 18px",
                  borderBottom: i < API_ENDPOINTS.length - 1 ? "1px solid var(--border)" : "none",
                }}>
                  <span style={{
                    width: 52, flexShrink: 0, fontSize: 10.5, fontWeight: 700, textAlign: "center",
                    padding: "2px 4px", borderRadius: 4, background: `${METHOD_COLORS[ep.method]}20`,
                    color: METHOD_COLORS[ep.method],
                  }}>{ep.method}</span>
                  <code style={{ width: 280, flexShrink: 0, fontSize: 11.5, fontFamily: "ui-monospace,monospace", color: "var(--text-2)" }}>
                    {functionsBase}{ep.path}
                  </code>
                  <div style={{ flex: 1, fontSize: 12, color: "var(--text-3)" }}>{ep.description}</div>
                  <button onClick={() => copyText(`${functionsBase}${ep.path}`, `ep-${i}`)}
                    style={{ background: "none", border: "1px solid var(--border-strong)", borderRadius: 5, padding: "3px 8px", cursor: "pointer", fontSize: 11, color: copied === `ep-${i}` ? "#10b981" : "var(--text-3)", flexShrink: 0 }}>
                    {copied === `ep-${i}` ? "Copied!" : "Copy URL"}
                  </button>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {activeTab === "webhooks" && (
        <div>
          <div className="pc-adm-card" style={{ marginBottom: 16 }}>
            <div className="pc-adm-card-header">
              <div className="pc-adm-card-title">Webhook Events Reference</div>
              <div style={{ fontSize: 11, color: "var(--text-3)" }}>Events emitted to the audit_log table</div>
            </div>
            <div>
              {WEBHOOK_EVENTS.map((ev, i) => (
                <div key={i} style={{
                  display: "flex", alignItems: "center", gap: 14, padding: "11px 18px",
                  borderBottom: i < WEBHOOK_EVENTS.length - 1 ? "1px solid var(--border)" : "none",
                }}>
                  <code style={{ width: 200, flexShrink: 0, fontSize: 12, fontFamily: "ui-monospace,monospace", color: "var(--accent)", background: "rgba(16,185,129,0.07)", padding: "2px 8px", borderRadius: 5 }}>
                    {ev.event}
                  </code>
                  <div style={{ flex: 1, fontSize: 13, color: "var(--text-2)" }}>{ev.description}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="pc-adm-card">
            <div className="pc-adm-card-header">
              <div className="pc-adm-card-title">Supabase Realtime / Webhook Setup</div>
            </div>
            <div style={{ padding: "18px 18px", fontSize: 13, color: "var(--text-2)", lineHeight: 1.7 }}>
              <p style={{ marginBottom: 12 }}>To subscribe to audit events externally, use Supabase's built-in webhook or Realtime features:</p>
              <div style={{ background: "var(--bg-elev-2)", borderRadius: 8, padding: "12px 14px", fontFamily: "ui-monospace,monospace", fontSize: 11.5, color: "var(--text)", marginBottom: 12 }}>
                <div style={{ color: "var(--text-3)", marginBottom: 6 }}>// Subscribe to audit_log inserts (Supabase Realtime)</div>
                <div>{"supabase"}</div>
                <div>{"  .channel('audit-events')"}</div>
                <div>{"  .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'audit_log' },"}</div>
                <div>{"    (payload) => console.log(payload))"}</div>
                <div>{"  .subscribe();"}</div>
              </div>
              <p style={{ fontSize: 12, color: "var(--text-3)" }}>
                Database webhooks can also be configured in the Supabase dashboard under Database → Webhooks to forward events to any HTTP endpoint.
              </p>
            </div>
          </div>
        </div>
      )}

      {toast && <AdminToast msg={toast.msg} type={toast.type} />}
    </div>
  );
}

// ─── Onboard section ──────────────────────────────────────────────────────────

function OnboardSection({ onStartWizard }) {
  const STEPS = [
    { n: 1, title: "Choose Business Model", desc: "Select the customer's primary business model — this drives which KPIs, ratios, and modules are active on their dashboard." },
    { n: 2, title: "Company Profile", desc: "Enter company name, subdomain, entity type, revenue band, employee count, plan tier, and contact details." },
    { n: 3, title: "Invite Owner", desc: "Provide the owner's name and email. They'll receive a personalised invite email with a one-click activation link." },
    { n: 4, title: "Review & Create", desc: "Confirm all details and create the account. The system creates the company record, sets up RLS, and dispatches the invite." },
  ];

  const CHECKLIST = [
    { item: "Business model selected (drives dashboard modules)", done: false },
    { item: "Company name and unique subdomain confirmed", done: false },
    { item: "Plan tier agreed (Trial / Starter / Growth / Pro / Enterprise)", done: false },
    { item: "Owner name and email address provided", done: false },
    { item: "Owner briefed to expect an invite email", done: false },
    { item: "GL integration credentials ready (optional, can do later)", done: false },
  ];

  return (
    <div className="pc-adm-section">
      <div className="pc-adm-section-header">
        <h2 className="pc-adm-section-title">Onboard a Customer</h2>
        <button className="pc-adm-btn-primary" style={{ fontSize: 13, padding: "10px 20px" }} onClick={onStartWizard}>
          Start Onboarding Wizard →
        </button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
        {/* Process steps */}
        <div className="pc-adm-card">
          <div className="pc-adm-card-header">
            <div className="pc-adm-card-title">Onboarding Process</div>
            <div style={{ fontSize: 11, color: "var(--text-3)" }}>4-step wizard</div>
          </div>
          <div style={{ padding: "8px 0" }}>
            {STEPS.map((s, i) => (
              <div key={s.n} style={{
                display: "flex", gap: 14, padding: "14px 18px",
                borderBottom: i < STEPS.length - 1 ? "1px solid var(--border)" : "none",
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: "50%", flexShrink: 0, marginTop: 1,
                  background: "rgba(16,185,129,0.12)", color: "#10b981",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, fontWeight: 700,
                }}>{s.n}</div>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 3 }}>{s.title}</div>
                  <div style={{ fontSize: 12, color: "var(--text-3)", lineHeight: 1.5 }}>{s.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Pre-onboarding checklist */}
        <div>
          <div className="pc-adm-card" style={{ marginBottom: 16 }}>
            <div className="pc-adm-card-header">
              <div className="pc-adm-card-title">Pre-Onboarding Checklist</div>
            </div>
            <div style={{ padding: "8px 0" }}>
              {CHECKLIST.map((item, i) => (
                <div key={i} style={{
                  display: "flex", alignItems: "flex-start", gap: 10, padding: "10px 18px",
                  borderBottom: i < CHECKLIST.length - 1 ? "1px solid var(--border)" : "none",
                }}>
                  <div style={{
                    width: 16, height: 16, borderRadius: 4, flexShrink: 0, marginTop: 1,
                    border: "2px solid var(--border-strong)", background: "var(--bg-elev-2)",
                  }} />
                  <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.4 }}>{item.item}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="pc-adm-card">
            <div className="pc-adm-card-header">
              <div className="pc-adm-card-title">After Onboarding</div>
            </div>
            <div style={{ padding: "14px 18px", display: "flex", flexDirection: "column", gap: 10 }}>
              {[
                "Customer receives invite email with activation link",
                "They set their password and are directed to their dashboard",
                "Their account starts in Trial — upgrade plan in Billing section",
                "Customer connects their GL integration from Settings",
                "Data syncs automatically once connected",
              ].map((s, i) => (
                <div key={i} style={{ display: "flex", gap: 10, fontSize: 12.5, color: "var(--text-2)", alignItems: "flex-start" }}>
                  <div style={{ width: 18, height: 18, borderRadius: "50%", flexShrink: 0, background: "rgba(16,185,129,0.12)", color: "#10b981", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 700, marginTop: 1 }}>{i + 1}</div>
                  {s}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Main AdminPage ───────────────────────────────────────────────────────────

function AdminPage({ isSuperAdmin, onViewCompany, onLogout }) {
  const [section, setSection] = useAdm("dashboard");
  const [companies, setCompanies] = useAdm([]);
  const [allUsers, setAllUsers] = useAdm([]);
  const [loading, setLoading] = useAdm(true);
  const [showNew, setShowNew] = useAdm(false);
  const [showQuickInvite, setShowQuickInvite] = useAdm(false);
  const [adminEmail, setAdminEmail] = useAdm("");
  const [plans, setPlans] = useAdm([]);

  useAdmEffect(() => {
    const db = window.supabaseClient;
    if (!db) return;
    (async () => {
      const { data: { session } } = await db.auth.getSession();
      if (session?.user) setAdminEmail(session.user.email || "");
    })();
  }, []);

  const loadData = useAdmCb(async () => {
    setLoading(true);
    try {
      const db = window.supabaseClient;

      const [{ data: cos }, { data: cuRows }, { data: intRows }, { data: authUsersData }] = await Promise.all([
        db.from("companies")
          .select("id,name,subdomain,plan,status,mrr,created_at,business_model,business_type,company_type,industry,owner_name,revenue_band,employee_count,notes,phone,website,timezone,fiscal_year_end")
          .order("created_at", { ascending: false }),
        db.from("company_users").select("company_id,user_id,role,status,joined_at"),
        db.from("integrations").select("company_id,last_sync_at"),
        // Use admin edge function to get auth user data with last_sign_in
        callAdmin("list-users", "GET").catch(() => ({ users: [] })),
      ]);

      const userCounts = {};
      (cuRows || []).forEach(r => { userCounts[r.company_id] = (userCounts[r.company_id] || 0) + 1; });

      const lastSyncs = {};
      (intRows || []).forEach(r => {
        if (!r.last_sync_at) return;
        if (!lastSyncs[r.company_id] || r.last_sync_at > lastSyncs[r.company_id]) lastSyncs[r.company_id] = r.last_sync_at;
      });

      const cosWithCounts = (cos || []).map(c => ({ ...c, userCount: userCounts[c.id] || 0, lastSync: lastSyncs[c.id] || null }));
      setCompanies(cosWithCounts);

      // Build enriched user list from company_users + auth data
      const authUsers = (authUsersData?.users || []);
      const authByEmail = {};
      authUsers.forEach(u => { authByEmail[u.email] = u; });

      const companyById = {};
      cosWithCounts.forEach(c => { companyById[c.id] = c; });

      const enrichedUsers = (cuRows || []).map(cu => {
        const au = authUsers.find(u => u.id === cu.user_id) || {};
        const co = companyById[cu.company_id] || {};
        return {
          id: cu.user_id,
          email: au.email || cu.user_id,
          name: au.user_metadata?.full_name || au.user_metadata?.name || "",
          last_sign_in_at: au.last_sign_in_at,
          created_at: au.created_at,
          company_id: cu.company_id,
          company_name: co.name,
          subdomain: co.subdomain,
          role: cu.role,
          cu_status: cu.status,
          joined_at: cu.joined_at,
        };
      });
      setAllUsers(enrichedUsers);
    } catch (err) {
      console.error("[admin] loadData error", err);
    } finally {
      setLoading(false);
    }
  }, []);

  useAdmEffect(() => { loadData(); }, [loadData]);

  useAdmEffect(() => {
    const db = window.supabaseClient;
    if (!db) return;
    db.from("pricing_plans").select("id,name,slug,price_cents,is_active").order("sort_order").then(({ data }) => {
      setPlans(data || []);
    });
  }, []);

  function handleViewDashboard(company) {
    if (onViewCompany) { onViewCompany(company.id, company); return; }
    const base = window.location.hostname === "localhost"
      ? `http://localhost:${window.location.port}`
      : `https://project-ivigd.vercel.app`;
    window.open(`${base}/?subdomain=${company.subdomain}`, "_blank");
  }

  async function handleLogout() {
    const db = window.supabaseClient;
    if (db) await db.auth.signOut();
    if (onLogout) onLogout();
    else window.location.reload();
  }

  return (
    <div className="pc-adm-shell">
      <AdminSidebar
        activeSection={section}
        onNav={setSection}
        adminEmail={adminEmail}
        onLogout={handleLogout}
        companies={companies}
        onViewCompany={(id, co) => { if (onViewCompany) onViewCompany(id, co); }}
        onQuickInvite={() => setShowQuickInvite(true)}
      />

      <div className="pc-adm-main">
        {loading && !["audit","settings","integrations","onboard","documents"].includes(section) ? (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 400 }}>
            <div style={{ width: 28, height: 28, border: "2px solid var(--border-strong)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "pc-spin 0.7s linear infinite" }} />
          </div>
        ) : (
          <>
            {section === "dashboard"    && <DashboardSection companies={companies} allUsers={allUsers} />}
            {section === "analytics"    && <AnalyticsSection companies={companies} allUsers={allUsers} />}
            {section === "billing"      && <BillingSection companies={companies} setCompanies={setCompanies} />}
            {section === "pricing"      && <PricingPlansSection />}
            {section === "customers"    && (
              <CustomersSection
                companies={companies}
                setCompanies={setCompanies}
                onViewDashboard={handleViewDashboard}
                onNewCustomer={() => setShowNew(true)}
              />
            )}
            {section === "users"        && <UsersSection allUsers={allUsers} companies={companies} onRefresh={loadData} />}
            {section === "onboard"      && <OnboardSection onStartWizard={() => setShowNew(true)} />}
            {section === "documents"     && <DocumentsSection companies={companies} />}
            {section === "integrations" && <IntegrationsAPISection companies={companies} />}
            {section === "audit"        && <AuditLogSection />}
            {section === "settings"     && <SettingsSection adminEmail={adminEmail} />}
          </>
        )}
      </div>

      {showNew && (
        <NewCustomerWizard
          onClose={() => setShowNew(false)}
          onCreated={(co) => {
            setCompanies(prev => [{ ...co, userCount: 1, lastSync: null }, ...prev]);
            setSection("customers");
          }}
        />
      )}

      {showQuickInvite && (
        <QuickInviteModal
          plans={plans}
          onClose={() => setShowQuickInvite(false)}
          onCreated={(co) => {
            setCompanies(prev => [{ ...co, userCount: 1, lastSync: null }, ...prev]);
          }}
        />
      )}
    </div>
  );
}
