/* ============================================================
   AFTERWAVE — MISC  (window.MISC)
   History (list §2) · Settings (workspace) · Login · Compare ·
   shared state blocks (skeleton, typed error, failed, empty).
   ============================================================ */
(function () {
  "use strict";
  const { useState, useEffect } = React;
  const API = window.API, UI = window.UIX, RVZ = window.RVZ;
  const h = React.createElement;
  const k = API.fmt.k;
  const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);

  /* ---------- shared states ---------- */
  function ReportSkeleton() {
    return h("div", { className: "wrap wrap-wide" },
      h("div", { className: "skel", style: { width: 90, height: 28, marginBottom: 18, borderRadius: 8 } }),
      h("div", { className: "skel", style: { width: "60%", height: 50, marginBottom: 12 } }),
      h("div", { className: "skel", style: { width: 280, height: 16, marginBottom: 28 } }),
      h("div", { className: "grid g4", style: { marginBottom: 16 } }, [0, 1, 2, 3].map((i) => h("div", { key: i, className: "skel", style: { height: 116 } }))),
      h("div", { className: "grid", style: { gridTemplateColumns: "1.5fr 1fr" } }, [0, 1].map((i) => h("div", { key: i, className: "skel", style: { height: 260 } }))));
  }
  function ErrorState({ error, onRetry, onBack }) {
    return h("div", { className: "wrap" }, h("div", { style: { padding: "70px 0" } }, h("div", { className: "retry-box" },
      h("div", { style: { width: 46, height: 46, margin: "0 auto 14px", borderRadius: 12, background: "var(--neg-bg)", color: "var(--neg-ink)", display: "grid", placeItems: "center" } }, h(UI.Icon, { name: "alert", size: 22 })),
      h("h3", { style: { margin: "0 0 6px", fontSize: 18, fontWeight: 600 } }, "Couldn't load this report"),
      h("p", { className: "dim", style: { margin: "0 0 18px", fontSize: 13.5 } }, (error && error.message) || "The request failed. This is a transient error — try again."),
      h("div", { style: { display: "flex", gap: 8, justifyContent: "center" } }, h("button", { className: "btn sm", onClick: onRetry }, "Retry"), h("button", { className: "btn ghost sm", onClick: onBack }, "Back")))));
  }
  function FailedRun({ report, onRetry, onBack }) {
    return h("div", { className: "wrap" },
      h("button", { className: "btn ghost sm", onClick: onBack, style: { marginBottom: 18 } }, "← Back"),
      h("div", { className: "rpt-eyebrow" }, "consequence report", h("span", { className: "dot" }, "·"), report.run_id, h("span", { className: "dot" }, "·"), h("span", { className: "pill", "data-st": "failed" }, "failed")),
      h("h1", { className: "rpt-title", style: { marginBottom: 24 } }, report.artifact.caption),
      h("div", { className: "notice", "data-kind": "error", style: { maxWidth: 620 } },
        h("span", { className: "g", style: { width: 10, height: 10, borderRadius: "50%", background: "var(--neg)", marginTop: 3 } }),
        h("div", null, h("strong", null, "Run failed during " + report.error.stage + "."),
          h("p", { style: { margin: "6px 0 14px", color: "#7a3a2a" } }, report.error.message),
          report.error.retryable ? h("button", { className: "btn sm", onClick: () => onRetry(report) }, "Retry run") : null)));
  }

  /* ---------- HISTORY ---------- */
  function History({ onOpen, onNew }) {
    const [items, setItems] = useState(null);
    const [q, setQ] = useState(""); const [pf, setPf] = useState(""); const [bl, setBl] = useState(""); const [dc, setDc] = useState("");
    useEffect(() => { let on = true; API.listPredictions({ platform: pf, backlash: bl, decision: dc }).then((r) => on && setItems(r.items)); return () => on = false; }, [pf, bl, dc]);
    const rows = (items || []).filter((r) => !q || r.artifact.caption.toLowerCase().includes(q.toLowerCase()));
    const sel = (v, set, opts, ph) => h("select", { className: "input", style: { width: "auto" }, value: v, onChange: (e) => set(e.target.value) }, h("option", { value: "" }, ph), opts.map((o) => h("option", { key: o[0], value: o[0] }, o[1])));
    return h("div", { className: "wrap wrap-wide" },
      h("div", { className: "phead" }, h("div", null, h("div", { className: "eyebrow" }, "history"), h("h1", { style: { fontFamily: "var(--sans)", fontWeight: 600, fontSize: 27 } }, "Run library"), h("div", { className: "sub" }, (items ? items.length : "…") + " predictions")),
        h("div", { className: "phead-actions" }, h("button", { className: "btn ghost sm" }, h(UI.Icon, { name: "download", size: 13 }), "Export CSV"), h("button", { className: "btn pill", onClick: onNew }, h(UI.Icon, { name: "play", size: 13 }), "New Simulation"))),
      h("div", { className: "card", style: { padding: 14, marginBottom: 16, display: "flex", gap: 10, flexWrap: "wrap" } },
        h("div", { style: { position: "relative", flex: "1 1 240px" } }, h("span", { style: { position: "absolute", left: 12, top: 11, color: "var(--ink-3)" } }, h(UI.Icon, { name: "search", size: 15 })), h("input", { className: "input", placeholder: "Search captions…", value: q, onChange: (e) => setQ(e.target.value), style: { paddingLeft: 36 } })),
        sel(pf, setPf, API.PLATFORMS.map((p) => [p.id, p.label]), "All platforms"),
        sel(bl, setBl, API.LEVELS.map((l) => [l, l]), "All backlash"),
        sel(dc, setDc, [["publish", "publish"], ["edit", "edit"], ["kill", "kill"]], "All decisions")),
      !items ? h("div", { className: "card", style: { padding: 18, display: "grid", gap: 10 } }, [0, 1, 2, 3, 4].map((i) => h("div", { key: i, className: "skel", style: { height: 44 } })))
        : rows.length ? h("div", { className: "card", style: { padding: "6px 8px" } }, h("table", { className: "tbl" },
          h("thead", null, h("tr", null, ["Artifact", "Platforms", "Type", "Reach", "Backlash", "Decision", "Date"].map((c, i) => h("th", { key: i, style: c === "Reach" ? { textAlign: "right" } : null }, c)))),
          h("tbody", null, rows.map((r) => {
            const failed = r.status === "failed", lv = r.aggregate ? r.aggregate.overall.backlash.level : null;
            return h("tr", { key: r.run_id, onClick: () => onOpen(r.run_id), dir: r.artifact.lang === "ar" ? "rtl" : "ltr" },
              h("td", { className: "rt", style: { maxWidth: 280, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, r.artifact.caption),
              h("td", null, h("div", { style: { display: "flex", gap: 4 } }, r.platforms.map((p) => h("span", { key: p, className: "chip plain", style: { fontSize: 9 } }, (API.PLATFORMS.find((x) => x.id === p) || {}).label)))),
              h("td", { className: "dim" }, cap(r.artifact.type)),
              h("td", { className: "num", style: { textAlign: "right" } }, failed ? "—" : k(r.aggregate.overall.reach.value)),
              h("td", null, failed ? h("span", { className: "badge", "data-tone": "neg" }, h("span", { className: "g" }), "failed") : h("span", { className: "badge", "data-tone": lv === "high" ? "neg" : lv === "moderate" ? "warn" : lv === "low" ? "pos" : "ok" }, h("span", { className: "g" }), lv)),
              h("td", null, r.decision ? h("span", { className: "chip plain", style: { fontSize: 9.5 } }, r.decision) : h("span", { className: "dim-2" }, "—")),
              h("td", { className: "dim num", style: { fontSize: 12 } }, API.fmt.date(r.created_at)));
          }))))
          : h("div", { className: "card" }, h("div", { className: "empty" }, h("div", { className: "ei" }, h(UI.Icon, { name: "search", size: 20 })), h("h3", null, "No runs match"), h("p", null, "Try clearing a filter or adjusting your search."))));
  }

  /* ---------- SETTINGS ---------- */
  function Settings({ workspace }) {
    const [tab, setTab] = useState("General");
    const ws = workspace || { name: "Meridian Studio", members: [], usage: { used: 6, limit: 10 } };
    return h("div", { className: "wrap", style: { maxWidth: 860 } },
      h("div", { className: "phead" }, h("div", null, h("div", { className: "eyebrow" }, "settings"), h("h1", { style: { fontFamily: "var(--sans)", fontWeight: 600, fontSize: 27 } }, "Workspace"), h("div", { className: "sub" }, "Tenant: " + ws.name + " · your role: owner"))),
      h("div", { className: "tabs", style: { marginBottom: 22 } }, ["General", "Members", "Billing", "API"].map((t) => h("button", { key: t, "data-on": tab === t, onClick: () => setTab(t) }, t))),
      tab === "General" ? h("div", { className: "card card-pad" },
        h("div", { className: "field" }, h("label", null, "Workspace name"), h("input", { className: "input", defaultValue: ws.name })),
        h("div", { className: "field" }, h("label", null, "Default platforms"), h("div", { style: { display: "flex", gap: 6 } }, API.PLATFORMS.map((p) => h("span", { key: p.id, className: "chip plain" }, p.label)))),
        h("div", { className: "field", style: { margin: 0 } }, h("label", null, "Monthly simulations"), h("div", { className: "usage", style: { maxWidth: 280 } }, h("div", { className: "bar" }, h("i", { style: { width: (ws.usage.used / ws.usage.limit * 100) + "%" } })), h("div", { className: "eyebrow", style: { marginTop: 7 } }, ws.usage.used + " of " + ws.usage.limit + " used"))),
        h("div", { style: { display: "flex", justifyContent: "flex-end", marginTop: 16 } }, h("button", { className: "btn" }, "Save changes")))
      : tab === "Members" ? h("div", { className: "card" }, h("div", { className: "card-h" }, h("span", { className: "t" }, "Members"), h("button", { className: "btn ghost sm", style: { marginLeft: "auto" } }, "Invite")),
          (ws.members || []).map((m, i) => h("div", { key: i, style: { display: "flex", alignItems: "center", gap: 12, padding: "13px 18px", borderTop: "1px solid var(--line)" } }, h("span", { className: "acct", style: { width: 28, height: 28, fontSize: 11, borderRadius: "50%", background: "var(--ink)", color: "var(--bg)", display: "grid", placeItems: "center", fontFamily: "var(--mono)" } }, m.initials), h("span", { style: { flex: 1, fontSize: 13.5, fontWeight: 500 } }, m.name), h("span", { className: "eyebrow" }, m.role))))
      : h("div", { className: "card" }, h("div", { className: "soon", style: { margin: 18 } }, h("span", { className: "tag" }, "section"), h("strong", { style: { color: "var(--ink-2)", fontWeight: 600 } }, tab), h("p", { style: { margin: 0, fontSize: 12.5 } }, "Part of the full product."))));
  }

  /* ---------- LOGIN ---------- */
  function Login({ onLogin }) {
    const [mode, setMode] = useState("signin");
    const [email, setEmail] = useState("");
    const [pw, setPw] = useState("");
    const [name, setName] = useState("");
    const [ws, setWs] = useState("");
    const [err, setErr] = useState("");
    const [info, setInfo] = useState("");
    const [busy, setBusy] = useState(false);
    const signup = mode === "signup";

    const submit = async (e) => {
      e.preventDefault(); setErr(""); setInfo(""); setBusy(true);
      if (signup) {
        const r = await window.AWAuth.signUp(email, pw, name, ws);
        setBusy(false);
        if (!r.ok) return setErr(r.error || "Could not create account.");
        if (r.needConfirm) { setMode("signin"); setInfo("Account created. Check your email to confirm, then sign in."); return; }
        onLogin();
      } else {
        const r = await window.AWAuth.signIn(email, pw);
        setBusy(false);
        if (!r.ok) return setErr(r.error || "Sign-in failed.");
        if (r.isAdmin) { await window.AWAuth.signOut(); return setErr("This is an operator account — use the admin console."); }
        onLogin();
      }
    };

    return h("div", { style: { minHeight: "100vh", display: "grid", placeItems: "center", padding: 24 } },
      h("div", { style: { width: "100%", maxWidth: 384 } },
        h("div", { style: { display: "flex", alignItems: "center", gap: 10, justifyContent: "center", marginBottom: 26 } }, h(UI.Mark, { size: 24 }), h("b", { style: { fontSize: 20, fontWeight: 600, letterSpacing: "-.02em" } }, "afterwave")),
        h("div", { className: "card", style: { padding: 28 } },
          h("div", { className: "eyebrow", style: { marginBottom: 4 } }, signup ? "create account" : "sign in"),
          h("h1", { style: { margin: "0 0 4px", fontSize: 20, fontWeight: 600 } }, signup ? "Create your workspace" : "Welcome back"),
          h("p", { className: "dim", style: { marginTop: 0, marginBottom: 20, fontSize: 13 } }, signup ? "Set up a workspace to run predictions." : "Sign in to your workspace to run predictions."),
          info ? h("div", { className: "notice", "data-kind": "info", style: { marginBottom: 16, fontSize: 12.5 } }, h("span", { className: "g", style: { width: 9, height: 9, borderRadius: "50%", background: "var(--pos, #2a8)" } }), h("span", null, info)) : null,
          err ? h("div", { style: { color: "var(--neg-ink)", fontSize: 12.5, marginBottom: 14 } }, err) : null,
          h("form", { onSubmit: submit },
            signup ? h("div", { className: "field" }, h("label", null, "Your name"), h("input", { className: "input", value: name, onChange: (e) => setName(e.target.value), required: true })) : null,
            signup ? h("div", { className: "field" }, h("label", null, "Workspace name"), h("input", { className: "input", value: ws, onChange: (e) => setWs(e.target.value), placeholder: "e.g. Meridian Studio", required: true })) : null,
            h("div", { className: "field" }, h("label", null, "Work email"), h("input", { className: "input", type: "email", value: email, onChange: (e) => setEmail(e.target.value), required: true, autoComplete: "username" })),
            h("div", { className: "field" }, h("label", null, "Password"), h("input", { className: "input", type: "password", value: pw, onChange: (e) => setPw(e.target.value), required: true, minLength: 6, autoComplete: signup ? "new-password" : "current-password" })),
            h("button", { className: "btn", type: "submit", disabled: busy, style: { width: "100%", justifyContent: "center", marginTop: 4, opacity: busy ? 0.7 : 1 } }, busy ? "Please wait…" : (signup ? "Create account" : "Sign in")))),
        h("div", { style: { display: "flex", justifyContent: "space-between", marginTop: 16, fontSize: 12.5, color: "var(--ink-2)", padding: "0 4px" } },
          h("button", { onClick: () => { setErr(""); setInfo(""); setMode(signup ? "signin" : "signup"); }, style: { border: "none", background: "none", color: "var(--ink-2)", fontSize: 12.5, cursor: "pointer", padding: 0 } }, signup ? "← Have an account? Sign in" : "Create an account →"),
          h("a", { href: "../index.html", style: { color: "var(--ink-3)" } }, "afterwave.org"))));
  }

  /* ---------- COMPARE ---------- */
  function Compare({ initialA, onOpen }) {
    const [items, setItems] = useState(null);
    const [aId, setA] = useState(initialA || "run_8f3a");
    const [bId, setB] = useState("run_5c20");
    const [A, setAR] = useState(null); const [B, setBR] = useState(null);
    useEffect(() => { API.listPredictions().then((r) => setItems(r.items.filter((x) => x.status !== "failed"))); }, []);
    useEffect(() => { API.getReport(aId).then(setAR); }, [aId]);
    useEffect(() => { API.getReport(bId).then(setBR); }, [bId]);
    if (!items || !A || !B) return h("div", { className: "wrap" }, h("div", { className: "skel", style: { height: 300, marginTop: 30 } }));
    const sel = (v, set) => h("select", { className: "input", style: { width: "auto", fontWeight: 500, maxWidth: 260 }, value: v, onChange: (e) => set(e.target.value) }, items.map((it) => h("option", { key: it.run_id, value: it.run_id }, it.artifact.caption)));
    const oa = A.aggregate.overall, ob = B.aggregate.overall;
    const blScore = { none: 0, low: .33, moderate: .66, high: 1 };
    const rows = [["Predicted reach", oa.reach.value, ob.reach.value, k, false], ["Engagement duration", oa.engagement_duration_h.value, ob.engagement_duration_h.value, (x) => Math.round(x) + "h", false], ["Breakout probability", oa.breakout_probability.value, ob.breakout_probability.value, (x) => Math.round(x * 100) + "%", false], ["Backlash score", oa.backlash.score.value, ob.backlash.score.value, (x) => x.toFixed(2), true]];
    const Delta = ({ a, b, fmt, invert }) => { const d = a - b; if (Math.abs(d) < 1e-9) return h("span", { className: "dim-2 num", style: { fontSize: 11 } }, "· same"); const better = invert ? d < 0 : d > 0; return h("span", { className: "num", style: { fontSize: 12, fontWeight: 500, color: better ? "var(--pos-ink)" : "var(--neg-ink)" } }, (d > 0 ? "▲ " : "▼ ") + fmt(Math.abs(d))); };
    return h("div", { className: "wrap wrap-wide" },
      h("div", { className: "phead" }, h("div", null, h("div", { className: "eyebrow" }, "compare"), h("h1", { style: { fontFamily: "var(--sans)", fontWeight: 600, fontSize: 27 } }, "Compare variants"), h("div", { className: "sub" }, "Which variant is lower-risk and higher-reach — and why."))),
      h("div", { style: { display: "flex", gap: 22, marginBottom: 20, flexWrap: "wrap" } }, h("div", { style: { display: "flex", gap: 8, alignItems: "center" } }, h("span", { className: "eyebrow" }, "A"), sel(aId, setA)), h("div", { style: { display: "flex", gap: 8, alignItems: "center" } }, h("span", { className: "eyebrow" }, "B"), sel(bId, setB))),
      h("div", { className: "card", style: { marginBottom: 16, overflow: "hidden" } }, h("table", { className: "tbl" },
        h("thead", null, h("tr", null, ["Metric", "A", "B", "Difference"].map((c, i) => h("th", { key: i }, c)))),
        h("tbody", null, rows.map((m) => h("tr", { key: m[0], style: { cursor: "default" } }, h("td", { className: "rt" }, m[0]), h("td", { className: "num" }, m[3](m[1])), h("td", { className: "num" }, m[3](m[2])), h("td", null, h(Delta, { a: m[1], b: m[2], fmt: m[3], invert: m[4] }))))),
        h("tbody", null, h("tr", { style: { cursor: "default" } }, h("td", { className: "rt" }, "Backlash level"), h("td", null, h("span", { className: "badge", "data-tone": oa.backlash.level === "high" ? "neg" : oa.backlash.level === "moderate" ? "warn" : "ok" }, h("span", { className: "g" }), oa.backlash.level)), h("td", null, h("span", { className: "badge", "data-tone": ob.backlash.level === "high" ? "neg" : ob.backlash.level === "moderate" ? "warn" : "ok" }, h("span", { className: "g" }), ob.backlash.level)), h("td", null, h(Delta, { a: blScore[oa.backlash.level], b: blScore[ob.backlash.level], fmt: (x) => x.toFixed(2), invert: true })))))),
      h("div", { className: "grid g2" }, [A, B].map((R, i) => h("div", { key: i, className: "card" }, h("div", { className: "card-h" }, h("span", { className: "t" }, (i ? "B" : "A") + " · decay")), h("div", { className: "card-b" }, h(RVZ.DecayCurve, { byPlatform: R.aggregate.by_platform, platforms: R.platforms, height: 170 }))))),
      h("div", { style: { display: "flex", gap: 10, marginTop: 16 } }, h("button", { className: "btn ghost", onClick: () => onOpen(aId) }, "Open A →"), h("button", { className: "btn ghost", onClick: () => onOpen(bId) }, "Open B →")));
  }

  window.MISC = { History, Settings, Login, Compare, ReportSkeleton, ErrorState, FailedRun };
})();
