// viewer-embed.jsx — responsive page-embed of the chosen "Trio Row" comparison viewer
// Mounts into #teaser-viewer in index.html. Exports window.mountTeaserViewer()
(function () {
  const { useState, useEffect } = React;
  const { METHODS, SEQUENCES, DATASETS, DURATION } = window.VIEWER_DATA;

  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 the viewer's *UI chrome* only — play button,
  // active chips, sync dot. Method colors (Ours green / Baseline red) stay fixed.
  function brandHex() {
    const v = getComputedStyle(document.documentElement).getPropertyValue('--brand-dark').trim();
    return v || '#4a3fc0';
  }
  function brandTint(hex, a) {
    const h = hex.replace('#', '');
    const r = parseInt(h.substring(0, 2), 16), g = parseInt(h.substring(2, 4), 16), b = parseInt(h.substring(4, 6), 16);
    return `rgba(${r},${g},${b},${a})`;
  }
  // Mass shown as a neutral light→dark ramp (heavier = darker), so hue stays
  // reserved for the methods (Ours green / Baseline red).
  const loadColor = { Light: '#aab2bd', Medium: '#7c8694', Heavy: '#3a4150' };

  function DatasetToggle({ value, 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 }}>Dataset</span>
        <div style={{ display: 'inline-flex', padding: 3, gap: 3, background: theme.chipBg, border: `1px solid ${theme.border}`, borderRadius: 999 }}>
        {DATASETS.map((d) => {
          const on = d === value;
          return (
            <button key={d} onClick={() => onChange(d)} style={{
              padding: '7px 18px', borderRadius: 999, border: 'none', cursor: 'pointer',
              background: on ? theme.ink : 'transparent', color: on ? '#fff' : theme.inkSoft,
              fontSize: 13, fontWeight: 700, fontFamily: theme.font, transition: 'all .15s', whiteSpace: 'nowrap',
            }}>{d}</button>
          );
        })}
        </div>
      </div>
    );
  }

  function SeqChip({ seq, active, onClick }) {
    return (
      <button onClick={onClick} style={{
        display: 'flex', alignItems: 'center', gap: 9, cursor: 'pointer', padding: '8px 14px',
        borderRadius: 999, border: `1px solid ${active ? theme.accent : theme.border}`,
        background: active ? theme.accentSoft : theme.chipBg,
        boxShadow: active ? `inset 0 0 0 1px ${theme.accent}` : 'none', transition: 'all .15s',
      }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: loadColor[seq.load], flexShrink: 0 }}></span>
        <span style={{ fontSize: 13.5, fontWeight: 600, color: theme.ink, fontFamily: theme.font, whiteSpace: 'nowrap' }}>{seq.name}</span>
        <span style={{ fontSize: 11, color: theme.inkSoft, fontFamily: "'JetBrains Mono',monospace", whiteSpace: 'nowrap', flexShrink: 0 }}>
          {seq.load}
        </span>
      </button>
    );
  }

  function PageViewer() {
    // sync the UI-chrome accent to the current brand theme on every render
    theme.accent = brandHex();
    theme.accentSoft = brandTint(theme.accent, 0.10);
    const [dataset, setDataset] = useState(DATASETS[0]);
    const seqs = SEQUENCES.filter((s) => s.dataset === dataset);
    const [seqId, setSeqId] = useState(seqs[0].id);
    // measured clip length of the active sequence (0 = unknown → use DURATION fallback)
    const [measured, setMeasured] = useState(0);
    const seq = SEQUENCES.find((s) => s.id === seqId) || seqs[0];
    // each sequence can be a different length: drive the shared clock with the real duration
    const clock = window.useClock(measured > 0 ? measured : DURATION);
    const pickDataset = (d) => { setDataset(d); setSeqId(SEQUENCES.find((s) => s.dataset === d).id); };

    // switching sequence/dataset restarts playback from the beginning and re-measures
    useEffect(() => { setMeasured(0); clock.setT(0); clock.setPlaying(true); }, [seqId]);
    const onMeta = (d) => { if (d && isFinite(d)) setMeasured((m) => Math.max(m, d)); };

    return (
      <div style={{ fontFamily: theme.font, color: theme.ink }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14, flexWrap: 'wrap', marginBottom: 14 }}>
          <DatasetToggle value={dataset} onChange={pickDataset} />
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {seqs.map((s) => (
              <SeqChip key={s.id} seq={s} active={s.id === seqId} onClick={() => setSeqId(s.id)} />
            ))}
          </div>
        </div>

        <div className="cf-row" style={{ display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'stretch' }}>
          {/* the two methods we actually compare */}
          {METHODS.filter((m) => m.id !== 'gt').map((m) => (
            <div key={m.id} className="cf-col" style={{ flex: '1 1 220px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ aspectRatio: '3 / 4', width: '100%' }}>
                <window.VideoPanel seq={seq} method={m} t={clock.t} duration={clock.duration} theme={theme} onMeta={onMeta} playing={clock.playing} speed={clock.speed} />
              </div>
              <div style={{ fontSize: 12.5, color: theme.inkSoft, textAlign: 'center', fontFamily: theme.font }}>{m.full}</div>
            </div>
          ))}
          {/* divider — Ground Truth is a reference, not a competing method */}
          <div className="cf-divider" style={{ flex: '0 0 1px', alignSelf: 'stretch', minHeight: 120, background: theme.border, margin: '0 2px' }}></div>
          {(() => {
            const gt = METHODS.find((m) => m.id === 'gt');
            return (
              <div key={gt.id} className="cf-col" style={{ flex: '1 1 220px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ aspectRatio: '3 / 4', width: '100%' }}>
                  <window.VideoPanel seq={seq} method={gt} t={clock.t} duration={clock.duration} theme={theme} onMeta={onMeta} playing={clock.playing} speed={clock.speed} />
                </div>
                <div style={{ fontSize: 12.5, color: theme.inkSoft, textAlign: 'center', fontFamily: theme.font }}>
                  {gt.full}
                  <span style={{ marginLeft: 6, fontSize: 10, fontWeight: 700, letterSpacing: '.04em', textTransform: 'uppercase', color: theme.inkSoft, border: `1px solid ${theme.border}`, borderRadius: 4, padding: '1px 5px' }}>reference</span>
                </div>
              </div>
            );
          })()}
        </div>

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

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