// intro-app.jsx — Mounts the Khyran Studio 30s intro into the front page.
//
// Depends on:
//   - React 18 (UMD global)
//   - animations.jsx  (TimelineContext)
//   - scenes.jsx      (IntroReel)

(function () {
  const FONT_DISPLAY = '"Space Grotesk", "Helvetica Neue", Helvetica, sans-serif';

  const STAGE_W = 1920;
  const STAGE_H = 1080;
  const DURATION = 30; // seconds — matches the design

  // Auto-scaling stage that loops the IntroReel forever.
  function ReelStage() {
    const wrapRef = React.useRef(null);
    const [scale, setScale] = React.useState(1);
    const [time, setTime] = React.useState(0);

    React.useEffect(() => {
      const wrap = wrapRef.current;
      if (!wrap) return;
      const measure = () => {
        const s = Math.min(wrap.clientWidth / STAGE_W, wrap.clientHeight / STAGE_H);
        setScale(Math.max(0.05, s));
      };
      measure();
      const ro = new ResizeObserver(measure);
      ro.observe(wrap);
      window.addEventListener('resize', measure);
      return () => { ro.disconnect(); window.removeEventListener('resize', measure); };
    }, []);

    React.useEffect(() => {
      let raf, last = null;
      const step = (ts) => {
        if (last == null) last = ts;
        const dt = (ts - last) / 1000;
        last = ts;
        setTime((t) => {
          let n = t + dt;
          if (n >= DURATION) n = n % DURATION;
          return n;
        });
        raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
      return () => cancelAnimationFrame(raf);
    }, []);

    const ctxValue = React.useMemo(
      () => ({ time, duration: DURATION, playing: true }),
      [time]
    );

    return (
      <div
        ref={wrapRef}
        style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: '#000', overflow: 'hidden',
        }}
      >
        <div
          style={{
            width: STAGE_W, height: STAGE_H,
            background: '#000000',
            position: 'relative',
            transform: `scale(${scale})`,
            transformOrigin: 'center',
            flexShrink: 0,
            overflow: 'hidden',
            fontFamily: FONT_DISPLAY,
            color: '#fff',
          }}
        >
          <TimelineContext.Provider value={ctxValue}>
            <IntroReel />
          </TimelineContext.Provider>
        </div>
      </div>
    );
  }

  function IntroApp() {
    return (
      <div className="grain" style={{ position: 'absolute', inset: 0 }}>
        <ReelStage />
      </div>
    );
  }

  function mount() {
    const host = document.getElementById('khyran-intro-mount');
    if (!host) return;
    const root = ReactDOM.createRoot(host);
    root.render(<IntroApp />);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mount);
  } else {
    mount();
  }
})();
