// hook-main.jsx — Timeline controller for the hook video
const { useState, useEffect, useRef } = React;

const DURATION = 30.0; // seconds

function HookApp() {
  const [time, setTime] = useState(0);
  const [playing, setPlaying] = useState(false);
  const rafRef = useRef(null);
  const lastRef = useRef(null);

  useEffect(() => {
    if (!playing) {
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      lastRef.current = null;
      return;
    }
    const tick = (now) => {
      if (lastRef.current == null) lastRef.current = now;
      const dt = (now - lastRef.current) / 1000;
      lastRef.current = now;
      setTime((t) => {
        // Scrub override for testing
        if (typeof window._forceTime === 'number') {
          return window._forceTime;
        }
        const nt = t + dt;
        if (nt >= DURATION) {
          setPlaying(false);
          return DURATION;
        }
        return nt;
      });
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); };
  }, [playing]);

  // External scrub support
  useEffect(() => {
    window._scrub = (t) => { setTime(t); setPlaying(false); };
  }, []);

  // Update UI elements outside React tree
  useEffect(() => {
    const pbar = document.getElementById('pbar');
    if (pbar) pbar.style.width = `${(time / DURATION) * 100}%`;
    const clock = document.getElementById('clock');
    if (clock) {
      const secs = Math.floor(time);
      const ss = String(secs).padStart(2, '0');
      clock.textContent = `00:${ss} / 00:30`;
    }
    const tl = document.getElementById('timeLabel');
    if (tl) tl.textContent = `${time.toFixed(1)}s / 30.0s`;
  }, [time]);

  // Wire buttons
  useEffect(() => {
    const playBtn = document.getElementById('playBtn');
    const restartBtn = document.getElementById('restartBtn');
    if (!playBtn || !restartBtn) return;
    const handlePlay = () => {
      if (time >= DURATION) setTime(0);
      setPlaying((p) => !p);
    };
    const handleRestart = () => {
      setTime(0);
      setPlaying(true);
    };
    playBtn.addEventListener('click', handlePlay);
    restartBtn.addEventListener('click', handleRestart);
    return () => {
      playBtn.removeEventListener('click', handlePlay);
      restartBtn.removeEventListener('click', handleRestart);
    };
  }, [time]);

  // Update play button icon (icons only — no text)
  useEffect(() => {
    const btn = document.getElementById('playBtn');
    if (btn) btn.textContent = playing ? '❚❚' : '▶';
  }, [playing, time]);

  return <window.HookVideo time={time} />;
}

// Auto-start after mount
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HookApp />);

// Auto-play after brief delay
setTimeout(() => {
  const btn = document.getElementById('playBtn');
  if (btn) btn.click();
}, 500);
