// viewer-overview.jsx — Overview "mass re-targeting" interactive.
// A captured motion is the REFERENCE (a starting point at its original mass),
// NOT a target to match. From that reference we re-target the mass to the
// opposite end (Light<->Heavy) two ways and ask which better EXPRESSES the
// target weight:
//   • Baseline : change the TEXT mass only
//   • Ours     : change the text mass AND steer with ACG
// Reuses the shared core (window.useClock / VideoPanel / Transport).
// Mounts via window.mountOverviewViewer() into #overview-viewer.
(function () {
  const { useState, useEffect } = React;

  const theme = {
    bg: '#ffffff', stage: '#f3f6f8', border: '#e2e6ea', ink: '#1f2733', inkSoft: '#5b6573',
    accent: '#2ea866', accentSoft: 'rgba(46,168,102,.10)', chipBg: '#ffffff', barBg: '#ffffff',
    stripeA: '#eef1f4', stripeB: '#e8ecf0', panelShadow: '0 6px 20px rgba(15,30,50,.06)',
    font: "'Noto Sans',sans-serif", serif: "'Castoro',serif",
  };
  // Brand accent (themeable) drives only the viewer UI chrome (transport button).
  // Method colors (Ours green / Baseline red / Reference gray) stay fixed.
  function brandHex() {
    const v = getComputedStyle(document.documentElement).getPropertyValue('--brand-dark').trim();
    return v || '#4a3fc0';
  }

  // Mass is NOT color-coded by hue (green/red are reserved for the methods —
  // Ours/Baseline). The TARGET we steer toward is emphasized with the brand color.
  const DATASETS = ['PA-HOI', 'FORCE'];

  // One re-targeting case per (dataset, flip direction).
  //  cfVid -> per-case clips: static/videos/{cfVid}__{gt|finetuned|ours}.mp4
  //           gt = captured reference, finetuned = text-only flip, ours = text + ACG flip
  const CASES = [
    { dataset: 'PA-HOI', from: 'Light', to: 'Heavy', object: 'Box',   cfVid: 'cf_pahoi_l2h' },
    { dataset: 'PA-HOI', from: 'Heavy', to: 'Light', object: 'Box',   cfVid: 'cf_pahoi_h2l' },
    { dataset: 'FORCE',  from: 'Light', to: 'Heavy', object: 'Crate', cfVid: 'cf_force_l2h' },
    { dataset: 'FORCE',  from: 'Heavy', to: 'Light', object: 'Crate', cfVid: 'cf_force_h2l' },
  ];

  // Per-case description & discussion (from the counterfactual analysis).
  // kind: 'ours' = ACG expresses the target better, 'tie' = Text and Text+ACG end up similar.
  const NOTES = {
    cf_pahoi_l2h: { winner: "Text ≈ Text + ACG", kind: "tie",
      desc: "Reference carries a 5 kg empty box (light); we re-target the text to heavy.",
      finding: "Both Text and Text + ACG carry the box more hunched forward than the reference, so both read as heavier — the two interventions express the target about equally well here." },
    cf_pahoi_h2l: { winner: "Text + ACG", kind: "ours",
      desc: "Reference carries a heavy bucket and sets it down; we re-target the text to light.",
      finding: "Text alone barely changes from the reference (still looks heavy). Only Text + ACG holds the bucket away from the body and carries it more upright — it expresses the lighter target far better." },
    cf_force_l2h: { winner: "Text ≈ Text + ACG", kind: "tie",
      desc: "Reference carries a 5 kg light container; we re-target the text to 30 kg.",
      finding: "Both Text and Text + ACG lean the torso back to counterbalance a heavy load, so both express the heavier target — the two look about the same here." },
    cf_force_h2l: { winner: "Text + ACG (subtle)", kind: "ours",
      desc: "Reference lifts and carries a 25 kg heavy suitcase; we re-target the text to 5 kg.",
      finding: "The two are close, but Ours leans the torso back a touch less and stays nearer upright, so it expresses the lighter target slightly better than text alone." },
  };

  // Panel "methods" — ids/colors match the shared core & drive the video path.
  const M = {
    ref:      { id: 'gt',        color: '#3b424e', tag: 'REF',  short: 'Reference' },
    baseline: { id: 'finetuned', color: '#d6483b', tag: 'TEXT', short: 'Baseline' },
    ours:     { id: 'ours',      color: '#2ea866', tag: 'ACG',  short: 'Ours' },
  };

  function Toggle({ label, options, value, render, onChange }) {
    return (
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
        <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.04em', color: theme.inkSoft, fontFamily: theme.font }}>{label}</span>
        <div style={{ display: 'inline-flex', padding: 3, gap: 3, background: theme.chipBg, border: `1px solid ${theme.border}`, borderRadius: 999 }}>
          {options.map((o) => {
            const on = o === value;
            return (
              <button key={o} onClick={() => onChange(o)} style={{
                padding: '7px 16px', borderRadius: 999, border: 'none', cursor: 'pointer',
                background: on ? theme.ink : 'transparent', color: on ? '#fff' : theme.inkSoft,
                fontSize: 12.5, fontWeight: 700, fontFamily: theme.font, transition: 'all .15s', whiteSpace: 'nowrap',
              }}>{render ? render(o) : o}</button>
            );
          })}
        </div>
      </div>
    );
  }

  function Panel({ seqId, name, load, method, label, sub, clock, onMeta, muted }) {
    return (
      <div className="cf-col" style={{ flex: '1 1 200px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8, opacity: muted ? 0.96 : 1 }}>
        <div style={{ aspectRatio: '3 / 4', width: '100%', filter: muted ? 'saturate(.55)' : 'none' }}>
          <window.VideoPanel seq={{ id: seqId, name: name, load: load }} method={method}
            t={clock.t} duration={clock.duration} theme={theme}
            playing={clock.playing} speed={clock.speed} onMeta={onMeta} badge={false} />
        </div>
        <div style={{ textAlign: 'center', fontFamily: theme.font }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 700, color: theme.ink }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: method.color }}></span>
            {label}
            {method.id === 'ours' && <span style={{ fontSize: 9, fontWeight: 800, color: '#fff', background: method.color, padding: '1px 5px', borderRadius: 4 }}>★</span>}
          </div>
          <div style={{ fontSize: 11, color: theme.inkSoft, marginTop: 2 }}>{sub}</div>
        </div>
      </div>
    );
  }

  function OverviewViewer() {
    theme.accent = brandHex(); // UI-chrome accent follows the brand theme
    const [dataset, setDataset] = useState('PA-HOI');
    const [dir, setDir] = useState('Light → Heavy');
    const [measured, setMeasured] = useState(0);

    const fromWanted = dir.indexOf('Light') === 0 ? 'Light' : 'Heavy';
    const cse = CASES.find((c) => c.dataset === dataset && c.from === fromWanted) || CASES[0];

    const clock = window.useClock(measured > 0 ? measured : 4.0);
    useEffect(() => { setMeasured(0); clock.setT(0); clock.setPlaying(true); }, [dataset, dir]);
    const onMeta = (d) => { if (d && isFinite(d)) setMeasured((m) => Math.max(m, d)); };

    const toC = theme.accent; // brand color = the target mass we steer toward
    const note = NOTES[cse.cfVid];

    return (
      <div style={{ fontFamily: theme.font, color: theme.ink }}>
        {/* controls */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14, flexWrap: 'wrap', marginBottom: 14 }}>
          <Toggle label="Dataset" options={DATASETS} value={dataset} onChange={setDataset} />
          <Toggle label="Re-target" options={['Light → Heavy', 'Heavy → Light']} value={dir} onChange={setDir} />
        </div>

        {/* setup banner: a reference motion, re-targeted to the opposite mass */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', margin: '0 2px 14px',
          padding: '10px 14px', borderRadius: 10, background: theme.stage, border: `1px solid ${theme.border}` }}>
          <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.12em', textTransform: 'uppercase', color: theme.inkSoft }}>Setup</span>
          <span style={{ fontSize: 13, color: theme.ink }}>
            one captured motion (truly <b style={{ color: theme.ink }}>{cse.from.toLowerCase()}</b>), its mass re-targeted to
            <b style={{ color: toC }}> {cse.to.toLowerCase()}</b> — does the generated posture follow?
          </span>
        </div>

        {/* reference (origin) → judged pair (Baseline vs Ours) */}
        <div className="cf-row" style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'stretch' }}>
          {/* the REFERENCE: the source motion, an anchor — not a target to match */}
          <div className="cf-ref" style={{ flex: '1 1 190px', minWidth: 0, display: 'flex', flexDirection: 'column' }}>
            <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.1em', textTransform: 'uppercase', color: theme.inkSoft, marginBottom: 8, textAlign: 'center' }}>Starting point</div>
            <Panel clock={clock} onMeta={onMeta} muted
              seqId={cse.cfVid} name={cse.object} load={cse.from} method={M.ref}
              label="Reference" sub={`captured motion · truly ${cse.from.toLowerCase()}`} />
          </div>

          {/* re-target arrow */}
          <div className="cf-arrow" style={{ flex: '0 0 auto', alignSelf: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '0 2px' }}>
            <span style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: '.08em', textTransform: 'uppercase', color: theme.inkSoft }}>re-target</span>
            <span style={{ fontSize: 24, lineHeight: 1, color: toC }}>→</span>
            <span style={{ fontSize: 11, fontWeight: 800, color: toC }}>{cse.to}</span>
          </div>

          {/* the JUDGED PAIR: which intervention better expresses the target mass */}
          <div className="cf-judge" style={{ flex: '2.1 1 400px', minWidth: 0, display: 'flex', flexDirection: 'column',
            border: `1px solid ${theme.border}`, borderRadius: 12, padding: '12px 12px 14px', background: theme.stage }}>
            <div style={{ textAlign: 'center', marginBottom: 10 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: theme.ink }}>Which expresses a <b style={{ color: toC }}>{cse.to.toLowerCase()}</b> object better?</span>
            </div>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'stretch' }}>
              <Panel clock={clock} onMeta={onMeta}
                seqId={cse.cfVid} name={cse.object} load={cse.to} method={M.baseline}
                label="Baseline" sub="change text mass only" />
              <Panel clock={clock} onMeta={onMeta}
                seqId={cse.cfVid} name={cse.object} load={cse.to} method={M.ours}
                label="Ours" sub="text mass + ACG" />
            </div>
          </div>
        </div>

        {/* finding */}
        {(() => {
          const bk = note.kind === 'ours' ? M.ours.color : theme.inkSoft;
          return (
            <div style={{ margin: '14px 2px 0', padding: '12px 14px', background: theme.stage, border: `1px solid ${theme.border}`, borderRadius: 10, fontFamily: theme.font }}>
              <div style={{ fontSize: 12, marginBottom: 6 }}>
                <span style={{ fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', color: theme.inkSoft }}>Expresses target better</span>
                <span style={{ marginLeft: 8, fontWeight: 800, color: bk }}>{note.winner}</span>
              </div>
              <p style={{ margin: 0, fontSize: 13, color: theme.inkSoft, lineHeight: 1.55 }}>
                <b style={{ color: theme.ink }}>{note.desc}</b> {note.finding}
              </p>
            </div>
          );
        })()}

        {/* transport */}
        <div style={{ marginTop: 16, maxWidth: 760, marginLeft: 'auto', marginRight: 'auto' }}>
          <window.Transport clock={clock} theme={theme} />
        </div>
      </div>
    );
  }

  window.mountOverviewViewer = function (el) {
    const root = el.__root || (el.__root = ReactDOM.createRoot(el));
    root.render(<OverviewViewer />);
  };
})();
