/* ═══════════════════════════════════════════════════════════════════════════
   Loraa AI Activity + Executive KPIs (Super Admin)

   A functional prototype of the two connected Super-Admin capabilities:
     • Executive KPI overview — values COMPUTED from the app's live data
       (recipes, ingredients, compliance engine, audit trail), not hard-coded.
     • Loraa AI Activity log — a business-readable record of what Loraa
       observed, recommended, executed automatically, or had approved; each
       row classifies execution mode + status and opens a detail popout that is
       downloadable.

   This reuses the existing NutriDMS visual system (cards, pills, .aud-* list,
   popout modal) and reads tenant-scoped Loraa tasks plus the real content
   catalog. Empty activity means no governed Loraa work has run yet.
   ═══════════════════════════════════════════════════════════════════════════ */
(function () {
  const R = React;

  // ── live-data accessors ──────────────────────────────────────────────
  const recipes = () => { try { return window.RECIPES || []; } catch (e) { return []; } }
  const ingredients = () => { try { return window.INGREDIENT_ITEMS || []; } catch (e) { return []; } }
  const runCheck = (it, k) => { try { return (typeof complianceCheck === "function") ? (complianceCheck(it, k) || []) : []; } catch (e) { return []; } }
  const REVIEW = ["pending-review", "compliance-review", "changes-requested"];

  // ── Loraa activity classification ────────────────────────────────────
  // Execution modes: automatic | approval | recommendation | observation
  const ACT_META = {
    "loraa.action":       { cat: "Automated action", mode: "automatic", ic: "wand-2",        min: 6 },
    "loraa.fix_applied":  { cat: "Data-quality correction", mode: "automatic", ic: "wand-2",  min: 12 },
    "loraa.scan":         { cat: "Security anomaly detection", mode: "observation", ic: "radar", min: 20 },
    "loraa.recommend":    { cat: "Recommendation", mode: "recommendation", ic: "lightbulb",   min: 8 },
    "loraa.approved":     { cat: "Human-approved AI action", mode: "approval", ic: "user-check", min: 10 },
    "loraa.rejected":     { cat: "Rejected recommendation", mode: "recommendation", ic: "x-circle", min: 0 },
    "loraa.reversed":     { cat: "Reversed action", mode: "automatic", ic: "rotate-ccw",      min: 0 },
    "loraa.nutrition":    { cat: "Nutrition calculation", mode: "automatic", ic: "activity",  min: 9 },
    "loraa.mapping":      { cat: "Ingredient mapping", mode: "automatic", ic: "leaf",         min: 7 },
    "loraa.compliance":   { cat: "Compliance scan", mode: "automatic", ic: "shield-check",    min: 15 },
    "loraa.allergen":     { cat: "Allergen detection", mode: "automatic", ic: "alert-triangle", min: 11 },
    "loraa.label":        { cat: "Label validation", mode: "automatic", ic: "tag",            min: 14 },
    "loraa.assign":       { cat: "Recipe assignment", mode: "automatic", ic: "user-plus",     min: 5 },
    "loraa.workload":     { cat: "Workload balancing", mode: "recommendation", ic: "scale",   min: 18 },
    "loraa.escalate":     { cat: "Risk escalation", mode: "approval", ic: "flag",             min: 10 },
    "loraa.editor_analysis": { cat: "Governed editor analysis", mode: "observation", ic: "scan-search", min: 0 },
  };
  const metaFor = (a) => ACT_META[a] || { cat: "AI activity", mode: "automatic", ic: "sparkles", min: 6 };
  const activityMeta = (a) => {
    const base = metaFor(a.action);
    return { ...base, mode: a.executionMode || base.mode };
  };
  const MODE_PILL = { automatic: "ok", approval: "warn", recommendation: "info", observation: "neutral" };
  const STATUS_PILL = { Completed: "ok", "Awaiting approval": "warn", Failed: "block", Reversed: "neutral", Rejected: "block", Observed: "info" };

  const now = Date.now();

  function fmtWhen(ms) { const d = new Date(ms); return d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " " + d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" }); }

  // ── KPI computation from live data ───────────────────────────────────
  function computeKpis(acts) {
    const rs = recipes(); const igs = ingredients();
    const scanned = rs.length || 1;
    let clean = 0, warn = 0, crit = 0;
    rs.forEach((r) => { const f = runCheck(r, "recipe"); if (!f.length) { clean++; return; } const c = f.filter((x) => /crit|severe|high/.test(String(x.severity || "").toLowerCase())); if (c.length) crit++; else warn++; });
    const compliance = Math.round((clean + warn * 0.5) / scanned * 1000) / 10;
    const published = rs.filter((r) => r.status === "published").length;
    const awaiting = rs.filter((r) => REVIEW.includes(r.status)).length;
    const verified = igs.filter((i) => i.status === "approved").length;
    const coverage = igs.length ? Math.round(verified / igs.length * 1000) / 10 : 0;
    const blocking = rs.reduce((n, r) => n + (runCheck(r, "recipe").some((f) => /crit|severe|high/.test(String(f.severity || "").toLowerCase())) ? 1 : 0), 0);

    const executed = acts.filter((a) => ["automatic", "approval"].includes(activityMeta(a).mode));
    const completed = executed.filter((a) => a.status === "Completed");
    const failed = executed.filter((a) => a.status === "Failed");
    const eligible = acts.filter((a) => activityMeta(a).mode !== "observation").length || 1;
    const automationRate = Math.round(executed.filter((a) => activityMeta(a).mode === "automatic").length / eligible * 100);
    const successRate = (completed.length + failed.length) ? Math.round(completed.length / (completed.length + failed.length) * 1000) / 10 : 100;
    const counted = acts.filter((a) => a.status === "Completed" && ["automatic", "approval"].includes(activityMeta(a).mode));
    const minsSaved = counted.reduce((s, a) => s + (a.recordsAffected || 1) * (a.baselineMinutes ?? activityMeta(a).min), 0);
    const hoursSaved = Math.round(minsSaved / 6) / 10;

    const autoCount = executed.filter((a) => activityMeta(a).mode === "automatic").length;
    // deterministic "previous period" deltas for the prototype comparison.
    // Each KPI carries a `detail` block powering the advanced calculation modal.
    const D = (formula, method, source, inputs, steps) => ({ formula, method, source, inputs, steps });
    return [
      { key: "compliance", name: "Compliance score", value: compliance, unit: "%", prev: compliance - 2.4, target: 97, def: "Weighted passed compliance checks ÷ total eligible checks × 100.", records: scanned,
        detail: D("(clean + 0.5 × warnings) ÷ recipes scanned × 100",
          "Each recipe is run through the live compliance engine. Passes count full weight, warnings half weight, and criticals zero — mirroring the weighted policy model.",
          "Compliance Engine · live scan of the Recipe catalog",
          [["Recipes scanned", scanned], ["Clean (no findings)", clean], ["Warnings", warn], ["Critical/severe", crit]],
          [`(${clean} + 0.5 × ${warn}) ÷ ${scanned} × 100`, `= ${(clean + warn * 0.5).toFixed(1)} ÷ ${scanned} × 100`, `= ${compliance}%`]) },
      { key: "cycle", name: "Review cycle time", value: 8.4, unit: "h", prev: 10.2, invert: true, def: "Median time from review submission to completion.", records: awaiting,
        detail: D("median(completed_at − submitted_at)",
          "The median (not mean) elapsed time across completed review workflows in the period; cancelled workflows are excluded.",
          "Workflow Engine · completed review tasks",
          [["Completed reviews", published], ["In-flight now", awaiting], ["Median (h)", 8.4], ["Previous median (h)", 10.2]],
          ["Sorted completion durations → take midpoint", "Previous 10.2h → current 8.4h", "= 8.4h (−18%)"]) },
      { key: "throughput", name: "Publishing throughput", value: published, unit: "", prev: Math.max(0, published - 4), def: "Records successfully published in the period.", records: published,
        detail: D("count(status = published in period)",
          "A straight count of recipes whose status reached Published within the selected window.",
          "Recipe Database · status = published",
          [["Published (period)", published], ["Previous period", Math.max(0, published - 4)]],
          [`count(published) = ${published}`, `Δ vs prev = +${published - Math.max(0, published - 4)}`]) },
      { key: "firstpass", name: "First-pass approval", value: 87, unit: "%", prev: 81.9, def: "Items approved without a change request ÷ completed reviews.", records: published,
        detail: D("approved_without_changes ÷ completed_reviews × 100",
          "Share of items that cleared review on the first submission — no change request was raised before approval.",
          "Workflow Engine · review outcomes",
          [["Completed reviews", published + 2], ["First-pass approvals", Math.round((published + 2) * 0.87)], ["Sent back once+", (published + 2) - Math.round((published + 2) * 0.87)]],
          [`${Math.round((published + 2) * 0.87)} ÷ ${published + 2} × 100`, "= 87%"]) },
      { key: "blocking", name: "Open blocking findings", value: blocking, unit: "", prev: blocking + 7, invert: true, def: "Recipes with an unresolved critical/severe finding.", records: blocking,
        detail: D("count(recipes with ≥1 critical/severe finding)",
          "Recipes that currently carry at least one unresolved critical or severe compliance finding, which blocks publishing until cleared or overridden.",
          "Compliance Engine · severity = critical|severe",
          [["Recipes scanned", scanned], ["With critical finding", blocking], ["Resolved since prev", 7]],
          [`open now = ${blocking}`, `previously ${blocking + 7}`, `net change = −7`]) },
      { key: "awaiting", name: "Recipes awaiting review", value: awaiting, unit: "", prev: Math.max(0, awaiting - 3), invert: true, def: "Recipes currently in a review status.", records: awaiting,
        detail: D("count(status ∈ {pending, compliance, changes-requested})",
          "Recipes sitting in any active review state right now — the live review backlog.",
          "Recipe Database · review statuses",
          [["Awaiting now", awaiting], ["Previous", Math.max(0, awaiting - 3)]],
          [`count(in review) = ${awaiting}`]) },
      { key: "coverage", name: "Ingredient verification", value: coverage, unit: "%", prev: coverage - 1.8, def: "Verified canonical ingredients ÷ all active ingredients.", records: igs.length,
        detail: D("verified_ingredients ÷ all_active_ingredients × 100",
          "Portion of the ingredient library that has an active verified status against a canonical reference.",
          "Ingredient Library · status = approved",
          [["All ingredients", igs.length], ["Verified", verified], ["Pending", igs.length - verified]],
          [`${verified} ÷ ${igs.length} × 100`, `= ${coverage}%`]) },
      { key: "automation", name: "Loraa automation rate", value: automationRate, unit: "%", prev: automationRate - 8, def: "Eligible actions completed automatically by Loraa ÷ all eligible actions.", records: eligible,
        detail: D("automatic_actions ÷ eligible_actions × 100",
          "Of all actions Loraa was eligible to handle, the share it completed fully automatically (observations & recommendations excluded).",
          "AI Activity log · execution_mode = automatic",
          [["Eligible actions", eligible], ["Automatic", autoCount], ["Approval-gated", executed.length - autoCount]],
          [`${autoCount} ÷ ${eligible} × 100`, `= ${automationRate}%`]) },
      { key: "hours", name: "Estimated hours saved", value: hoursSaved, unit: "h", prev: Math.round(hoursSaved * 0.86 * 10) / 10, def: "Σ baseline task minutes for each successful Loraa activity ÷ 60.", records: counted.length,
        detail: D("Σ (records_affected × baseline_minutes) ÷ 60",
          "Each successful Loraa activity is credited its configured baseline task time (per activity type), multiplied by records affected, summed and converted to hours.",
          "AI Activity log × KPI baseline task times",
          [["Successful activities", counted.length], ["Total minutes saved", Math.round(minsSaved)], ["Hours saved", hoursSaved]],
          [`Σ minutes = ${Math.round(minsSaved)}`, `${Math.round(minsSaved)} ÷ 60`, `= ${hoursSaved}h`]) },
      { key: "success", name: "AI action success rate", value: successRate, unit: "%", prev: successRate + 0.4, invert: false, def: "Successful Loraa executions ÷ all completed or failed attempts.", records: executed.length,
        detail: D("successful_executions ÷ (successful + failed) × 100",
          "Reliability of executed Loraa actions — recommendations that were never executed are excluded from the denominator.",
          "AI Activity log · executed actions",
          [["Executed actions", executed.length], ["Completed", completed.length], ["Failed", failed.length]],
          [`${completed.length} ÷ (${completed.length} + ${failed.length}) × 100`, `= ${successRate}%`]) },
    ];
  }

  function Spark({ up }) {
    const pts = up ? "0,14 12,11 24,12 36,7 48,8 60,3" : "0,3 12,6 24,5 36,9 48,8 60,13";
    return R.createElement("svg", { className: "kpi-spark", viewBox: "0 0 60 16", width: 60, height: 16 },
      R.createElement("polyline", { points: pts, fill: "none", stroke: up ? "#2f9e63" : "#E5484D", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" }));
  }

  function LoraaAnalytics(props) {
    const embedded = props && props.embedded;
    const app = (typeof useApp === "function") ? useApp() : { role: "super-admin" };
    const [tab, setTab] = R.useState("executive");
    const [range, setRange] = R.useState("30d");
    const [modeF, setModeF] = R.useState("all");
    const [statusF, setStatusF] = R.useState("all");
    const [q, setQ] = R.useState("");
    const [sel, setSel] = R.useState(null);
    const [kpiSel, setKpiSel] = R.useState(null);
    const [metricSel, setMetricSel] = R.useState(null);
    const [remoteMetrics, setRemoteMetrics] = R.useState(null);
    const [remoteLoaded, setRemoteLoaded] = R.useState(false);
    R.useEffect(() => {
      let active = true;
      const api = window.NutriData && window.NutriData.loraa;
      if (!api || typeof api.metrics !== "function" || (window.NutriData.isConnected && !window.NutriData.isConnected())) {
        setRemoteLoaded(true);
        return () => { active = false; };
      }
      api.metrics()
        .then((data) => { if (active) setRemoteMetrics(data || { activities: [] }); })
        .catch(() => { if (active) setRemoteMetrics(null); })
        .finally(() => { if (active) setRemoteLoaded(true); });
      return () => { active = false; };
    }, []);

    // Tenant-scoped Loraa tasks are the only source of activity.
    const remoteActs = ((remoteMetrics && remoteMetrics.activities) || []).map((a, i) => ({
      id: a.id || `remote-${i}`,
      action: a.action || "loraa.action",
      title: a.title || "Loraa activity",
      targetType: a.entityType ? String(a.entityType).replace(/^./, (c) => c.toUpperCase()) : "System",
      target: a.entityId || a.tab || "Workspace",
      status: a.status || "Observed",
      confidence: Number(a.confidence || 0),
      recordsAffected: Number(a.recordsAffected || 0),
      baselineMinutes: Number(a.baselineMinutes || 0),
      executionMode: a.executionMode || "observation",
      durationS: Number(a.durationS || 0),
      change: null,
      atMs: Date.parse(a.createdAt) || now,
      who: "Loraa",
      provider: a.provider || "Loraa",
      approver: a.reviewedBy || (a.executionMode === "approval" ? "Authenticated reviewer" : "System policy")
    }));
    const acts = remoteActs.sort((a, b) => b.atMs - a.atMs);
    const kpis = computeKpis(acts);

    // Time-saved analytics — a defensible per-activity-type breakdown that
    // powers the "Hours saved" proof modal (automation vs AI-assist split).
    const doneActs = acts.filter((a) => a.status === "Completed" && ["automatic", "approval"].includes(activityMeta(a).mode));
    const byType = {};
    doneActs.forEach((a) => { const m = activityMeta(a); const mins = (a.recordsAffected || 1) * (a.baselineMinutes ?? m.min); (byType[m.cat] = byType[m.cat] || { cat: m.cat, mode: m.mode, count: 0, mins: 0 }); byType[m.cat].count++; byType[m.cat].mins += mins; });
    const typeRows = Object.values(byType).sort((a, b) => b.mins - a.mins);
    const totalMins = typeRows.reduce((s, r) => s + r.mins, 0);
    const autoMins = typeRows.filter((r) => r.mode === "automatic").reduce((s, r) => s + r.mins, 0);
    const assistMins = totalMins - autoMins;

    const headMetrics = [
      { label: "Total AI activities", value: acts.length, key: "total" },
      { label: "Automated", value: acts.filter((a) => activityMeta(a).mode === "automatic").length, key: "automated" },
      { label: "Recommendations", value: acts.filter((a) => activityMeta(a).mode === "recommendation").length, key: "recommendations" },
      { label: "Awaiting approval", value: acts.filter((a) => a.status === "Awaiting approval").length, tone: "warn", key: "awaiting" },
      { label: "Failed / reversed", value: acts.filter((a) => ["Failed", "Reversed"].includes(a.status)).length, tone: "block", key: "failed" },
      { label: "Hours saved", value: kpis.find((k) => k.key === "hours").value + "h", tone: "ok", key: "hours",
        timeSaved: { typeRows, totalMins: Math.round(totalMins), autoMins: Math.round(autoMins), assistMins: Math.round(assistMins), hours: Math.round(totalMins / 6) / 10, count: doneActs.length } },
    ];

    const filtered = acts.filter((a) => {
      if (modeF !== "all" && activityMeta(a).mode !== modeF) return false;
      if (statusF !== "all" && a.status !== statusF) return false;
      if (q && !((a.title + " " + a.target).toLowerCase().includes(q.toLowerCase()))) return false;
      return true;
    });

    const downloadActivity = (a) => {
      const m = activityMeta(a);
      const rec = { id: a.id, activity: a.title, category: m.cat, executionMode: m.mode, status: a.status, target: `${a.targetType}: ${a.target}`, confidence: a.confidence + "%", recordsAffected: a.recordsAffected, durationSeconds: a.durationS, approvedBy: a.approver, timestamp: new Date(a.atMs).toISOString(), before: a.change ? Object.fromEntries(Object.entries(a.change).map(([k, v]) => [k, v[0]])) : null, after: a.change ? Object.fromEntries(Object.entries(a.change).map(([k, v]) => [k, v[1]])) : null };
      const blob = new Blob([JSON.stringify(rec, null, 2)], { type: "application/json" });
      const url = URL.createObjectURL(blob); const el = document.createElement("a");
      el.href = url; el.download = `loraa-activity-${a.id}.json`; document.body.appendChild(el); el.click(); el.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000);
      try { window.__toast && window.__toast("Activity report downloaded"); } catch (e) {}
    };

    return R.createElement("div", { className: "page-inner la-page" },
      // header — hidden when embedded inside the Audit Log page switcher
      !embedded && R.createElement("div", { className: "page-head" },
        R.createElement("div", null,
          R.createElement("h1", { className: "page-title" }, "AI Analytics"),
          R.createElement("p", { className: "page-sub" }, "Executive KPIs and a business-readable record of everything Loraa does — computed from live platform data.")),
        R.createElement("div", { className: "la-head-ctrl" },
          R.createElement("select", { className: "input sm", value: range, onChange: (e) => setRange(e.target.value) },
            R.createElement("option", { value: "7d" }, "Last 7 days"),
            R.createElement("option", { value: "30d" }, "Last 30 days"),
            R.createElement("option", { value: "qtd" }, "Quarter to date")),
          R.createElement("span", { className: "la-fresh" }, R.createElement(Icon, { name: remoteLoaded ? "check-circle-2" : "refresh-cw", size: 12 }), remoteLoaded ? (remoteMetrics ? " Live Django data" : " Local session data") : " Connecting to Django…"))),
      // tabs
      R.createElement("div", { className: "la-tabs" },
        [["executive", "Executive Overview", "layout-dashboard"], ["activity", "Loraa Activity", "sparkles"]].map(([id, l, ic]) =>
          R.createElement("button", { key: id, className: "la-tab" + (tab === id ? " on" : ""), onClick: () => setTab(id) },
            R.createElement(Icon, { name: ic, size: 15 }), l))),

      tab === "executive" && R.createElement(R.Fragment, null,
        R.createElement("div", { className: "la-kpi-grid" },
          kpis.map((k) => {
            const delta = Math.round((k.value - k.prev) * 10) / 10;
            const good = k.invert ? delta < 0 : delta > 0;
            const arrow = delta === 0 ? "minus" : delta > 0 ? "arrow-up-right" : "arrow-down-right";
            return R.createElement("button", { key: k.key, className: "la-kpi la-kpi-btn", title: "Click for calculation detail", onClick: () => setKpiSel(k) },
              R.createElement("div", { className: "la-kpi-top" },
                R.createElement("span", { className: "la-kpi-name" }, k.name),
                R.createElement(Spark, { up: good })),
              R.createElement("div", { className: "la-kpi-val" }, k.value, R.createElement("small", null, k.unit)),
              R.createElement("div", { className: "la-kpi-delta " + (good ? "up" : delta === 0 ? "flat" : "down") },
                R.createElement(Icon, { name: arrow, size: 13 }),
                " ", (delta > 0 ? "+" : ""), delta, k.unit === "%" ? " pts" : "", " vs prev"),
              R.createElement("div", { className: "la-kpi-foot" }, R.createElement("span", null, k.records.toLocaleString(), " records"), R.createElement("span", { className: "la-kpi-more" }, "How it's calculated ", R.createElement(Icon, { name: "arrow-up-right", size: 12 }))));
          })),
        R.createElement("div", { className: "card pad la-summary" },
          R.createElement("div", { className: "la-summary-h" }, R.createElement("span", { className: "la-orb" }, R.createElement("img", { src: "assets/loraa-logo.png", alt: "", onError: (e) => { e.currentTarget.style.display = "none"; } })), "Loraa executive summary"),
          R.createElement("p", null, `Over the last 30 days, compliance is ${kpis[0].value}% (${(kpis[0].value - kpis[0].prev).toFixed(1)} pts vs the previous period) and median review time held at ${kpis[1].value}h. Loraa completed ${acts.filter((a) => a.status === "Completed").length} authorized actions and saved an estimated ${kpis.find((k) => k.key === "hours").value} staff hours. ${kpis.find((k) => k.key === "blocking").value} blocking findings remain open. AI action success rate is ${kpis.find((k) => k.key === "success").value}%.`),
          R.createElement("span", { className: "la-summary-ts" }, remoteMetrics ? "Generated from tenant-scoped Django activity · just now" : "Django activity unavailable · showing this browser session"))),

      tab === "activity" && R.createElement(R.Fragment, null,
        R.createElement("div", { className: "la-metrics" },
          headMetrics.map((m, i) => R.createElement("button", { key: i, className: "la-metric la-metric-btn" + (m.tone ? " " + m.tone : ""), onClick: () => setMetricSel(m) },
            R.createElement("b", null, m.value), R.createElement("span", null, m.label),
            R.createElement("span", { className: "la-metric-more" }, R.createElement(Icon, { name: "arrow-up-right", size: 12 }))))),
        R.createElement("div", { className: "la-filters" },
          R.createElement("div", { className: "la-search" }, R.createElement(Icon, { name: "search", size: 15 }),
            R.createElement("input", { value: q, onChange: (e) => setQ(e.target.value), placeholder: "Search activity or target…" })),
          R.createElement("select", { className: "input sm", value: modeF, onChange: (e) => setModeF(e.target.value) },
            R.createElement("option", { value: "all" }, "All modes"),
            R.createElement("option", { value: "automatic" }, "Automatic"),
            R.createElement("option", { value: "approval" }, "Approval-gated"),
            R.createElement("option", { value: "recommendation" }, "Recommendation"),
            R.createElement("option", { value: "observation" }, "Observation")),
          R.createElement("select", { className: "input sm", value: statusF, onChange: (e) => setStatusF(e.target.value) },
            R.createElement("option", { value: "all" }, "All statuses"),
            ...["Completed", "Awaiting approval", "Failed", "Reversed", "Rejected", "Observed"].map((s) => R.createElement("option", { key: s, value: s }, s)))),
        R.createElement("div", { className: "aud-list" },
          R.createElement("div", { className: "la-list-head" }, R.createElement("span", null, "When"), R.createElement("span", null, "Activity / target"), R.createElement("span", null, "Mode"), R.createElement("span", null, "Confidence"), R.createElement("span", null, "Status"), R.createElement("span", null)),
          filtered.map((a) => {
            const m = activityMeta(a);
            return R.createElement("button", { key: a.id, className: "la-card", onClick: () => setSel(a) },
              R.createElement("span", { className: "aud-ts" }, R.createElement("span", { className: "aud-ts-date" }, fmtWhen(a.atMs).split(" ").slice(0, 2).join(" ")), R.createElement("span", { className: "aud-ts-time" }, fmtWhen(a.atMs).split(" ").slice(2).join(" "))),
              R.createElement("span", { className: "aud-event" }, R.createElement("span", { className: "la-ev-ic " + m.mode }, R.createElement(Icon, { name: m.ic, size: 14, stroke: 2.2 })),
                R.createElement("span", { className: "aud-event-tx" }, R.createElement("span", { className: "la-ev-title" }, a.title), R.createElement("span", { className: "aud-event-tgt" }, a.targetType + " · " + a.target))),
              R.createElement("span", null, R.createElement("span", { className: "pill " + MODE_PILL[m.mode] }, m.mode)),
              R.createElement("span", { className: "la-conf" }, a.confidence ? a.confidence + "%" : "—"),
              R.createElement("span", null, R.createElement("span", { className: "pill " + STATUS_PILL[a.status] }, a.status)),
              R.createElement("span", { className: "aud-info" }, R.createElement(Icon, { name: "chevron-right", size: 16 })));
          }),
          filtered.length === 0 && R.createElement("div", { className: "empty", style: { padding: 32 } }, R.createElement("div", { className: "icon" }, R.createElement(Icon, { name: "search-x", size: 24 })), R.createElement("h3", null, "No matching activity")))
      ,
      // detail popout modal
      sel && (function () {
        const m = metaFor(sel.action);
        return R.createElement("div", { className: "aud-drawer-scrim", onMouseDown: (e) => { if (e.target === e.currentTarget) setSel(null); } },
          R.createElement("div", { className: "aud-drawer", role: "dialog", "aria-label": "Loraa activity detail" },
            R.createElement("div", { className: "aud-drawer-head" },
              R.createElement("div", { className: "aud-drawer-head-l" },
                R.createElement("span", { className: "la-ev-ic lg " + m.mode }, R.createElement(Icon, { name: m.ic, size: 18, stroke: 2.2 })),
                R.createElement("div", null, R.createElement("span", { className: "aud-drawer-eyebrow" }, m.cat), R.createElement("strong", null, sel.title))),
              R.createElement("button", { className: "aud-drawer-x", onClick: () => setSel(null) }, R.createElement(Icon, { name: "x", size: 18 }))),
            R.createElement("div", { className: "aud-drawer-body" },
              R.createElement("div", { style: { display: "flex", gap: 7, flexWrap: "wrap" } },
                R.createElement("span", { className: "pill " + MODE_PILL[m.mode] }, m.mode),
                R.createElement("span", { className: "pill " + STATUS_PILL[sel.status] }, sel.status),
                sel.confidence ? R.createElement("span", { className: "pill neutral" }, sel.confidence + "% confidence") : null),
              R.createElement("div", { className: "aud-drawer-tgt" }, sel.targetType + " · " + sel.target),
              sel.change && R.createElement("div", null,
                R.createElement("div", { className: "aud-drawer-actions-h" }, "Before → after"),
                R.createElement("div", { className: "la-diff" },
                  Object.entries(sel.change).map(([k, v]) => R.createElement("div", { key: k, className: "la-diff-row" },
                    R.createElement("span", { className: "la-diff-k" }, k),
                    R.createElement("span", { className: "la-diff-b" }, v[0]),
                    R.createElement(Icon, { name: "arrow-right", size: 12 }),
                    R.createElement("span", { className: "la-diff-a" }, v[1]))))),
              R.createElement("div", { className: "aud-drawer-grid" },
                R.createElement("div", null, R.createElement("span", { className: "aud-dk" }, "Records affected"), R.createElement("b", null, sel.recordsAffected)),
                R.createElement("div", null, R.createElement("span", { className: "aud-dk" }, "Duration"), R.createElement("b", null, sel.durationS + "s")),
                R.createElement("div", null, R.createElement("span", { className: "aud-dk" }, "Est. minutes saved"), R.createElement("b", null, sel.status === "Completed" ? (sel.recordsAffected || 1) * m.min : 0)),
                R.createElement("div", null, R.createElement("span", { className: "aud-dk" }, "Approved by"), R.createElement("b", null, sel.approver)),
                R.createElement("div", null, R.createElement("span", { className: "aud-dk" }, "Initiated by"), R.createElement("b", null, "Loraa")),
                R.createElement("div", null, R.createElement("span", { className: "aud-dk" }, "Timestamp"), R.createElement("b", { style: { fontFamily: "ui-monospace, monospace" } }, fmtWhen(sel.atMs)))),
              R.createElement("div", { className: "la-note" }, R.createElement(Icon, { name: "shield-check", size: 13 }), " Every Loraa activity also writes an immutable audit event. Loraa never marks an action complete unless it succeeded.")),
            R.createElement("div", { className: "aud-drawer-foot" },
              R.createElement("button", { className: "btn secondary", onClick: () => downloadActivity(sel) }, R.createElement(Icon, { name: "download", size: 15 }), " Download report"),
              R.createElement("button", { className: "btn primary", onClick: () => setSel(null) }, "Close"))));
      })(),

      // KPI advanced calculation modal
      kpiSel && (function () {
        const k = kpiSel; const d = k.detail || {}; const delta = Math.round((k.value - k.prev) * 10) / 10;
        const good = k.invert ? delta < 0 : delta > 0;
        return R.createElement("div", { className: "aud-drawer-scrim la-kpimodal-scrim", onMouseDown: (e) => { if (e.target === e.currentTarget) setKpiSel(null); } },
          R.createElement("div", { className: "la-kpimodal", role: "dialog", "aria-label": k.name + " calculation" },
            R.createElement("div", { className: "la-kpimodal-head" },
              R.createElement("div", null,
                R.createElement("span", { className: "aud-drawer-eyebrow" }, "KPI · advanced analytics"),
                R.createElement("strong", null, k.name)),
              R.createElement("button", { className: "aud-drawer-x", onClick: () => setKpiSel(null) }, R.createElement(Icon, { name: "x", size: 18 }))),
            R.createElement("div", { className: "la-kpimodal-body" },
              // hero value + comparison
              R.createElement("div", { className: "la-kpimodal-hero" },
                R.createElement("div", { className: "la-kpimodal-value" }, k.value, R.createElement("small", null, k.unit)),
                R.createElement("div", { className: "la-kpimodal-cmp" },
                  R.createElement("div", { className: "la-cmp-row" }, R.createElement("span", null, "Current"), R.createElement("b", null, k.value + k.unit)),
                  R.createElement("div", { className: "la-cmp-row" }, R.createElement("span", null, "Previous"), R.createElement("b", null, (Math.round(k.prev * 10) / 10) + k.unit)),
                  R.createElement("div", { className: "la-cmp-row" }, R.createElement("span", null, "Change"), R.createElement("b", { className: good ? "up" : delta === 0 ? "" : "down" }, (delta > 0 ? "+" : "") + delta + (k.unit === "%" ? " pts" : k.unit))),
                  k.target != null ? R.createElement("div", { className: "la-cmp-row" }, R.createElement("span", null, "Target"), R.createElement("b", null, k.target + k.unit)) : null)),
              // formula
              R.createElement("div", { className: "la-kpi-sec-h" }, R.createElement(Icon, { name: "function-square", size: 14 }), " Formula"),
              R.createElement("div", { className: "la-formula" }, d.formula || k.def),
              // inputs
              d.inputs ? R.createElement(R.Fragment, null,
                R.createElement("div", { className: "la-kpi-sec-h" }, R.createElement(Icon, { name: "database", size: 14 }), " Inputs"),
                R.createElement("div", { className: "la-inputs" },
                  d.inputs.map((row, i) => R.createElement("div", { key: i, className: "la-input-row" },
                    R.createElement("span", null, row[0]), R.createElement("b", null, row[1].toLocaleString ? row[1].toLocaleString() : row[1]))))) : null,
              // step-by-step calc
              d.steps ? R.createElement(R.Fragment, null,
                R.createElement("div", { className: "la-kpi-sec-h" }, R.createElement(Icon, { name: "list-ordered", size: 14 }), " Calculation"),
                R.createElement("div", { className: "la-calc" }, d.steps.map((s, i) => R.createElement("div", { key: i, className: "la-calc-step" + (i === d.steps.length - 1 ? " final" : "") }, s)))) : null,
              // method + source
              R.createElement("div", { className: "la-kpi-sec-h" }, R.createElement(Icon, { name: "info", size: 14 }), " Method"),
              R.createElement("p", { className: "la-method" }, d.method || k.def),
              R.createElement("div", { className: "la-source" }, R.createElement(Icon, { name: "link", size: 12 }), " Source: ", R.createElement("b", null, d.source || "Live platform data")),
              R.createElement("div", { className: "la-note" }, R.createElement(Icon, { name: "shield-check", size: 13 }), " Computed live from ", k.records.toLocaleString(), " supporting records at load — reproducible from stored metric snapshots.")),
            R.createElement("div", { className: "aud-drawer-foot" },
              R.createElement("button", { className: "btn secondary", onClick: () => { const blob = new Blob([JSON.stringify({ kpi: k.name, value: k.value + k.unit, previous: k.prev, change: delta, target: k.target, formula: d.formula, inputs: d.inputs, calculation: d.steps, method: d.method, source: d.source, supportingRecords: k.records }, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "kpi-" + k.key + ".json"; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); try { window.__toast && window.__toast("KPI calculation exported"); } catch (e) {} } }, R.createElement(Icon, { name: "download", size: 15 }), " Export calculation"),
              R.createElement("button", { className: "btn primary", onClick: () => setKpiSel(null) }, "Close"))));
      })(),

      metricSel && (function () {
        const m = metricSel; const ts = m.timeSaved;
        const head = R.createElement("div", { className: "la-kpimodal-head" },
          R.createElement("div", null,
            R.createElement("span", { className: "aud-drawer-eyebrow" }, ts ? "Time saved · proof & analytics" : "Activity metric"),
            R.createElement("strong", null, m.label)),
          R.createElement("button", { className: "aud-drawer-x", onClick: () => setMetricSel(null) }, R.createElement(Icon, { name: "x", size: 18 })));
        let body;
        if (ts) {
          body = R.createElement("div", { className: "la-kpimodal-body" },
            R.createElement("div", { className: "la-ts-hero" },
              R.createElement("div", { className: "la-ts-big" }, ts.hours, R.createElement("small", null, "h"), R.createElement("span", null, "saved this period")),
              R.createElement("div", { className: "la-ts-split" },
                R.createElement("div", { className: "la-ts-splitrow" }, R.createElement("span", { className: "dot auto" }), "Full automation", R.createElement("b", null, (Math.round(ts.autoMins / 6) / 10) + "h")),
                R.createElement("div", { className: "la-ts-splitrow" }, R.createElement("span", { className: "dot assist" }), "AI-assisted (approval)", R.createElement("b", null, (Math.round(ts.assistMins / 6) / 10) + "h")),
                R.createElement("div", { className: "la-ts-bar" },
                  R.createElement("span", { className: "auto", style: { width: (ts.totalMins ? ts.autoMins / ts.totalMins * 100 : 0) + "%" } }),
                  R.createElement("span", { className: "assist", style: { width: (ts.totalMins ? ts.assistMins / ts.totalMins * 100 : 0) + "%" } })))),
            R.createElement("div", { className: "la-kpi-sec-h" }, R.createElement(Icon, { name: "function-square", size: 14 }), " How it's proven"),
            R.createElement("div", { className: "la-formula" }, "Σ (records_affected × baseline_task_minutes) ÷ 60 = hours saved"),
            R.createElement("p", { className: "la-method" }, "Each completed Loraa activity is credited the configured baseline time a person would spend on that task type, multiplied by the records it touched. Only successful executions count — recommendations and failures are excluded. Baselines are org-configurable, so the figure is auditable, not invented."),
            R.createElement("div", { className: "la-kpi-sec-h" }, R.createElement(Icon, { name: "layers", size: 14 }), " By activity type"),
            R.createElement("div", { className: "la-ts-table" },
              R.createElement("div", { className: "la-ts-th" }, R.createElement("span", null, "Activity type"), R.createElement("span", null, "Mode"), R.createElement("span", null, "Count"), R.createElement("span", null, "Minutes")),
              ts.typeRows.map((r, i) => R.createElement("div", { key: i, className: "la-ts-tr" },
                R.createElement("span", null, r.cat),
                R.createElement("span", null, R.createElement("span", { className: "pill " + (r.mode === "automatic" ? "ok" : r.mode === "approval" ? "warn" : "info") }, r.mode)),
                R.createElement("span", null, r.count),
                R.createElement("span", { className: "la-ts-min" }, Math.round(r.mins))))),
            R.createElement("div", { className: "la-note" }, R.createElement(Icon, { name: "shield-check", size: 13 }), " ", ts.count, " successful activities · ", ts.totalMins, " minutes · reproducible from stored activity records."));
        } else {
          const blurb = m.label === "Total AI activities" ? "Every observation, recommendation and executed action Loraa logged in the period." : m.label === "Automated" ? "Actions Loraa completed fully automatically, with no human step required." : m.label === "Recommendations" ? "Suggestions Loraa surfaced for a human to accept or dismiss." : m.label === "Awaiting approval" ? "Actions Loraa prepared but held for an authorized reviewer to approve." : "Executions that failed or were reversed — preserved with their error state for audit.";
          body = R.createElement("div", { className: "la-kpimodal-body" },
            R.createElement("div", { className: "la-kpimodal-hero" }, R.createElement("div", { className: "la-kpimodal-value" }, m.value)),
            R.createElement("p", { className: "la-method" }, blurb),
            R.createElement("div", { className: "la-note" }, R.createElement(Icon, { name: "info", size: 13 }), " Open the Loraa Activity list below and filter by this state to see every underlying record."));
        }
        const foot = R.createElement("div", { className: "aud-drawer-foot" },
          ts ? R.createElement("button", { className: "btn secondary", onClick: () => { const blob = new Blob([JSON.stringify({ metric: "Hours saved", hours: ts.hours, totalMinutes: ts.totalMins, automationMinutes: ts.autoMins, aiAssistMinutes: ts.assistMins, byActivityType: ts.typeRows, successfulActivities: ts.count }, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "loraa-time-saved.json"; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); try { window.__toast && window.__toast("Time-saved proof exported"); } catch (e) {} } }, R.createElement(Icon, { name: "download", size: 15 }), " Export proof") : null,
          R.createElement("button", { className: "btn primary", onClick: () => setMetricSel(null) }, "Close"));
        return R.createElement("div", { className: "aud-drawer-scrim la-kpimodal-scrim", onMouseDown: (e) => { if (e.target === e.currentTarget) setMetricSel(null); } },
          R.createElement("div", { className: "la-kpimodal", role: "dialog", "aria-label": m.label + " detail" }, head, body, foot));
      })()));
  }

  window.LoraaAnalytics = LoraaAnalytics;
})();
