/* ============================================================
   AFTERWAVE — VIDEO TIMELINE  (window.TL)
   Player + scrubbable stacked tracks (retention/drop-off,
   arousal/valence, share/stop, backlash risk) + labeled
   key-moment markers + clickable moment inspector + segment table.
   Driven entirely by the contract's timeline block.
   ============================================================ */
(function () {
  "use strict";
  const { useState, useRef } = React;
  const U = window.AU, RVZ = window.RVZ;
  const h = React.createElement;
  const SENT = RVZ.SENT;

  const TRACKS = [
    { id: "retention", label: "Retention / drop-off", pick: (s) => 1 + Math.min(0, s.predicted.retention_delta.value), tone: "ink", neg: (s) => s.predicted.retention_delta.value < -0.06 },
    { id: "arousal", label: "Arousal", pick: (s) => s.neural_signals.arousal.value, tone: "ink" },
    { id: "valence", label: "Valence", pick: (s) => s.neural_signals.valence.value, tone: "ink" },
    { id: "share", label: "Share impulse", pick: (s) => s.neural_signals.share_impulse.value, tone: "ink" },
    { id: "stop", label: "Scroll-stop", pick: (s) => s.neural_signals.scroll_stop.value, tone: "ink" },
    { id: "backlash", label: "Backlash risk", pick: (s) => s.backlash.score.value, tone: "neg" },
  ];

  function Track({ track, segments, duration, onPick, sel }) {
    const [ref, { w }] = U.useSize();
    const W = w || 600, H = 30;
    const x = (t) => (t / duration) * W;
    return h("div", { className: "tl-track" },
      h("div", { className: "tlabel" }, h("span", null, track.label)),
      h("div", { ref, style: { width: "100%", position: "relative", height: H, background: "var(--surface-2)", borderRadius: 5, overflow: "hidden", cursor: "pointer" } },
        segments.map((s, i) => {
          const v = U.clamp(track.pick(s), 0, 1);
          const isNeg = track.tone === "neg" || (track.neg && track.neg(s));
          const col = track.tone === "neg" ? SENT.neg : isNeg ? SENT.neg : U.gray(0.3 + v * 0.6);
          return h("div", { key: i, onClick: () => onPick(i),
            onMouseMove: (e) => U.T(e, `<b>${RVZ ? "" : ""}${track.label}</b> · ${s.t_start}–${s.t_end}s<br><span class='k'>value</span> ${(v * 100).toFixed(0)}%`), onMouseLeave: U.hideTip,
            style: { position: "absolute", left: x(s.t_start) + "px", width: (x(s.t_end) - x(s.t_start) - 1) + "px", bottom: 0, height: (8 + v * (H - 10)) + "px", background: col, opacity: sel === i ? 1 : .85, outline: sel === i ? "2px solid var(--ink)" : "none", outlineOffset: -2, borderRadius: "2px 2px 0 0" } });
        })));
  }

  function VideoTimeline({ timeline, artifact }) {
    const dur = timeline.duration_s;
    const [t, setT] = useState(0);
    const [sel, setSel] = useState(null);
    const segAt = (tt) => timeline.segments.findIndex((s) => tt >= s.t_start && tt < s.t_end);
    const curIdx = sel != null ? sel : Math.max(0, segAt(t));
    const seg = timeline.segments[curIdx];
    const pick = (i) => { setSel(i); setT((timeline.segments[i].t_start + timeline.segments[i].t_end) / 2); };
    const fmt = window.API.fmt.time;
    const rtl = artifact.lang === "ar";

    return h("div", null,
      // player + scrubber
      h("div", { className: "grid", style: { gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start", marginBottom: 16 } },
        h("div", null,
          h("div", { className: "player", style: { position: "relative" } },
            h("div", { style: { textAlign: "center" } }, h(window.UIX.Icon, { name: "video", size: 30 }), h("div", { style: { fontSize: 12, marginTop: 8, fontFamily: "var(--mono)" } }, "frame @ " + fmt(t))),
            h("div", { className: "scrubline", style: { left: (t / dur * 100) + "%" } }),
            seg && seg.flag ? h("div", { style: { position: "absolute", top: 12, left: 12 } }, h("span", { className: "seg-flag", "data-f": seg.flag }, seg.flag)) : null),
          h("div", { style: { display: "flex", alignItems: "center", gap: 12, margin: "12px 2px 0" } },
            h("span", { className: "num", style: { fontSize: 12, color: "var(--ink-2)", width: 40 } }, fmt(t)),
            h("input", { type: "range", min: 0, max: dur, step: .5, value: t, onChange: (e) => { setSel(null); setT(+e.target.value); }, style: { flex: 1 }, "aria-label": "scrub timeline" }),
            h("span", { className: "num", style: { fontSize: 12, color: "var(--ink-3)", width: 40, textAlign: "right" } }, fmt(dur)))),
        // moment inspector
        h("div", { className: "card card-pad" },
          h("div", { className: "eyebrow", style: { marginBottom: 10 } }, "moment inspector · " + seg.t_start + "–" + seg.t_end + "s"),
          h("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 12 } },
            seg.flag ? h("span", { className: "seg-flag", "data-f": seg.flag }, seg.flag) : h("span", { className: "chip plain", style: { fontSize: 9.5 } }, "steady"),
            h("span", { className: "badge", "data-tone": seg.backlash.level === "high" ? "neg" : seg.backlash.level === "moderate" ? "warn" : "ok" }, h("span", { className: "g" }), "backlash " + seg.backlash.level)),
          h("div", { style: { display: "grid", gap: 8 } }, ["arousal", "valence", "scroll_stop", "share_impulse"].map((kk) => {
            const v = seg.neural_signals[kk].value;
            return h("div", { key: kk, style: { display: "grid", gridTemplateColumns: "84px 1fr 30px", gap: 9, alignItems: "center" } },
              h("span", { style: { fontSize: 11.5 } }, window.API.NEURAL_LABEL[kk]),
              h("div", { style: { height: 7, background: "var(--sunken)", borderRadius: 99 } }, h("div", { style: { width: v * 100 + "%", height: "100%", background: kk === "valence" && v < .4 ? SENT.neg : "var(--d4)", borderRadius: 99 } })),
              h("span", { className: "num", style: { fontSize: 10.5, color: "var(--ink-2)", textAlign: "right" } }, Math.round(v * 100)));
          })),
          h("div", { style: { marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", fontSize: 12 } },
            h("span", { className: "dim" }, "predicted drop-off"),
            h("span", { className: "num", style: { color: seg.predicted.retention_delta.value < -.05 ? "var(--neg-ink)" : "var(--ink)" } }, Math.round(seg.predicted.retention_delta.value * 100) + "%")))),

      // retention overview with markers
      h("div", { className: "card card-pad", style: { marginBottom: 16 } },
        h("div", { className: "eyebrow", style: { marginBottom: 4 } }, "retention curve"),
        h("div", { style: { position: "relative" } },
          h(RVZ.Retention, { curve: timeline.retention_curve, duration: dur, playT: t, height: 92 }),
          // key-moment markers
          h("div", { style: { position: "relative", height: 26 } }, timeline.key_moments.map((m, i) =>
            h("div", { key: i, className: "tl-marker", "data-type": m.type, style: { left: (m.t / dur * 100) + "%" },
              onClick: () => pick(Math.max(0, segAt(m.t))),
              onMouseMove: (e) => U.T(e, `<b>${m.label}</b>${m.drivers ? "<br><span class='k'>drivers</span> " + m.drivers.join(", ") : ""}`), onMouseLeave: U.hideTip },
              h("div", { className: "mdot" }))))),
        h("div", { style: { display: "flex", gap: 12, flexWrap: "wrap", marginTop: 6 } }, timeline.key_moments.map((m, i) =>
          h("button", { key: i, onClick: () => pick(Math.max(0, segAt(m.t))), style: { border: "none", background: "var(--surface-2)", borderRadius: 99, padding: "5px 11px", fontSize: 11.5, cursor: "pointer", display: "inline-flex", gap: 7, alignItems: "center" } },
            h("span", { className: "num dim-2", style: { fontSize: 10 } }, fmt(m.t)), m.label)))),

      // stacked tracks
      h("div", { className: "card card-pad", style: { marginBottom: 16 } },
        h("div", { className: "eyebrow", style: { marginBottom: 12 } }, "stacked tracks · click a bin to inspect"),
        h("div", { className: "tl-tracks", style: { position: "relative" } },
          h("div", { className: "tl-playhead", style: { left: "calc(" + (t / dur * 100) + "% )" } }),
          TRACKS.map((tr) => h(Track, { key: tr.id, track: tr, segments: timeline.segments, duration: dur, onPick: pick, sel: curIdx })))),

      // segment table
      h("div", { className: "card" },
        h("div", { className: "card-h" }, h("span", { className: "t" }, "Segment breakdown", h("small", null, timeline.segments.length + " segments · " + timeline.resolution_s + "s bins"))),
        h("div", { style: { overflowX: "auto" } }, h("table", { className: "tbl" },
          h("thead", null, h("tr", null, ["Time", "Dominant", "Arousal", "Valence", "Share", "Backlash", "Flag"].map((c, i) => h("th", { key: i, style: i > 1 && i < 5 ? { textAlign: "right" } : null }, c)))),
          h("tbody", null, timeline.segments.map((s, i) => {
            const blTone = s.backlash.level === "high" ? "neg" : s.backlash.level === "moderate" ? "warn" : "ok";
            return h("tr", { key: i, onClick: () => pick(i), style: { background: curIdx === i ? "var(--surface-2)" : undefined } },
              h("td", { className: "num" }, s.t_start + "–" + s.t_end + "s"),
              h("td", { className: "dim" }, window.API.NEURAL_LABEL[s.dominant_signal]),
              h("td", { className: "num", style: { textAlign: "right" } }, Math.round(s.neural_signals.arousal.value * 100)),
              h("td", { className: "num", style: { textAlign: "right", color: s.neural_signals.valence.value < .4 ? "var(--neg-ink)" : undefined } }, Math.round(s.neural_signals.valence.value * 100)),
              h("td", { className: "num", style: { textAlign: "right" } }, Math.round(s.neural_signals.share_impulse.value * 100)),
              h("td", null, h("span", { className: "badge", "data-tone": blTone }, h("span", { className: "g" }), s.backlash.level)),
              h("td", null, s.flag ? h("span", { className: "seg-flag", "data-f": s.flag }, s.flag) : h("span", { className: "dim-2" }, "—")));
          }))))));
  }

  window.TL = { VideoTimeline };
})();
