// viewer-core.jsx — shared data + hooks + panel/transport for the PACG-HOI comparison viewer
// Exports to window: VIEWER_DATA, useClock, VideoPanel, Transport, fmtTime, methodColor
(function () {
  const { useState, useEffect, useRef } = React;

  // ---------- Method semantics (colors match the qualitative-figure legend below) ----------
  const METHODS = [
    { id: 'finetuned', short: 'Baseline', full: 'Baseline (Fine-tuned)',                    tag: 'BASE', color: '#d6483b' },
    { id: 'ours',      short: 'Ours', full: 'Ours (Fine-tuned + ACG)', tag: 'ACG',  color: '#2ea866' },
    { id: 'gt',        short: 'Ground Truth', full: 'Ground Truth',                   tag: 'GT',   color: '#3b424e' },
  ];

  const DATASETS = ['PA-HOI', 'FORCE'];

  // ---------- Example sequences (Δ = Pred − GT for the specific clip displayed) ----------
  // pelvis Δ in cm, lean Δ in degrees. Picked from per-sequence errors where
  // guidance (Ours) reduces the absolute Δ vs. no_classifier_guidance (Baseline).
  // FORCE masses are taken from the dataset prompts; PA-HOI prompts only
  // encode the categorical Light/Medium/Heavy.
  const SEQUENCES = [
    { id: 'pahoi_light',  name: 'Jar',            load: 'Light',  dataset: 'PA-HOI',
      dPelvis: { finetuned: -3.24, ours: -0.10 },  dLean: { finetuned: 11.46, ours:  2.05 } },
    { id: 'pahoi_medium', name: 'Thermos',        load: 'Medium', dataset: 'PA-HOI',
      dPelvis: { finetuned: -2.26, ours:  0.28 },  dLean: { finetuned: -0.65, ours: -0.08 } },
    { id: 'pahoi_heavy',  name: 'Milkbox',        load: 'Heavy',  dataset: 'PA-HOI',
      dPelvis: { finetuned: -0.99, ours: -0.94 },  dLean: { finetuned: 12.65, ours: 11.52 } },
    { id: 'force_light',  name: 'Chair',          load: 'Light',  dataset: 'FORCE',
      dPelvis: { finetuned: -10.50, ours: -1.90 }, dLean: { finetuned:  5.55, ours: -3.37 } },
    { id: 'force_medium', name: 'Huge box',       load: 'Medium', dataset: 'FORCE',
      dPelvis: { finetuned: -13.85, ours: -4.06 }, dLean: { finetuned: 21.53, ours: -1.13 } },
    { id: 'force_heavy',  name: 'Laundry basket', load: 'Heavy',  dataset: 'FORCE',
      dPelvis: { finetuned: -2.64, ours: -2.52 },  dLean: { finetuned: 20.09, ours: 19.55 } },
  ];

  const DURATION = 4.0; // fallback clock length (s) until a real video reports its duration
  // Bump VIDEO_REV when mp4s are regenerated to defeat browser cache.
  const VIDEO_REV = 104;
  const videoSrc = (seqId, methodId) => `static/videos/${seqId}__${methodId}.mp4?v=${VIDEO_REV}`;

  function methodColor(id) {
    const m = METHODS.find((x) => x.id === id);
    return m ? m.color : '#888';
  }

  function fmtTime(t) {
    if (!isFinite(t)) t = 0;
    const m = Math.floor(t / 60);
    const s = Math.floor(t % 60);
    const cs = Math.floor((t - Math.floor(t)) * 10);
    return `${m}:${s < 10 ? '0' + s : s}.${cs}`;
  }

  // ---------- Shared clock: drives placeholders AND real <video> currentTime ----------
  function useClock(duration = DURATION) {
    const [t, setT] = useState(0);
    const [playing, setPlaying] = useState(true);
    const [speed, setSpeed] = useState(1);
    const raf = useRef(null);
    const last = useRef(null);
    useEffect(() => {
      if (!playing) { last.current = null; return; }
      const tick = (now) => {
        if (last.current == null) last.current = now;
        const dt = ((now - last.current) / 1000) * speed;
        last.current = now;
        setT((prev) => {
          let n = prev + dt;
          if (n >= duration) n = n % duration;
          return n;
        });
        raf.current = requestAnimationFrame(tick);
      };
      raf.current = requestAnimationFrame(tick);
      return () => { cancelAnimationFrame(raf.current); last.current = null; };
    }, [playing, speed, duration]);
    return { t, setT, playing, setPlaying, speed, setSpeed, duration };
  }

  // ---------- A single method panel: real video if present, else animated placeholder ----------
  function VideoPanel(props) {
    const { seq, method, t, duration, theme, dim, badge, onMeta, playing, speed } = props;
    const [ok, setOk] = useState(false);
    const ref = useRef(null);
    const src = videoSrc(seq.id, method.id);

    // Probe existence first so we never hand a missing URL to a <video> (avoids console resource errors).
    useEffect(() => {
      let alive = true;
      setOk(false);
      fetch(src, { method: 'HEAD' })
        .then((r) => { if (alive) setOk(r.ok); })
        .catch(() => { if (alive) setOk(false); });
      return () => { alive = false; };
    }, [src]);

    // Smooth playback: let the <video> play natively and only nudge currentTime when it
    // drifts from the shared clock. (Seeking every frame is what made it stutter.)
    useEffect(() => {
      const v = ref.current;
      if (v && ok && Math.abs(v.currentTime - t) > 0.2) { try { v.currentTime = t; } catch (e) {} }
    }, [t, ok]);

    // Play/pause and speed are applied to the element itself so the browser decodes smoothly.
    useEffect(() => {
      const v = ref.current;
      if (!v || !ok) return;
      try { v.playbackRate = speed || 1; } catch (e) {}
      if (playing) { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
      else { v.pause(); }
    }, [ok, playing, speed]);

    const pct = (t / duration) * 100;
    const isOurs = method.id === 'ours';

    return (
      React.createElement('div', { style: {
        position: 'relative', width: '100%', height: '100%',
        background: theme.stage, borderRadius: 10, overflow: 'hidden',
        border: `1px solid ${isOurs ? method.color + '66' : theme.border}`,
        boxShadow: isOurs ? `0 0 0 2px ${method.color}22, ${theme.panelShadow}` : theme.panelShadow,
      } },
        // real video (hidden until it actually loads)
        React.createElement('video', {
          ref, src: ok ? src : undefined, muted: true, loop: true, playsInline: true, preload: 'auto',
          onLoadedMetadata: (e) => { if (onMeta) onMeta(e.target.duration); },
          style: { display: ok ? 'block' : 'none', width: '100%', height: '100%', objectFit: 'cover' },
        }),
        // placeholder
        !ok && React.createElement('div', { style: {
          position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          background: `repeating-linear-gradient(135deg, ${theme.stripeA} 0 10px, ${theme.stripeB} 10px 20px)`,
        } },
          React.createElement('div', { style: {
            fontFamily: "'Castoro', serif", fontSize: dim ? 13 : 15, letterSpacing: '.18em',
            textTransform: 'uppercase', color: method.color, fontWeight: 700, opacity: .85,
          } }, method.tag),
          React.createElement('div', { style: {
            marginTop: 6, fontSize: dim ? 11 : 12, color: theme.inkSoft, opacity: .7,
          } }, `${seq.name} · ${seq.load}`),
          React.createElement('div', { style: {
            position: 'absolute', bottom: 10, left: 12, right: 12, textAlign: 'center',
            fontFamily: "'JetBrains Mono','Courier New',monospace", fontSize: 9.5,
            color: theme.inkSoft, opacity: .45, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          } }, src),
          // moving playhead to convey synced playback even without media
          React.createElement('div', { style: {
            position: 'absolute', top: 0, bottom: 0, left: pct + '%', width: 2,
            background: method.color, opacity: .5, transition: 'left .05s linear',
          } })
        ),
        // top-left badge
        badge !== false && React.createElement('div', { style: {
          position: 'absolute', top: 8, left: 8, display: 'flex', gap: 6, alignItems: 'center',
          padding: '3px 9px', borderRadius: 999, background: theme.chipBg,
          border: `1px solid ${theme.border}`, fontSize: dim ? 10.5 : 11.5, fontWeight: 600, color: theme.ink,
          whiteSpace: 'nowrap',
        } },
          React.createElement('span', { style: { width: 7, height: 7, borderRadius: 999, background: method.color } }),
          method.short,
          isOurs && React.createElement('span', { style: {
            fontSize: 9, fontWeight: 700, color: '#fff', background: method.color,
            padding: '1px 5px', borderRadius: 4, letterSpacing: '.04em',
          } }, '★'))
      )
    );
  }

  // ---------- Transport: play/pause, scrubber, time, speed ----------
  function Transport(props) {
    const { clock, theme, compact } = props;
    const { t, setT, playing, setPlaying, speed, setSpeed, duration } = clock;
    const speeds = [0.5, 1, 2];
    const cycleSpeed = () => setSpeed(speeds[(speeds.indexOf(speed) + 1) % speeds.length]);
    return (
      React.createElement('div', { className: 'transport-bar', style: {
        display: 'flex', alignItems: 'center', gap: compact ? 10 : 14,
        padding: compact ? '8px 12px' : '10px 16px', background: theme.barBg,
        border: `1px solid ${theme.border}`, borderRadius: 999,
        flexWrap: 'wrap', rowGap: 8, maxWidth: '100%', boxSizing: 'border-box',
      } },
        React.createElement('button', {
          onClick: () => setPlaying((p) => !p), 'aria-label': 'play/pause',
          style: {
            width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: theme.accent, color: '#fff', fontSize: 13, display: 'flex',
            alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
          },
        }, playing ? '❚❚' : '▶'),
        React.createElement('input', {
          type: 'range', min: 0, max: duration, step: 0.01, value: t,
          'aria-label': 'playback position',
          onChange: (e) => setT(parseFloat(e.target.value)),
          style: { flex: '1 1 160px', minWidth: 140, accentColor: theme.accent, cursor: 'pointer' },
        }),
        React.createElement('span', { style: {
          fontFamily: "'JetBrains Mono',monospace", fontSize: 12, color: theme.inkSoft,
          minWidth: 64, textAlign: 'right', flexShrink: 0,
        } }, `${fmtTime(t)} / ${fmtTime(duration)}`),
        React.createElement('button', {
          onClick: cycleSpeed,
          style: {
            border: `1px solid ${theme.border}`, background: theme.chipBg, color: theme.ink,
            borderRadius: 999, padding: '5px 11px', fontSize: 12, fontWeight: 600, cursor: 'pointer',
            fontFamily: "'JetBrains Mono',monospace", flexShrink: 0,
          },
        }, `${speed}×`),
        React.createElement('span', { style: {
          display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: theme.inkSoft, fontWeight: 600,
          flexShrink: 0, whiteSpace: 'nowrap',
        } },
          React.createElement('span', { style: { width: 7, height: 7, borderRadius: 999, background: theme.accent } }),
          'synced')
      )
    );
  }

  window.VIEWER_DATA = { METHODS, SEQUENCES, DATASETS, DURATION, videoSrc };
  window.useClock = useClock;
  window.VideoPanel = VideoPanel;
  window.Transport = Transport;
  window.fmtTime = fmtTime;
  window.methodColor = methodColor;
})();
