// Main app — wires scenes into a Stage timeline.

const DURATION = 32;

// Scene windows (in seconds, with small crossfade overlap handled by scenes)
const SCENES = [
  { Comp: HookScene,    start:  0.0, end:  5.0 },
  { Comp: RecordScene,  start:  5.0, end: 12.5 },
  { Comp: PhotosScene,  start: 12.5, end: 16.5 },
  { Comp: ChapterScene, start: 16.5, end: 24.5 },
  { Comp: BookScene,    start: 24.5, end: 27.8 },
  { Comp: EndScene,     start: 27.8, end: 32.0 },
];

// Updates a data-screen-label on the stage root each second so comments
// resolve to a real timestamp.
function TimeLabel() {
  const t = useTime();
  React.useEffect(() => {
    const root = document.querySelector('[data-video-root]');
    if (!root) return;
    const s = Math.floor(t);
    root.setAttribute('data-screen-label', `t=${String(s).padStart(2,'0')}s`);
  }, [Math.floor(t)]);
  return null;
}

function VideoRoot() {
  return (
    <div data-video-root="true" style={{ position: 'absolute', inset: 0 }}>
      <TimeLabel/>
      {SCENES.map(({ Comp, start, end }, i) => (
        <Sprite key={i} start={start} end={end}>
          <Comp/>
        </Sprite>
      ))}
    </div>
  );
}

function App() {
  // Reload when the hash changes so appending #clean / #record switches
  // cleanly into record mode (controls hidden, plays once start-to-finish).
  React.useEffect(() => {
    const onHash = () => window.location.reload();
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const clean = typeof window !== 'undefined' &&
    /clean|record/i.test(window.location.hash || '');
  return (
    <Stage
      width={540}
      height={960}
      duration={DURATION}
      background={TPALETTE.cream}
      persistKey="tellings-video"
      clean={clean}
      loop={!clean}
    >
      <VideoRoot/>
    </Stage>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
