/* ============================================================
   AFTERWAVE — REPORT VIZ  (window.RVZ)
   Contract-specific: CI distribution, platform decay, retention
   curve, stacked timeline tracks with playhead + markers.
   ============================================================ */
(function () {
  "use strict";
  const U = window.AU;
  const h = React.createElement;
  const SENT = { pos: "#5d8a6b", neu: "#9a9081", neg: "#bd6149" };

  /* inline CI distribution: point estimate + interval inside a domain */
  function CIInline({ value, ciArr, domain, height = 30 }) {
    const [ref, { w }] = U.useSize();
    const W = w || 240, H = height, pad = 1;
    const [d0, d1] = domain;
    const sx = (v) => pad + ((v - d0) / (d1 - d0 || 1)) * (W - pad * 2);
    const lo = ciArr ? ciArr[0] : value, hi = ciArr ? ciArr[1] : value;
    const baseY = H - 8;
    return h("div", { ref, style: { width: "100%" } },
      h("svg", { width: W, height: H, style: { display: "block", overflow: "visible" } },
        h("line", { x1: pad, y1: baseY, x2: W - pad, y2: baseY, stroke: "var(--line-2)", strokeWidth: 1 }),
        ciArr ? h("rect", { x: sx(lo), y: baseY - 4, width: Math.max(2, sx(hi) - sx(lo)), height: 8, rx: 4, fill: "var(--d1)" }) : null,
        ciArr ? h("line", { x1: sx(lo), y1: baseY - 6, x2: sx(lo), y2: baseY + 6, stroke: "var(--ink-3)", strokeWidth: 1 }) : null,
        ciArr ? h("line", { x1: sx(hi), y1: baseY - 6, x2: sx(hi), y2: baseY + 6, stroke: "var(--ink-3)", strokeWidth: 1 }) : null,
        h("line", { x1: sx(value), y1: baseY - 13, x2: sx(value), y2: baseY + 5, stroke: "var(--ink)", strokeWidth: 2 }),
        h("rect", { x: sx(value) - 3, y: baseY - 3, width: 6, height: 6, rx: 1, fill: "var(--ink)" })));
  }

  /* platform decay curves from half-lives */
  const DASH = { tiktok: "0", instagram: "6 4", x: "2 4" };
  function DecayCurve({ byPlatform, platforms, height = 200 }) {
    const [ref, { w }] = U.useSize();
    const W = w || 560, H = height, L = 36, R = 16, Tp = 14, B = 34, span = 72;
    const x = (t) => L + (t / span) * (W - L - R);
    const y = (v) => Tp + (1 - v) * (H - Tp - B);
    const PL = window.API.PLATFORMS.filter((p) => platforms.includes(p.id));
    return h("div", { ref, style: { width: "100%" } },
      h("svg", { width: W, height: H, style: { display: "block" }, role: "img", "aria-label": "engagement decay by platform" },
        [0, .5, 1].map((g, i) => h("g", { key: i },
          h("line", { x1: L, y1: y(g), x2: W - R, y2: y(g), stroke: "var(--line)", strokeWidth: 1 }),
          h("text", { x: L - 7, y: y(g) + 3, textAnchor: "end", className: "num", fontSize: 9, fill: "var(--ink-3)" }, Math.round(g * 100)))),
        [0, 24, 48, 72].map((t, i) => h("text", { key: i, x: x(t), y: H - 16, textAnchor: "middle", className: "num", fontSize: 9, fill: "var(--ink-3)" }, t === 0 ? "0h" : t + "h")),
        h("text", { x: (L + W - R) / 2, y: H - 3, textAnchor: "middle", fontSize: 9, fill: "var(--ink-3)", style: { fontFamily: "var(--mono)", letterSpacing: ".06em" } }, "HOURS AFTER PUBLISH"),
        PL.map((pl) => {
          const half = byPlatform[pl.id].decay_half_life_h;
          const pts = []; for (let t = 0; t <= span; t += 2) pts.push([t, Math.exp(-t / half)]);
          const line = pts.map((p, i) => (i ? "L" : "M") + x(p[0]).toFixed(1) + " " + y(p[1]).toFixed(1)).join(" ");
          return h("g", { key: pl.id },
            h("path", { d: line, fill: "none", stroke: "var(--ink)", strokeWidth: 1.7, strokeDasharray: DASH[pl.id], opacity: .9 }),
            h("circle", { cx: x(half), cy: y(Math.exp(-1)), r: 2.6, fill: "var(--ink)" }));
        })),
      h("div", { className: "legend", style: { marginTop: 8 } }, PL.map((pl) => h("span", { key: pl.id, style: { display: "inline-flex", alignItems: "center", gap: 7 } },
        h("svg", { width: 22, height: 8 }, h("line", { x1: 0, y1: 4, x2: 22, y2: 4, stroke: "var(--ink)", strokeWidth: 1.7, strokeDasharray: DASH[pl.id] })),
        pl.label, h("span", { className: "dim-2" }, "t½ " + byPlatform[pl.id].decay_half_life_h + "h")))));
  }

  /* 6-axis neural radar with optional second (segment) overlay */
  function NeuralRadar({ signals, size = 210, overlay }) {
    const keys = window.API.NEURAL_KEYS, lab = window.API.NEURAL_LABEL, n = keys.length;
    const cx = size / 2, cy = size / 2, Rr = size * 0.31;
    const ang = (i) => -Math.PI / 2 + (i / n) * Math.PI * 2;
    const pt = (i, v) => [cx + Math.cos(ang(i)) * Rr * v, cy + Math.sin(ang(i)) * Rr * v];
    const poly = (src, style) => h("polygon", { points: keys.map((kk, i) => pt(i, (src[kk] || { value: 0 }).value).join(",")).join(" "),
      fill: style.fill, fillOpacity: style.fo, stroke: "var(--ink)", strokeWidth: 1.5, strokeDasharray: style.dash || "0" });
    return h("svg", { width: size, height: size, role: "img", "aria-label": "neural signals" },
      [.33, .66, 1].map((g, gi) => h("polygon", { key: gi, points: keys.map((_, i) => pt(i, g).join(",")).join(" "), fill: "none", stroke: "var(--line)", strokeWidth: 1 })),
      keys.map((_, i) => h("line", { key: i, x1: cx, y1: cy, x2: pt(i, 1)[0], y2: pt(i, 1)[1], stroke: "var(--line)", strokeWidth: 1 })),
      overlay ? poly(overlay, { fill: "none", fo: 0, dash: "4 3" }) : null,
      poly(signals, { fill: "var(--d2)", fo: .5 }),
      keys.map((kk, i) => { const [px, py] = pt(i, 1.2); return h("text", { key: kk, x: px, y: py + 3, textAnchor: px < cx - 4 ? "end" : px > cx + 4 ? "start" : "middle", fontSize: 8.5, fill: "var(--ink-2)" }, lab[kk]); }));
  }

  /* retention curve (area) */
  function Retention({ curve, height = 90, onHover, playT, duration }) {
    const [ref, { w }] = U.useSize();
    const W = w || 560, H = height, L = 4, R = 4, Tp = 6, B = 4;
    const x = (t) => L + (t / duration) * (W - L - R);
    const y = (v) => Tp + (1 - v) * (H - Tp - B);
    const line = curve.map((p, i) => (i ? "L" : "M") + x(p.t).toFixed(1) + " " + y(p.value).toFixed(1)).join(" ");
    return h("div", { ref, style: { width: "100%", position: "relative" } },
      h("svg", { width: W, height: H, style: { display: "block" } },
        h("path", { d: line + ` L ${x(duration)} ${y(0)} L ${x(0)} ${y(0)} Z`, fill: "var(--d0)" }),
        h("path", { d: line, fill: "none", stroke: "var(--ink)", strokeWidth: 1.6 })),
      playT != null ? h("div", { className: "tl-playhead", style: { left: x(playT) + "px" } }) : null);
  }

  window.RVZ = { CIInline, DecayCurve, NeuralRadar, Retention, SENT, DASH };
})();
