// LogoutOverlay — OM Group Premium Logout Transition
// Covers the screen the instant Sign Out is clicked.
// Plays the branded logout animation, clears the session in the background,
// fades the login screen in behind it, then dissolves away.
// Zero flashing. Zero hard cuts. Zero visible state transitions.

(function () {
  const { useState: loSt, useEffect: loEf, useRef: loRf, useMemo: loMemo } = React;

  const ANIM_DURATION = 5.2; // mirrors DURATION in logout-scene.jsx

  function LogoutOverlay({ onReadyToShowLogin, onComplete }) {
    const [time,   setTime]   = loSt(0);
    const [fading, setFading] = loSt(false);

    const rafRef    = loRf(null);
    const lastTsRef = loRf(null);
    const timeRef   = loRf(0);   // mutable time tracked outside React state
    const phasesRef = loRf({ loginReady: false, fadingOut: false, done: false });

    // ── Cover-mode scale: fills viewport while keeping scene centered ──────
    const [vp, setVp] = loSt(() => {
      const W = 1920, H = 1080;
      const vw = window.innerWidth  || 1920;
      const vh = window.innerHeight || 1080;
      const s  = Math.max(vw / W, vh / H);
      return { s, ox: (vw - W * s) / 2, oy: (vh - H * s) / 2 };
    });

    loEf(() => {
      const W = 1920, H = 1080;
      const measure = () => {
        const vw = window.innerWidth;
        const vh = window.innerHeight;
        const s  = Math.max(vw / W, vh / H);
        setVp({ s, ox: (vw - W * s) / 2, oy: (vh - H * s) / 2 });
      };
      window.addEventListener('resize',            measure);
      window.addEventListener('orientationchange', measure);
      return () => {
        window.removeEventListener('resize',            measure);
        window.removeEventListener('orientationchange', measure);
      };
    }, []);

    // ── RAF timeline ────────────────────────────────────────────────────────
    loEf(() => {
      const p = phasesRef.current;

      const step = (ts) => {
        if (lastTsRef.current == null) lastTsRef.current = ts;
        const dt = Math.min((ts - lastTsRef.current) / 1000, 0.05);
        lastTsRef.current = ts;

        setTime(prev => {
          const t = prev + dt;

          // ── t ≈ 4.0 s ── animation white-out begins
          // Clear session NOW, mount login behind the still-opaque overlay.
          if (!p.loginReady && t >= 4.0) {
            p.loginReady = true;
            onReadyToShowLogin();
          }

          // ── t ≈ 4.8 s ── animation white-out complete
          // Start dissolving the overlay; login is fully rendered below.
          if (!p.fadingOut && t >= 4.8) {
            p.fadingOut = true;
            setFading(true);
          }

          // ── t ≈ 5.5 s ── CSS transition finished, remove overlay
          if (!p.done && t >= 5.5) {
            p.done = true;
            setTimeout(onComplete, 30);
            return t;
          }

          rafRef.current = requestAnimationFrame(step);
          return t;
        });
      };

      rafRef.current = requestAnimationFrame(step);
      return () => {
        if (rafRef.current) { cancelAnimationFrame(rafRef.current); rafRef.current = null; }
      };
    }, []);

    // ── Provide TimelineContext so LogoutSceneContent can call useTime() ───
    const ctxValue = loMemo(() => ({
      time:       Math.min(time, ANIM_DURATION),
      duration:   ANIM_DURATION,
      playing:    time < ANIM_DURATION,
      setTime:    () => {},
      setPlaying: () => {},
    }), [time]);

    const { s, ox, oy } = vp;

    return (
      <div style={{
        position:      'fixed',
        inset:          0,
        zIndex:         9998,
        overflow:       'hidden',
        pointerEvents:  'all',
        // opacity transitions from 1→0 when fading=true
        opacity:        fading ? 0 : 1,
        transition:     'opacity 0.65s cubic-bezier(0.4, 0, 0.2, 1)',
        willChange:     'opacity',
      }}>
        {/* 1920×1080 scene canvas, scaled + translated to cover the viewport */}
        <div style={{
          position:        'absolute',
          width:            1920,
          height:           1080,
          background:      '#FDFCFB',
          transformOrigin: 'top left',
          transform:       `translate(${ox}px, ${oy}px) scale(${s})`,
          overflow:        'hidden',
        }}>
          <window.TimelineContext.Provider value={ctxValue}>
            <window.LogoutSceneContent />
          </window.TimelineContext.Provider>
        </div>
      </div>
    );
  }

  window.LogoutOverlay = LogoutOverlay;
})();
