/* ============================================================
   AFTERWAVE — REPORT (contract core)  (window.RPT)
   Editorial header · verdict band w/ CIs · per-platform · an
   unmissable backlash flag linking to drivers · 12-persona grid
   + drawer · content signal · video timeline (when video).
   Full RTL for Arabic artifacts. Predicted-silence state.
   ============================================================ */
(function () {
  "use strict";
  const { useState } = React;
  const U = window.AU, API = window.API, RVZ = window.RVZ, UI = window.UIX, PERS = window.PERS, TL = window.TL;
  const h = React.createElement;
  const k = API.fmt.k, pct = API.fmt.pct;

  function jumpTo(refEl) { if (!refEl) return; let pa = refEl.closest(".main") || refEl.parentElement; while (pa && pa.scrollHeight <= pa.clientHeight) pa = pa.parentElement; (pa || window).scrollTo({ top: refEl.offsetTop - 60, behavior: "smooth" }); }

  function VCell({ label, icon, value, unit, ci, domain, sub, flag, level }) {
    return h("div", { className: "vcell" + (flag ? " flag" : ""), "data-lv": level || "" },
      h("div", { className: "vl" }, h("span", { className: "eyebrow" }, label), h("span", { style: { color: "var(--ink-3)" } }, icon ? h(UI.Icon, { name: icon, size: 14 }) : null)),
      h("div", { className: "vv" }, value, unit ? h("small", null, unit) : null),
      ci ? h(RVZ.CIInline, { value: ci.v, ciArr: ci.arr, domain }) : null,
      ci && ci.arr ? h("div", { className: "ci-txt" }, "CI " + ci.fmt(ci.arr[0]) + "–" + ci.fmt(ci.arr[1]), ci.source ? h(UI.Prov, { source: ci.source }) : null) : sub);
  }

  function Report({ report, onBack, decision, onDecide, onCompare }) {
    const [openP, setOpenP] = useState(null);
    const [view, setView] = useState("report");
    const personasRef = React.useRef(null), backRef = React.useRef(null);
    const rtl = report.artifact.lang === "ar";
    const ov = report.aggregate.overall;
    const isVideo = report.artifact.type === "video" && report.timeline;
    const silence = ov.backlash.level === "none" && ov.reach.value < 4000;

    // sentiment split derived from personas[].reaction_lean (contract-faithful)
    const counts = { positive: 0, neutral: 0, negative: 0 };
    report.personas.forEach((p) => counts[p.reaction_lean]++);
    const tot = report.personas.length || 1;
    const net = (counts.positive - counts.negative) / tot;
    const overallLabel = net > 0.15 ? "Net Positive" : net < -0.1 ? "Net Negative" : "Mixed";

    const driverNames = ov.backlash.drivers.map((id) => (report.personas.find((p) => p.id === id) || {}).name).filter(Boolean);
    const platLabel = report.platforms.map((p) => (API.PLATFORMS.find((x) => x.id === p) || {}).label).join(" · ");
    const TABS = [["report", "Report"]]; if (isVideo) TABS.push(["timeline", "Video timeline"]);

    return h("div", { className: "wrap wrap-wide", dir: rtl ? "rtl" : "ltr", ref: backRef },
      h("button", { className: "btn ghost sm", onClick: onBack, style: { marginBottom: 18 } }, (rtl ? "→ " : "← ") + "Back"),
      // editorial header
      h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 20, flexWrap: "wrap" } },
        h("div", { style: { minWidth: 0, flex: 1 } },
          h("div", { className: "rpt-eyebrow" }, "consequence report", h("span", { className: "dot" }, "·"), report.run_id,
            h("span", { className: "dot" }, "·"), h("span", { className: "pill", "data-st": report.status }, report.status)),
          h("h1", { className: "rpt-title" }, report.artifact.caption),
          h("div", { className: "rpt-meta" }, [platLabel, report.personas.length + " personas", API.fmt.date(report.created_at), "completed in " + report.completed_in].join("  ·  "))),
        h("div", { style: { display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" } },
          h("div", { className: "tabs" }, [["publish", "Publish"], ["edit", "Edit"], ["kill", "Kill"]].map(([d, l]) => h("button", { key: d, "data-on": decision === d, onClick: () => onDecide(report.run_id, d) }, l))),
          h("button", { className: "btn ghost sm", onClick: () => onCompare(report.run_id) }, "Compare"),
          h("button", { className: "btn ghost sm pill", onClick: () => window.print() }, h(UI.Icon, { name: "export", size: 13 }), "Export PDF"))),
      h("div", { className: "rpt-rule" }),

      isVideo ? h("div", { className: "utabs" }, TABS.map(([id, l]) => h("button", { key: id, "data-on": view === id, onClick: () => setView(id) }, l))) : null,

      view === "timeline" && isVideo ? h(TL.VideoTimeline, { timeline: report.timeline, artifact: report.artifact }) :
      h(React.Fragment, null,
        silence ? h("div", { className: "silence-card", style: { marginBottom: 18 } },
          h("span", { className: "badge", "data-tone": "ok" }, h("span", { className: "g" }), "finding"),
          h("div", null, h("strong", null, "Predicted silence. "), h("span", { className: "dim" }, "Low reach with a tight interval and no backlash — a confident read, not an empty result."))) : null,

        // VERDICT BAND with CIs
        h("div", { className: "eyebrow", style: { marginBottom: 10 } }, "verdict"),
        h("div", { className: "verdict", style: { marginBottom: 26 } },
          h(VCell, { label: "predicted reach", icon: "up", value: k(ov.reach.value),
            ci: { v: ov.reach.value, arr: ov.reach.ci, fmt: k, source: ov.reach.source }, domain: [ov.reach.ci[0] * .8, ov.reach.ci[1] * 1.1] }),
          h(VCell, { label: "engagement duration", icon: "history", value: ov.engagement_duration_h.value, unit: "h",
            ci: { v: ov.engagement_duration_h.value, arr: ov.engagement_duration_h.ci, fmt: (x) => Math.round(x), source: ov.engagement_duration_h.source }, domain: [0, ov.engagement_duration_h.ci[1] * 1.4] }),
          h(VCell, { label: "breakout probability", icon: "bolt", value: pct(ov.breakout_probability.value),
            ci: { v: ov.breakout_probability.value, arr: ov.breakout_probability.ci, fmt: pct, source: ov.breakout_probability.source }, domain: [0, 1] }),
          // backlash — unmissable flag
          h("div", { className: "vcell flag", "data-lv": ov.backlash.level },
            h("div", { className: "vl" }, h("span", { className: "eyebrow" }, "backlash risk"), h("span", { style: { color: "var(--ink-3)" } }, h(UI.Icon, { name: "alert", size: 14 }))),
            h("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
              h("span", { className: "badge", "data-tone": ov.backlash.level === "high" ? "neg" : ov.backlash.level === "moderate" ? "warn" : ov.backlash.level === "low" ? "pos" : "ok" }, h("span", { className: "g" }), ov.backlash.level),
              h("span", { className: "num", style: { fontSize: 22, fontWeight: 500 } }, ov.backlash.score.value.toFixed(2))),
            driverNames.length ? h("div", { className: "vsub" }, "driven by ", h("button", { onClick: () => jumpTo(personasRef.current) }, driverNames.join(" & ")), rtl ? " ←" : " →") : h("div", { className: "vsub dim" }, "no single driver"))),

        // narrative-style row: left = signal-over-artifact, right = sentiment split
        h("div", { className: "grid", style: { gridTemplateColumns: "1.5fr 1fr", marginBottom: 16, alignItems: "stretch" } },
          h("div", { className: "card" },
            h("div", { className: "card-h" }, h("span", { className: "t" }, isVideo ? "Retention over time" : "Content signal", h("small", null, isVideo ? "predicted viewer retention" : "L1 linguistic & affective parse"))),
            h("div", { className: "card-b" }, isVideo
              ? h(React.Fragment, null, h(RVZ.Retention, { curve: report.timeline.retention_curve, duration: report.timeline.duration_s, height: 150 }),
                  h("button", { className: "btn ghost sm", style: { marginTop: 12 }, onClick: () => setView("timeline") }, "Open full timeline " + (rtl ? "←" : "→")))
              : h(ContentSignal, { signal: report.content_signal }))),
          h("div", { className: "card" },
            h("div", { className: "card-h" }, h("span", { className: "t" }, "Sentiment", h("small", null, "agent response split · by reaction lean"))),
            h("div", { className: "card-b" },
              h("div", { className: "split", style: { marginBottom: 16 } },
                [["positive", "pos"], ["neutral", "neu"], ["negative", "neg"]].map(([lean, t]) =>
                  h("div", { key: lean, className: "row" },
                    h("div", { className: "rl" }, h("span", { style: { textTransform: "capitalize" } }, lean), h("span", { className: "num dim" }, Math.round(counts[lean] / tot * 100) + "%")),
                    h("div", { className: "track " + t }, h("i", { style: { width: counts[lean] / tot * 100 + "%" } }))))),
              h("div", { style: { paddingTop: 14, borderTop: "1px solid var(--line)" } },
                h("div", { className: "eyebrow", style: { marginBottom: 4 } }, "overall signal"),
                h("div", { className: "rpt-title", style: { fontSize: 30, margin: 0, color: "var(--ink)" } }, overallLabel),
                h("div", { className: "dim", style: { fontSize: 12.5, marginTop: 6 } }, net > .15 ? "Sentiment skews favorable. Monitor backlash drivers before launch." : net < -.1 ? "Sentiment skews adverse — review the backlash drivers." : "Sentiment is mixed across the panel.")))) ),

        // PER-PLATFORM
        h("div", { className: "eyebrow", style: { margin: "4px 0 10px" } }, "per platform"),
        h("div", { className: "grid", style: { gridTemplateColumns: "1.2fr 1fr", marginBottom: 16, alignItems: "start" } },
          h("div", { className: "grid", style: { gridTemplateColumns: "repeat(" + report.platforms.length + ",1fr)", gap: 12 } },
            report.platforms.map((pid) => { const b = report.aggregate.by_platform[pid]; const p = API.PLATFORMS.find((x) => x.id === pid);
              return h("div", { key: pid, className: "card card-pad", style: { display: "grid", gap: 9 } },
                h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" } }, h("span", { style: { fontWeight: 600, fontSize: 13.5 } }, p.label), h("span", { className: "badge", "data-tone": b.backlash.level === "high" ? "neg" : b.backlash.level === "moderate" ? "warn" : b.backlash.level === "low" ? "pos" : "ok" }, h("span", { className: "g" }), b.backlash.level)),
                h("div", null, h("span", { className: "num", style: { fontSize: 22, fontWeight: 500 } }, k(b.reach.value)), h("span", { className: "dim-2", style: { fontSize: 11.5, marginInlineStart: 5 } }, "reach")),
                h("div", { className: "eyebrow", style: { display: "flex", justifyContent: "space-between" } }, h("span", null, "half-life"), h("span", { className: "num", style: { color: "var(--ink)" } }, b.decay_half_life_h + "h"))); })),
          h("div", { className: "card" }, h("div", { className: "card-h" }, h("span", { className: "t" }, "Engagement decay", h("small", null, "drawn from platform half-lives"))),
            h("div", { className: "card-b" }, h(RVZ.DecayCurve, { byPlatform: report.aggregate.by_platform, platforms: report.platforms, height: 190 })))),

        // PERSONAS
        h("div", { ref: personasRef, style: { display: "flex", alignItems: "center", justifyContent: "space-between", margin: "30px 0 12px", scrollMarginTop: 70 } },
          h("span", { className: "eyebrow" }, "audience · " + report.personas.length + " personas"),
          driverNames.length ? h("span", { className: "badge", "data-tone": "neg" }, h("span", { className: "g" }), driverNames.length + " backlash " + (driverNames.length === 1 ? "driver" : "drivers")) : null),
        h(PERS.PersonaGrid, { personas: report.personas, onOpen: setOpenP, drivers: ov.backlash.drivers }),

        // CONTENT hooks/entities
        h("div", { className: "card card-pad", style: { marginTop: 16 } },
          h("div", { className: "eyebrow", style: { marginBottom: 12 } }, "content signal · L1 parse"),
          h(ContentSignal, { signal: report.content_signal, full: true })),

        openP ? h(PERS.Drawer, { p: report.personas.find((x) => x.id === openP), onClose: () => setOpenP(null), rtl }) : null));
  }

  /* content signal: 5 L1 features w/ CI + source, hooks, entities */
  function ContentSignal({ signal, full }) {
    if (!signal) return h("div", { className: "dim", style: { fontSize: 13 } }, "No content signal for this artifact.");
    const feats = ["arousal", "valence", "concreteness", "readability", "sentiment"];
    return h("div", null,
      h("div", { style: { display: "grid", gap: 11 } }, feats.map((f) => {
        const m = signal[f]; if (!m) return null;
        return h("div", { key: f },
          h("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: 4, alignItems: "center" } },
            h("span", { style: { fontSize: 12.5, textTransform: "capitalize" } }, f, " ", h(UI.Prov, { source: m.source })),
            h("span", { className: "num", style: { fontSize: 11, color: "var(--ink-2)" } }, Math.round(m.value * 100))),
          h("div", { style: { position: "relative", height: 8, background: "var(--sunken)", borderRadius: 99 } },
            h("div", { style: { position: "absolute", left: 0, width: m.value * 100 + "%", top: 0, bottom: 0, background: U.gray(.35 + m.value * .5), borderRadius: 99 } }),
            m.ci ? h("div", { title: "CI", style: { position: "absolute", left: m.ci[0] * 100 + "%", width: (m.ci[1] - m.ci[0]) * 100 + "%", top: -2, bottom: -2, border: "1px solid var(--ink-3)", borderRadius: 99, opacity: .5 } }) : null));
      })),
      full ? h("div", { style: { display: "flex", gap: 24, flexWrap: "wrap", marginTop: 16 } },
        h("div", null, h("div", { className: "eyebrow", style: { marginBottom: 7 } }, "hooks"), h("div", { style: { display: "flex", gap: 6, flexWrap: "wrap" } }, signal.hooks.length ? signal.hooks.map((x, i) => h("span", { key: i, className: "chip plain" }, x)) : h("span", { className: "dim-2", style: { fontSize: 12 } }, "none detected"))),
        h("div", null, h("div", { className: "eyebrow", style: { marginBottom: 7 } }, "entities"), h("div", { style: { display: "flex", gap: 6, flexWrap: "wrap" } }, signal.entities.map((x, i) => h("span", { key: i, className: "chip plain" }, x))))) : null);
  }

  window.RPT = { Report };
})();
