// AdminKpiLibrary
//
// Super-admin console for the KPI library + industry profiles (tables from
// migrations 48/49/50). Two-panel layout:
//   • Left  — navigation tree grouped by archetype, expandable to its industries.
//   • Right — tabs: "KPIs" (kpi_library rows for the selection) and
//             "Industry Profile" (the industry_profiles row for archetype+industry).
// Both tabs have full edit forms covering every column. Writes go directly through
// the authenticated super-admin session (RLS policies added in migration 51).
//
// Self-contained IIFE exposing window.AdminKpiLibrary; loaded via <script
// type="text/babel"> before page-admin.jsx. Uses the global pc-adm-* CSS classes
// and theme vars for visual consistency with the rest of the admin console.

(function () {
  const { useState, useEffect, useMemo } = React;

  const ARCHETYPES = [
    { slug: "retail",        label: "Retail" },
    { slug: "distribution",  label: "Distribution / Wholesale" },
    { slug: "manufacturing", label: "Manufacturing" },
    { slug: "saas",          label: "SaaS / Software" },
    { slug: "services",      label: "Professional Services" },
    { slug: "ecommerce",     label: "E-commerce" },
    { slug: "clinic",        label: "Medical / Healthcare" },
    { slug: "nonprofit",     label: "Nonprofit" },
  ];
  const ARCHE_LABEL = ARCHETYPES.reduce((m, a) => { m[a.slug] = a.label; return m; }, {});

  const UNITS = ["percent", "currency", "days", "ratio", "count"];
  const DIRECTIONS = ["higher_is_better", "lower_is_better", "context_dependent"];
  const DIR_LABEL = { higher_is_better: "Higher is better", lower_is_better: "Lower is better", context_dependent: "Context-dependent" };

  // ── tiny form atoms (theme-aware, match admin console) ──────────────────────
  function Field({ label, hint, children }) {
    return (
      <label style={{ display: "block", marginBottom: 12 }}>
        <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-2)", marginBottom: 5 }}>{label}</div>
        {children}
        {hint ? <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 4 }}>{hint}</div> : null}
      </label>
    );
  }
  const inputStyle = {
    width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 13,
    background: "var(--bg-elev-1, #11161f)", color: "var(--text, #e6edf3)",
    border: "1px solid var(--border-strong, #2a3340)", borderRadius: 7, outline: "none",
  };
  function TextInput({ value, onChange, placeholder, mono }) {
    return <input style={{ ...inputStyle, fontFamily: mono ? "monospace" : "inherit" }} value={value ?? ""} placeholder={placeholder || ""} onChange={(e) => onChange(e.target.value)} />;
  }
  function NumberInput({ value, onChange, placeholder, step }) {
    return <input type="number" step={step || "any"} style={inputStyle} value={value ?? ""} placeholder={placeholder || ""} onChange={(e) => onChange(e.target.value === "" ? null : Number(e.target.value))} />;
  }
  function TextArea({ value, onChange, rows, placeholder, mono }) {
    return <textarea rows={rows || 3} style={{ ...inputStyle, resize: "vertical", fontFamily: mono ? "monospace" : "inherit", lineHeight: 1.5 }} value={value ?? ""} placeholder={placeholder || ""} onChange={(e) => onChange(e.target.value)} />;
  }
  function Select({ value, onChange, options, render }) {
    return (
      <select style={inputStyle} value={value} onChange={(e) => onChange(e.target.value)}>
        {options.map((o) => <option key={o} value={o}>{render ? render(o) : o}</option>)}
      </select>
    );
  }
  function Toggle({ value, onChange, label }) {
    return (
      <button type="button" onClick={() => onChange(!value)} style={{
        display: "inline-flex", alignItems: "center", gap: 8, background: "transparent",
        border: "none", cursor: "pointer", padding: 0, color: "var(--text, #e6edf3)", fontSize: 13,
      }}>
        <span style={{
          width: 36, height: 20, borderRadius: 999, flex: "0 0 auto", position: "relative",
          background: value ? "#10b981" : "var(--border-strong, #2a3340)", transition: "background .15s",
        }}>
          <span style={{ position: "absolute", top: 2, left: value ? 18 : 2, width: 16, height: 16, borderRadius: "50%", background: "#fff", transition: "left .15s" }} />
        </span>
        {label}
      </button>
    );
  }
  function Modal({ title, onClose, children, footer, wide }) {
    return (
      <div className="pc-adm-modal-bg" onClick={onClose}>
        <div className="pc-adm-modal" style={{ maxWidth: wide ? 760 : 620, maxHeight: "92vh", overflowY: "auto" }} onClick={(e) => e.stopPropagation()}>
          <div className="pc-adm-modal-header">
            <div className="pc-adm-modal-title">{title}</div>
            <button className="pc-adm-modal-close" onClick={onClose}>✕</button>
          </div>
          {children}
          {footer ? <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 18 }}>{footer}</div> : null}
        </div>
      </div>
    );
  }

  const linesToArray = (s) => String(s || "").split("\n").map((x) => x.trim()).filter(Boolean);
  const arrayToLines = (a) => (Array.isArray(a) ? a.join("\n") : "");
  const csvToArray = (s) => String(s || "").split(",").map((x) => x.trim()).filter(Boolean);
  const arrayToCsv = (a) => (Array.isArray(a) ? a.join(", ") : "");

  // ── KPI editor ──────────────────────────────────────────────────────────────
  function KpiEditor({ row, onClose, onSaved, onError }) {
    const isNew = !row.id;
    const [f, setF] = useState({
      kpi_name: row.kpi_name || "", kpi_key: row.kpi_key || "", archetype: row.archetype || "retail",
      industry: row.industry || "", description: row.description || "", why_it_matters: row.why_it_matters || "",
      how_computed: row.how_computed || "", unit: row.unit || "percent", direction: row.direction || "higher_is_better",
      is_default: !!row.is_default, display_order: row.display_order ?? 0,
      benchmark_p25: row.benchmark_p25 ?? null, benchmark_p50: row.benchmark_p50 ?? null, benchmark_p75: row.benchmark_p75 ?? null,
      benchmark_source: row.benchmark_source || "", alert_threshold_pct: row.alert_threshold_pct ?? null,
      tags: arrayToCsv(row.tags), active: row.active !== false,
    });
    const [saving, setSaving] = useState(false);
    const set = (k, v) => setF((prev) => ({ ...prev, [k]: v }));

    const save = async () => {
      if (!f.kpi_name.trim()) { onError("KPI name is required."); return; }
      if (!f.kpi_key.trim()) { onError("KPI key is required."); return; }
      if (!f.description.trim() || !f.why_it_matters.trim() || !f.how_computed.trim()) { onError("Description, why-it-matters and how-computed are all required."); return; }
      setSaving(true);
      const db = window.supabaseClient;
      const payload = {
        archetype: f.archetype, industry: f.industry.trim() || null, kpi_key: f.kpi_key.trim(),
        kpi_name: f.kpi_name.trim(), description: f.description.trim(), why_it_matters: f.why_it_matters.trim(),
        how_computed: f.how_computed.trim(), unit: f.unit, direction: f.direction, is_default: f.is_default,
        display_order: Number(f.display_order) || 0, benchmark_p25: f.benchmark_p25, benchmark_p50: f.benchmark_p50,
        benchmark_p75: f.benchmark_p75, benchmark_source: f.benchmark_source.trim() || null,
        alert_threshold_pct: f.alert_threshold_pct, tags: csvToArray(f.tags), active: f.active,
        updated_at: new Date().toISOString(),
      };
      try {
        if (isNew) {
          const { error } = await db.from("kpi_library").insert(payload);
          if (error) throw error;
        } else {
          const { error } = await db.from("kpi_library").update(payload).eq("id", row.id);
          if (error) throw error;
        }
        onSaved();
      } catch (e) {
        setSaving(false);
        onError(e.message || "Save failed — check that you have super-admin rights.");
      }
    };

    return (
      <Modal wide title={isNew ? "New KPI" : `Edit KPI — ${row.kpi_name}`} onClose={onClose}
        footer={<>
          <button className="pc-adm-btn-ghost" onClick={onClose}>Cancel</button>
          <button className="pc-adm-btn-primary" disabled={saving} onClick={save}>{saving ? "Saving…" : "Save KPI"}</button>
        </>}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="KPI name"><TextInput value={f.kpi_name} onChange={(v) => set("kpi_name", v)} placeholder="Gross Margin %" /></Field>
          <Field label="KPI key" hint="machine key, snake_case"><TextInput mono value={f.kpi_key} onChange={(v) => set("kpi_key", v)} placeholder="gross_margin_pct" /></Field>
          <Field label="Archetype">
            <Select value={f.archetype} onChange={(v) => set("archetype", v)} options={ARCHETYPES.map((a) => a.slug)} render={(s) => ARCHE_LABEL[s] || s} />
          </Field>
          <Field label="Industry" hint="blank = applies to all industries in the archetype"><TextInput value={f.industry} onChange={(v) => set("industry", v)} placeholder="(all industries)" /></Field>
        </div>
        <Field label="Description — what it measures"><TextArea rows={2} value={f.description} onChange={(v) => set("description", v)} /></Field>
        <Field label="Why it matters — why the owner should care"><TextArea rows={2} value={f.why_it_matters} onChange={(v) => set("why_it_matters", v)} /></Field>
        <Field label="How computed — formula description"><TextInput value={f.how_computed} onChange={(v) => set("how_computed", v)} placeholder="Gross Profit / Revenue" /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <Field label="Unit"><Select value={f.unit} onChange={(v) => set("unit", v)} options={UNITS} /></Field>
          <Field label="Direction"><Select value={f.direction} onChange={(v) => set("direction", v)} options={DIRECTIONS} render={(d) => DIR_LABEL[d]} /></Field>
          <Field label="Display order"><NumberInput value={f.display_order} onChange={(v) => set("display_order", v ?? 0)} /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <Field label="Benchmark p25"><NumberInput value={f.benchmark_p25} onChange={(v) => set("benchmark_p25", v)} /></Field>
          <Field label="Benchmark p50 (median)"><NumberInput value={f.benchmark_p50} onChange={(v) => set("benchmark_p50", v)} /></Field>
          <Field label="Benchmark p75"><NumberInput value={f.benchmark_p75} onChange={(v) => set("benchmark_p75", v)} /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <Field label="Benchmark source"><TextInput value={f.benchmark_source} onChange={(v) => set("benchmark_source", v)} placeholder="Dun & Bradstreet 2024 / Perdura baseline" /></Field>
          <Field label="Alert threshold %" hint="% change that triggers an exception"><NumberInput value={f.alert_threshold_pct} onChange={(v) => set("alert_threshold_pct", v)} /></Field>
        </div>
        <Field label="Tags" hint="comma-separated, e.g. margin, profitability, cash"><TextInput value={f.tags} onChange={(v) => set("tags", v)} /></Field>
        <div style={{ display: "flex", gap: 24, marginTop: 4 }}>
          <Toggle value={f.is_default} onChange={(v) => set("is_default", v)} label="Pre-selected in wizard (default)" />
          <Toggle value={f.active} onChange={(v) => set("active", v)} label="Active" />
        </div>
      </Modal>
    );
  }

  // ── Industry profile editor ──────────────────────────────────────────────────
  function ProfileEditor({ row, archetype, industry, onClose, onSaved, onError }) {
    const isNew = !row || !row.id;
    const r = row || {};
    const [f, setF] = useState({
      display_name: r.display_name || industry || "", description: r.description || "",
      typical_revenue_model: r.typical_revenue_model || "", typical_cost_structure: r.typical_cost_structure || "",
      key_risks: arrayToLines(r.key_risks), key_opportunities: arrayToLines(r.key_opportunities),
      seasonal_notes: r.seasonal_notes || "", notes: r.notes || "", active: r.active !== false,
    });
    const [saving, setSaving] = useState(false);
    const set = (k, v) => setF((prev) => ({ ...prev, [k]: v }));

    const save = async () => {
      if (!f.display_name.trim()) { onError("Display name is required."); return; }
      setSaving(true);
      const db = window.supabaseClient;
      const payload = {
        archetype, industry, display_name: f.display_name.trim(), description: f.description.trim() || null,
        typical_revenue_model: f.typical_revenue_model.trim() || null, typical_cost_structure: f.typical_cost_structure.trim() || null,
        key_risks: linesToArray(f.key_risks), key_opportunities: linesToArray(f.key_opportunities),
        seasonal_notes: f.seasonal_notes.trim() || null, notes: f.notes.trim() || null, active: f.active,
      };
      try {
        if (isNew) {
          const { error } = await db.from("industry_profiles").insert(payload);
          if (error) throw error;
        } else {
          const { error } = await db.from("industry_profiles").update(payload).eq("id", r.id);
          if (error) throw error;
        }
        onSaved();
      } catch (e) {
        setSaving(false);
        onError(e.message || "Save failed — check that you have super-admin rights.");
      }
    };

    return (
      <Modal wide title={`${isNew ? "New" : "Edit"} profile — ${ARCHE_LABEL[archetype] || archetype} · ${industry}`} onClose={onClose}
        footer={<>
          <button className="pc-adm-btn-ghost" onClick={onClose}>Cancel</button>
          <button className="pc-adm-btn-primary" disabled={saving} onClick={save}>{saving ? "Saving…" : "Save profile"}</button>
        </>}>
        <Field label="Display name"><TextInput value={f.display_name} onChange={(v) => set("display_name", v)} /></Field>
        <Field label="Description"><TextArea rows={2} value={f.description} onChange={(v) => set("description", v)} /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Typical revenue model"><TextArea rows={3} value={f.typical_revenue_model} onChange={(v) => set("typical_revenue_model", v)} /></Field>
          <Field label="Typical cost structure"><TextArea rows={3} value={f.typical_cost_structure} onChange={(v) => set("typical_cost_structure", v)} /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Key risks" hint="one per line"><TextArea rows={4} value={f.key_risks} onChange={(v) => set("key_risks", v)} /></Field>
          <Field label="Key opportunities" hint="one per line"><TextArea rows={4} value={f.key_opportunities} onChange={(v) => set("key_opportunities", v)} /></Field>
        </div>
        <Field label="Seasonal notes"><TextArea rows={2} value={f.seasonal_notes} onChange={(v) => set("seasonal_notes", v)} /></Field>
        <Field label="Notes (internal)"><TextArea rows={2} value={f.notes} onChange={(v) => set("notes", v)} /></Field>
        <Toggle value={f.active} onChange={(v) => set("active", v)} label="Active" />
        {!isNew && r.industry_id ? <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 10 }}>Linked to industries.id <span style={{ fontFamily: "monospace" }}>{r.industry_id}</span></div> : null}
      </Modal>
    );
  }

  function ConfirmDelete({ what, onCancel, onConfirm }) {
    return (
      <Modal title="Confirm delete" onClose={onCancel}
        footer={<>
          <button className="pc-adm-btn-ghost" onClick={onCancel}>Cancel</button>
          <button className="pc-adm-btn-primary" style={{ background: "#ef4444" }} onClick={onConfirm}>Delete</button>
        </>}>
        <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.6 }}>Delete {what}? This cannot be undone.</div>
      </Modal>
    );
  }

  function Toast({ msg, kind }) {
    return (
      <div style={{
        position: "fixed", bottom: 22, right: 22, zIndex: 10000, padding: "11px 16px", borderRadius: 9,
        background: kind === "error" ? "#7f1d1d" : "#064e3b", color: "#fff", fontSize: 13, fontWeight: 500,
        boxShadow: "0 6px 24px rgba(0,0,0,0.4)", maxWidth: 360,
      }}>{msg}</div>
    );
  }

  // ── main component ────────────────────────────────────────────────────────────
  function AdminKpiLibrary() {
    const [kpis, setKpis] = useState([]);
    const [profiles, setProfiles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [sel, setSel] = useState({ archetype: "retail", industry: null });
    const [expanded, setExpanded] = useState(() => ({ retail: true }));
    const [tab, setTab] = useState("kpis");
    const [editKpi, setEditKpi] = useState(null);
    const [editProfile, setEditProfile] = useState(null);
    const [delKpi, setDelKpi] = useState(null);
    const [delProfile, setDelProfile] = useState(null);
    const [toast, setToast] = useState(null);

    const flash = (msg, kind) => { setToast({ msg, kind }); setTimeout(() => setToast(null), 3200); };

    const load = async () => {
      const db = window.supabaseClient;
      if (!db) { setLoading(false); return; }
      const [{ data: k }, { data: p }] = await Promise.all([
        db.from("kpi_library").select("*").order("archetype", { ascending: true }).order("display_order", { ascending: true }),
        db.from("industry_profiles").select("*").order("archetype", { ascending: true }).order("industry", { ascending: true }),
      ]);
      setKpis(k || []);
      setProfiles(p || []);
      setLoading(false);
    };
    useEffect(() => { load(); }, []);

    // Industries per archetype = profiles + any non-null industries used by KPIs.
    const industriesByArchetype = useMemo(() => {
      const map = {};
      for (const a of ARCHETYPES) map[a.slug] = new Set();
      for (const p of profiles) { (map[p.archetype] = map[p.archetype] || new Set()).add(p.industry); }
      for (const k of kpis) { if (k.industry) (map[k.archetype] = map[k.archetype] || new Set()).add(k.industry); }
      const out = {};
      Object.keys(map).forEach((a) => { out[a] = Array.from(map[a]).sort(); });
      return out;
    }, [profiles, kpis]);

    // Any archetype present in data but not in the canonical list (defensive).
    const archetypeList = useMemo(() => {
      const known = new Set(ARCHETYPES.map((a) => a.slug));
      const extra = [];
      for (const r of [...kpis, ...profiles]) { if (r.archetype && !known.has(r.archetype) && !extra.includes(r.archetype)) extra.push(r.archetype); }
      return [...ARCHETYPES, ...extra.map((s) => ({ slug: s, label: s }))];
    }, [kpis, profiles]);

    const visibleKpis = useMemo(() => {
      return kpis
        .filter((k) => k.archetype === sel.archetype && (sel.industry == null ? true : (k.industry === sel.industry || k.industry == null)))
        .sort((a, b) => (a.display_order ?? 0) - (b.display_order ?? 0) || String(a.kpi_name).localeCompare(String(b.kpi_name)));
    }, [kpis, sel]);

    const selProfile = useMemo(() => {
      if (!sel.industry) return null;
      return profiles.find((p) => p.archetype === sel.archetype && p.industry === sel.industry) || null;
    }, [profiles, sel]);

    const selectNode = (archetype, industry) => { setSel({ archetype, industry }); if (industry && tab !== "kpis") setTab(tab); };
    const toggleExpand = (slug) => setExpanded((e) => ({ ...e, [slug]: !e[slug] }));

    const deleteKpi = async (row) => {
      const db = window.supabaseClient;
      const { error } = await db.from("kpi_library").delete().eq("id", row.id);
      setDelKpi(null);
      if (error) { flash(error.message || "Delete failed.", "error"); return; }
      setKpis((prev) => prev.filter((r) => r.id !== row.id));
      flash("KPI deleted.");
    };
    const deleteProfile = async (row) => {
      const db = window.supabaseClient;
      const { error } = await db.from("industry_profiles").delete().eq("id", row.id);
      setDelProfile(null);
      if (error) { flash(error.message || "Delete failed.", "error"); return; }
      setProfiles((prev) => prev.filter((r) => r.id !== row.id));
      flash("Profile deleted.");
    };

    const selArcheLabel = ARCHE_LABEL[sel.archetype] || sel.archetype;

    return (
      <div className="pc-adm-section">
        {toast && <Toast {...toast} />}
        <div className="pc-adm-section-header">
          <div>
            <h2 className="pc-adm-section-title">KPI Library</h2>
            <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>
              Master KPI catalog and industry profiles that drive the onboarding wizard and dashboards.
              Edits are written directly to <span style={{ fontFamily: "monospace" }}>kpi_library</span> and <span style={{ fontFamily: "monospace" }}>industry_profiles</span>.
            </div>
          </div>
        </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: "260px 1fr", gap: 16, alignItems: "start" }}>
            {/* ── left: navigation tree ──────────────────────────────────── */}
            <div className="pc-adm-card" style={{ padding: 8, position: "sticky", top: 12 }}>
              {archetypeList.map((a) => {
                const inds = industriesByArchetype[a.slug] || [];
                const isOpen = !!expanded[a.slug];
                const archeActive = sel.archetype === a.slug && sel.industry == null;
                const kpiCount = kpis.filter((k) => k.archetype === a.slug).length;
                return (
                  <div key={a.slug} style={{ marginBottom: 2 }}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <button onClick={() => toggleExpand(a.slug)} title="Expand" style={{
                        background: "transparent", border: "none", color: "var(--text-3)", cursor: "pointer",
                        width: 20, height: 28, fontSize: 11, flex: "0 0 auto",
                      }}>{inds.length ? (isOpen ? "▾" : "▸") : "·"}</button>
                      <button onClick={() => selectNode(a.slug, null)} style={{
                        flex: 1, textAlign: "left", background: archeActive ? "var(--bg-elev-2)" : "transparent",
                        border: "none", borderRadius: 6, padding: "6px 8px", cursor: "pointer",
                        color: archeActive ? "var(--text)" : "var(--text-2)", fontWeight: archeActive ? 700 : 600, fontSize: 12.5,
                        display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8,
                      }}>
                        <span>{a.label}</span>
                        <span style={{ fontSize: 10.5, color: "var(--text-3)", fontWeight: 600 }}>{kpiCount}</span>
                      </button>
                    </div>
                    {isOpen && inds.map((ind) => {
                      const active = sel.archetype === a.slug && sel.industry === ind;
                      const hasProfile = profiles.some((p) => p.archetype === a.slug && p.industry === ind);
                      return (
                        <button key={ind} onClick={() => selectNode(a.slug, ind)} style={{
                          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6,
                          width: "calc(100% - 20px)", marginLeft: 20, textAlign: "left",
                          background: active ? "var(--bg-elev-2)" : "transparent", border: "none", borderRadius: 6,
                          padding: "5px 8px", cursor: "pointer", color: active ? "var(--text)" : "var(--text-3)",
                          fontSize: 12, fontWeight: active ? 600 : 500,
                        }}>
                          <span>{ind}</span>
                          {!hasProfile ? <span style={{ fontSize: 9.5, color: "var(--text-4, #5b6675)" }}>no profile</span> : null}
                        </button>
                      );
                    })}
                  </div>
                );
              })}
            </div>

            {/* ── right: tabs + content ──────────────────────────────────── */}
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 4, marginBottom: 14, borderBottom: "1px solid var(--border, #222b36)" }}>
                {[["kpis", "KPIs"], ["profile", "Industry Profile"]].map(([id, label]) => (
                  <button key={id} onClick={() => setTab(id)} style={{
                    background: "transparent", border: "none", cursor: "pointer", padding: "9px 14px", fontSize: 13,
                    fontWeight: 600, color: tab === id ? "var(--text)" : "var(--text-3)",
                    borderBottom: tab === id ? "2px solid var(--accent, #2563eb)" : "2px solid transparent", marginBottom: -1,
                  }}>{label}</button>
                ))}
                <div style={{ marginLeft: "auto", fontSize: 12, color: "var(--text-3)" }}>
                  {selArcheLabel}{sel.industry ? <span> · {sel.industry}</span> : <span> · archetype-wide</span>}
                </div>
              </div>

              {tab === "kpis" ? (
                <div className="pc-adm-card">
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 14px", borderBottom: "1px solid var(--border, #222b36)" }}>
                    <div style={{ fontSize: 12.5, color: "var(--text-2)" }}>
                      {visibleKpis.length} KPI{visibleKpis.length === 1 ? "" : "s"} for <strong style={{ color: "var(--text)" }}>{selArcheLabel}</strong>
                      {sel.industry ? <span> (including archetype-wide)</span> : null}
                    </div>
                    <button className="pc-adm-btn-primary" style={{ fontSize: 12.5, padding: "7px 14px" }}
                      onClick={() => setEditKpi({ archetype: sel.archetype, industry: sel.industry || "", display_order: visibleKpis.length })}>
                      + New KPI
                    </button>
                  </div>
                  <div className="pc-adm-table-wrap">
                    <table className="pc-adm-table">
                      <thead>
                        <tr>
                          <th style={{ width: 40 }}>#</th><th>KPI</th><th>Key</th><th>Unit</th><th>Direction</th>
                          <th>Scope</th><th>Default</th><th>Status</th><th style={{ textAlign: "right" }}>Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                        {visibleKpis.map((k) => (
                          <tr key={k.id}>
                            <td style={{ color: "var(--text-3)" }}>{k.display_order}</td>
                            <td style={{ fontWeight: 600, color: "var(--text)" }}>{k.kpi_name}</td>
                            <td style={{ fontFamily: "monospace", fontSize: 11.5, color: "var(--text-2)" }}>{k.kpi_key}</td>
                            <td style={{ color: "var(--text-2)" }}>{k.unit}</td>
                            <td style={{ color: "var(--text-2)", fontSize: 12 }}>{DIR_LABEL[k.direction] || k.direction}</td>
                            <td><span className="pc-adm-badge" style={{ background: "var(--bg-elev-2)", color: "var(--text-2)" }}>{k.industry || "all"}</span></td>
                            <td>{k.is_default ? <span className="pc-adm-badge" style={{ background: "rgba(37,99,235,0.12)", color: "#3b82f6" }}>Default</span> : <span style={{ color: "var(--text-4,#5b6675)" }}>—</span>}</td>
                            <td><span className="pc-adm-badge" style={k.active !== false ? { background: "rgba(16,185,129,0.12)", color: "#10b981" } : { background: "var(--bg-elev-2)", color: "var(--text-3)" }}>{k.active !== false ? "Active" : "Hidden"}</span></td>
                            <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                              <button className="pc-adm-btn-ghost" style={{ fontSize: 11, padding: "4px 10px" }} onClick={() => setEditKpi(k)}>Edit</button>
                              <button className="pc-adm-btn-ghost" style={{ fontSize: 11, padding: "4px 10px", color: "#ef4444" }} onClick={() => setDelKpi(k)}>Delete</button>
                            </td>
                          </tr>
                        ))}
                        {!visibleKpis.length && (
                          <tr><td colSpan={9} style={{ textAlign: "center", color: "var(--text-3)", padding: 28 }}>No KPIs for this selection. Use “+ New KPI” to add one.</td></tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>
              ) : (
                <div className="pc-adm-card" style={{ padding: 0 }}>
                  {!sel.industry ? (
                    <div style={{ padding: 16 }}>
                      <div style={{ fontSize: 12.5, color: "var(--text-2)", marginBottom: 12 }}>
                        Industry profiles for <strong style={{ color: "var(--text)" }}>{selArcheLabel}</strong>. Pick an industry on the left to edit its profile, or create one below.
                      </div>
                      <div className="pc-adm-table-wrap">
                        <table className="pc-adm-table">
                          <thead><tr><th>Industry</th><th>Profile</th><th>Linked</th><th style={{ textAlign: "right" }}>Actions</th></tr></thead>
                          <tbody>
                            {(industriesByArchetype[sel.archetype] || []).map((ind) => {
                              const p = profiles.find((x) => x.archetype === sel.archetype && x.industry === ind);
                              return (
                                <tr key={ind}>
                                  <td style={{ fontWeight: 600, color: "var(--text)" }}>{ind}</td>
                                  <td>{p ? <span className="pc-adm-badge" style={{ background: "rgba(16,185,129,0.12)", color: "#10b981" }}>{p.display_name}</span> : <span style={{ color: "var(--text-4,#5b6675)" }}>none</span>}</td>
                                  <td style={{ color: "var(--text-3)", fontSize: 11 }}>{p && p.industry_id ? "industries" : "—"}</td>
                                  <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                                    <button className="pc-adm-btn-ghost" style={{ fontSize: 11, padding: "4px 10px" }} onClick={() => { setSel({ archetype: sel.archetype, industry: ind }); setEditProfile({ row: p || null, archetype: sel.archetype, industry: ind }); }}>{p ? "Edit" : "Create"}</button>
                                    {p ? <button className="pc-adm-btn-ghost" style={{ fontSize: 11, padding: "4px 10px", color: "#ef4444" }} onClick={() => setDelProfile(p)}>Delete</button> : null}
                                  </td>
                                </tr>
                              );
                            })}
                            {!(industriesByArchetype[sel.archetype] || []).length && (
                              <tr><td colSpan={4} style={{ textAlign: "center", color: "var(--text-3)", padding: 28 }}>No industries known for this archetype yet.</td></tr>
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  ) : (
                    <div style={{ padding: 16 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                        <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text)" }}>{selArcheLabel} · {sel.industry}</div>
                        <div style={{ display: "flex", gap: 8 }}>
                          <button className="pc-adm-btn-primary" style={{ fontSize: 12.5, padding: "7px 14px" }} onClick={() => setEditProfile({ row: selProfile, archetype: sel.archetype, industry: sel.industry })}>
                            {selProfile ? "Edit profile" : "Create profile"}
                          </button>
                          {selProfile ? <button className="pc-adm-btn-ghost" style={{ fontSize: 12.5, padding: "7px 14px", color: "#ef4444" }} onClick={() => setDelProfile(selProfile)}>Delete</button> : null}
                        </div>
                      </div>
                      {!selProfile ? (
                        <div style={{ fontSize: 13, color: "var(--text-3)", padding: "20px 0" }}>No profile exists for this industry yet. Click “Create profile”.</div>
                      ) : (
                        <ProfileView p={selProfile} />
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        )}

        {editKpi && <KpiEditor row={editKpi} onClose={() => setEditKpi(null)} onError={(m) => flash(m, "error")} onSaved={async () => { setEditKpi(null); await load(); flash("KPI saved."); }} />}
        {editProfile && <ProfileEditor row={editProfile.row} archetype={editProfile.archetype} industry={editProfile.industry} onClose={() => setEditProfile(null)} onError={(m) => flash(m, "error")} onSaved={async () => { setEditProfile(null); await load(); flash("Profile saved."); }} />}
        {delKpi && <ConfirmDelete what={`the KPI “${delKpi.kpi_name}”`} onCancel={() => setDelKpi(null)} onConfirm={() => deleteKpi(delKpi)} />}
        {delProfile && <ConfirmDelete what={`the profile “${delProfile.display_name}”`} onCancel={() => setDelProfile(null)} onConfirm={() => deleteProfile(delProfile)} />}
      </div>
    );
  }

  // Read-only rendering of a profile row.
  function ProfileView({ p }) {
    const block = (label, value) => value ? (
      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.4, marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 13, color: "var(--text)", lineHeight: 1.55 }}>{value}</div>
      </div>
    ) : null;
    const list = (label, arr) => Array.isArray(arr) && arr.length ? (
      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.4, marginBottom: 4 }}>{label}</div>
        <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: "var(--text)", lineHeight: 1.6 }}>{arr.map((x, i) => <li key={i}>{x}</li>)}</ul>
      </div>
    ) : null;
    return (
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <div>
          {block("Description", p.description)}
          {block("Typical revenue model", p.typical_revenue_model)}
          {block("Typical cost structure", p.typical_cost_structure)}
          {block("Seasonal notes", p.seasonal_notes)}
          {block("Notes", p.notes)}
        </div>
        <div>
          {list("Key risks", p.key_risks)}
          {list("Key opportunities", p.key_opportunities)}
        </div>
      </div>
    );
  }

  window.AdminKpiLibrary = AdminKpiLibrary;
})();
