// scenes/camille.jsx
// Full "Camille — un client appelle" demo, embedded as an iframe so the
// original self-contained HTML/JS/CSS animation runs verbatim. This scene
// lasts one full animation cycle (~56.5s). The iframe is rendered at a
// 1280×720 logical canvas and scaled ×1.5 to fill the 1920×1080 stage.
//
// The embedded demo runs on its own clock, so we forward the main video's
// play/pause state to it via postMessage ('camille:play' / 'camille:pause').
function SceneCamilleAppel() {
  const { localTime, duration } = useSprite();
  const { playing } = useTimeline();
  const iframeRef = React.useRef(null);

  const t = localTime;
  const reveal = Math.max(0, Math.min(1, (t - 0.1) / 0.6));
  const exit   = Math.max(0, Math.min(1, (t - (duration - 0.5)) / 0.5));
  const opacity = reveal * (1 - exit);

  const post = React.useCallback((type) => {
    const w = iframeRef.current && iframeRef.current.contentWindow;
    if (w) { try { w.postMessage({ type }, '*'); } catch (e) {} }
  }, []);

  // Mirror the main video's play/pause onto the embedded demo.
  React.useEffect(() => {
    post(playing ? 'camille:play' : 'camille:pause');
  }, [playing, post]);

  // The embed runs on its own clock: a backwards seek inside this scene
  // (‹ button, ←, progress-bar segment) rewinds the timeline but not the
  // iframe. Detect the jump and restart the demo from the top, keeping it
  // frozen if the video is paused.
  const prevTRef = React.useRef(t);
  React.useEffect(() => {
    if (t < prevTRef.current - 0.75) {
      post('camille:restart');
      if (!playing) post('camille:pause');
    }
    prevTRef.current = t;
  }, [t, playing, post]);

  return (
    <div style={{ position: 'absolute', inset: 0, background: ALD.navy, opacity }}>
      <iframe
        ref={iframeRef}
        src="embeds/camille-appel.html"
        title="Camille — que se passe-t-il quand un client appelle ?"
        scrolling="no"
        onLoad={() => post(playing ? 'camille:play' : 'camille:pause')}
        style={{
          position: 'absolute', top: 0, left: 0,
          width: 1280, height: 720, border: 0,
          transform: 'scale(1.5)', transformOrigin: 'top left',
          pointerEvents: 'none', // let the video's own controls receive clicks
        }}
      />
    </div>
  );
}

Object.assign(window, { SceneCamilleAppel });
