/* ============================================================
   AFTERWAVE — DASHBOARD (contract)  (window.DASH)
   Overview derived from the list + workspace endpoints. No
   invented metrics: rollups are reach/backlash/decision counts.
   ============================================================ */
(function () {
  "use strict";
  const { useState, useEffect } = React;
  const API = window.API, UI = window.UIX;
  const h = React.createElement;
  const k = API.fmt.k;

  function Stat({ label, value, icon, sub }) {
    return h("div", { className: "card stat" },
      h("div", { className: "sl" }, h("span", { className: "eyebrow" }, label), h("span", { style: { color: "var(--ink-3)" } }, h(UI.Icon, { name: icon, size: 15 }))),
      h("div", { className: "sv" }, value),
      sub ? h("div", { className: "sd" }, h("span", { className: "flat" }, sub)) : null);
  }

  function Row({ item, onOpen }) {
    const failed = item.status === "failed";
    const bl = item.aggregate ? item.aggregate.overall.backlash.level : null;
    const reach = item.aggregate ? item.aggregate.overall.reach.value : null;
    return h("div", { className: "lrow", onClick: () => onOpen(item.run_id), role: "button", tabIndex: 0, dir: item.artifact.lang === "ar" ? "rtl" : "ltr" },
      h("div", { className: "th" }, h(UI.Icon, { name: UI.TYPE_ICON[cap(item.artifact.type)] || "doc", size: 16 })),
      h("div", { style: { flex: 1, minWidth: 0 } }, h("div", { className: "rt" }, item.artifact.caption),
        h("div", { className: "rc" }, item.platforms.map((p) => (API.PLATFORMS.find((x) => x.id === p) || {}).label).join(" · "))),
      h("div", { className: "num", style: { fontSize: 13, color: "var(--ink-2)", minWidth: 46, textAlign: "right" } }, failed ? "—" : k(reach)),
      failed ? h("span", { className: "badge", "data-tone": "neg" }, h("span", { className: "g" }), "failed")
        : h("span", { className: "badge", "data-tone": bl === "high" ? "neg" : bl === "moderate" ? "warn" : bl === "low" ? "pos" : "ok" }, h("span", { className: "g" }), "backlash " + bl),
      h("div", { style: { minWidth: 70, textAlign: "right" } }, item.decision ? h("span", { className: "chip plain", style: { fontSize: 9.5 } }, item.decision) : h("span", { className: "dim-2 eyebrow", style: { fontSize: 8.5 } }, failed ? "error" : "no decision")));
  }
  const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);

  function Dashboard({ onOpen, onNew, workspace }) {
    const [items, setItems] = useState(null);
    useEffect(() => { let on = true; API.listPredictions().then((r) => on && setItems(r.items)); return () => on = false; }, []);
    const done = items ? items.filter((i) => i.status !== "failed") : [];
    const flagged = done.filter((i) => ["moderate", "high"].includes(i.aggregate.overall.backlash.level)).length;
    const published = done.filter((i) => i.decision === "publish").length;
    const avgReach = done.length ? Math.round(done.reduce((a, i) => a + i.aggregate.overall.reach.value, 0) / done.length) : 0;
    return h("div", { className: "wrap wrap-wide" },
      h("div", { className: "phead" },
        h("div", null, h("div", { className: "eyebrow" }, "workspace · " + (workspace ? workspace.name.toLowerCase() : "meridian studio")),
          h("h1", null, "Welcome back, Sarah"),
          h("div", { className: "sub" }, "Your most recent run flagged " + flagged + " for backlash. Here's the workspace overview.")),
        h("div", { className: "phead-actions" }, h("button", { className: "btn pill", onClick: onNew }, h(UI.Icon, { name: "play", size: 13 }), "New Simulation"))),
      h("div", { className: "grid g4", style: { marginBottom: 16 } },
        h(Stat, { label: "Predictions", value: items ? items.length : "—", icon: "bars", sub: "this workspace" }),
        h(Stat, { label: "Avg. reach", value: items ? k(avgReach) : "—", icon: "up", sub: "across completed runs" }),
        h(Stat, { label: "Flagged for backlash", value: items ? flagged : "—", icon: "alert", sub: "moderate or high" }),
        h(Stat, { label: "Marked publish", value: items ? published : "—", icon: "check", sub: "decisions recorded" })),
      h("div", { className: "card" },
        h("div", { className: "card-h" }, h("span", { className: "t" }, "Recent runs", h("small", null, "click a run to open its consequence report")),
          h("button", { className: "hint btn ghost sm", onClick: () => onOpen(null, "history") }, "View all")),
        items ? h("div", { className: "rows", style: { marginTop: 8 } }, items.map((it) => h(Row, { key: it.run_id, item: it, onOpen })))
          : h("div", { style: { padding: 18, display: "grid", gap: 10 } }, [0, 1, 2, 3].map((i) => h("div", { key: i, className: "skel", style: { height: 48 } })))));
  }

  window.DASH = { Dashboard };
})();
