// Tobeads — ArcadeEntry
// Fullscreen arcade-cabinet entry / attract screen. The site does NOT reveal
// the homepage until the user presses START. Classic charcoal+metal cabinet,
// cyan CRT attract demo (bead-maze), red ball-top joystick, big red START.
// On START: button depresses → screen flash + zoom → onEnter() reveals the site.

const { useState: useStateEntry, useRef: useRefEntry, useEffect: useEffectEntry, useCallback: useCbEntry } = React;
const AE = () => window.AudioManager || null;
const CT = () => window.CabTheme || null;

function ArcadeEntry({ onEnter }) {
  const [pressing, setPressing] = useStateEntry(false);
  const [exiting, setExiting] = useStateEntry(false);
  const [tilt, setTilt] = useStateEntry({ x: 0, y: 0 });
  const [cabTheme, setCabTheme] = useStateEntry(() => (CT() && CT().read()) || null);
  const apiRef = useRefEntry(null);
  const tiltTimer = useRefEntry(null);
  const doneRef = useRefEntry(false);
  const prevBeadsRef = useRefEntry(0);
  const cabWrapRef = useRefEntry(null);
  const reduce = document.body.classList.contains('reduce-motion');

  const onReady = useCbEntry((api) => { apiRef.current = api; }, []);

  function flickDir(dx, dy) {
    apiRef.current && apiRef.current.setDir(dx, dy);
    setTilt({ x: dx, y: dy });
    if (tiltTimer.current) clearTimeout(tiltTimer.current);
    tiltTimer.current = setTimeout(() => setTilt({ x: 0, y: 0 }), 180);
  }

  function pickCabTheme(theme) {
    AE() && AE().unlock();
    AE() && AE().playSelect();
    setCabTheme((CT() && CT().toggle(theme)) || null);
  }

  function pressStart() {
    if (doneRef.current) return;
    doneRef.current = true;
    setPressing(true);
    const A = AE();
    if (A) { A.stopIntroBGM(); A.unlock(); A.setMute(false); A.playStart(); A.playBootTune(); }
    if (reduce) { document.body.classList.remove('no-scroll'); onEnter(); return; }
    setTimeout(() => { setPressing(false); setExiting(true); A && A.playTransition(); }, 240);
    setTimeout(() => { document.body.classList.remove('no-scroll'); onEnter(); }, 1080);
  }

  useEffectEntry(() => {
    // Scale the whole cabinet down when the natural height exceeds the flex slot
    // (common on desktop / landscape H5 after the larger CRT maze).
    const wrap = cabWrapRef.current;
    if (!wrap) return;
    const cab = wrap.querySelector('.cab3d');
    if (!cab) return;
    let raf = 0;
    function fitCab() {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        wrap.style.transform = '';
        const avail = wrap.clientHeight;
        const natural = cab.offsetHeight;
        if (avail > 0 && natural > avail + 1) {
          wrap.style.transform = `scale(${avail / natural})`;
        }
      });
    }
    fitCab();
    let ro = null;
    if (typeof ResizeObserver !== 'undefined') {
      ro = new ResizeObserver(fitCab);
      ro.observe(wrap);
      ro.observe(cab);
    }
    window.addEventListener('resize', fitCab);
    return () => {
      cancelAnimationFrame(raf);
      if (ro) ro.disconnect();
      window.removeEventListener('resize', fitCab);
      wrap.style.transform = '';
    };
  }, []);

  useEffectEntry(() => {
    // Lock document scroll (iOS ignores overflow:hidden on body — needs fixed body +
    // touchmove prevent). Homepage markup is not mounted until START, so there is
    // nothing to scroll to; this blocks rubber-band / background scroll.
    const scrollY = window.scrollY;
    document.documentElement.classList.add('no-scroll');
    document.body.classList.add('no-scroll');
    document.body.dataset.entryScrollY = String(scrollY);
    if (scrollY) document.body.style.top = `-${scrollY}px`;

    function blockTouchMove(e) {
      const t = e.target;
      if (t && t.closest && t.closest('button, .joy, .joy-wrapper, .arc-btn, .start-btn')) return;
      e.preventDefault();
    }
    function blockWheel(e) { e.preventDefault(); }

    document.addEventListener('touchmove', blockTouchMove, { passive: false });
    document.addEventListener('wheel', blockWheel, { passive: false });

    const A = AE();
    if (A) A.startIntroBGM();
    function onKey(e) {
      const map = { ArrowUp:[0,-1], ArrowDown:[0,1], ArrowLeft:[-1,0], ArrowRight:[1,0],
                    w:[0,-1], s:[0,1], a:[-1,0], d:[1,0], W:[0,-1], S:[0,1], A:[-1,0], D:[1,0] };
      if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pressStart(); return; }
      const dd = map[e.key];
      if (dd) { e.preventDefault(); flickDir(dd[0], dd[1]); }
    }
    window.addEventListener('keydown', onKey);

    function unlockScroll() {
      document.documentElement.classList.remove('no-scroll');
      document.body.classList.remove('no-scroll');
      document.body.style.top = '';
      delete document.body.dataset.entryScrollY;
    }

    return () => {
      const A2 = AE();
      if (A2) A2.stopIntroBGM();
      window.removeEventListener('keydown', onKey);
      document.removeEventListener('touchmove', blockTouchMove);
      document.removeEventListener('wheel', blockWheel);
      unlockScroll();
    };
  }, []);

  return (
    <div className={`entry ${exiting ? 'entry-exit' : ''}`} role="dialog" aria-label="Tobeads arcade — press start to enter">
      <div className="entry-vignette"/>
      <div className="entry-floor"/>

      {/* Subtle floating pixel dust in background */}
      <div className="pixel-dust" aria-hidden="true">
        <div className="dust-dot dust-dot-1" />
        <div className="dust-dot dust-dot-2" />
        <div className="dust-dot dust-dot-3" />
        <div className="dust-dot dust-dot-4" />
        <div className="dust-dot dust-dot-5" />
      </div>

      <div className="entry-cab-wrap" ref={cabWrapRef}>
        {/* graffiti / sticker decals (kept small + near the cabinet) */}
        <span className="gtag gtag-2">PIXEL</span>
        <span className="gtag gtag-3">★ DIY</span>
        <span className="gdot gdot-1"/>
        <span className="gdot gdot-3"/>

        {/* one coherent upright 3D cabinet: marquee → screen body → deck → lower body → base */}
        <div className={`cab3d${cabTheme ? ` cab-theme-${cabTheme}` : ''}`}>
          <div className="cab-side" aria-hidden="true"/>

          <div className="cab cab-xl">
            {/* marquee head-box with a premium neon-glowing nameplate */}
            <div className="cab-marquee">
              <div className="cab-nameplate">TOBEADS ARCADE</div>
              <div className="cab-bulbs">
                <span className="cab-bulb"/>
                <span className="cab-bulb"/>
                <span className="cab-bulb"/>
              </div>
            </div>

            {/* upper body holding the deeply recessed CRT */}
            <div className="cab-head">
            <div className="cab-bezel">
              <div className={`aw-screen ${pressing ? 'screen-flash' : ''}`}>
                <div className="aw-screen-hud">
                  <span style={{ color: 'var(--scr-cyan)', textShadow: '0 0 8px var(--scr-cyan)' }}>1UP</span>
                  <span style={{ color: 'var(--wh)' }}>ATTRACT</span>
                  <span style={{ color: 'var(--ylw)' }}>HI 999</span>
                </div>

                <div className="screen-padding">
                  <div className="maze-viewport">
                    {window.MiniBeadGame && (
                      <window.MiniBeadGame
                        stepSfx
                        fitViewport
                        onBeads={(n) => {
                          if (n > prevBeadsRef.current) AE() && AE().playEat();
                          prevBeadsRef.current = n;
                        }}
                        onReady={onReady}
                        paused={false}
                      />
                    )}
                  </div>
                </div>

                {/* Minimal attract prompt: keep the maze visible and uncluttered. */}
                <div className="entry-screen-ovl">
                  <div className="attract-panel">
                    <div className="px blink entry-press">PRESS START</div>
                  </div>
                </div>
              </div>
            </div>
            </div>

            {/* structural lip where the screen body meets the control deck */}
            <div className="deck-joint" />

            {/* slanted control deck with 3D side caps, vertical front thickness, and mounted sockets */}
            <div className="deck-3d">
              <div className="deck-side-l" aria-hidden="true" />
              <div className="deck-side-r" aria-hidden="true" />
              
              <div className="deck-top">
                <div className="joy-wrapper">
                  <div className="joy-socket">
                    <window.Joystick tilt={tilt} setTilt={setTilt} onDir={(x, y) => flickDir(x, y)}/>
                  </div>
                  <div className="deck-label">MOVE</div>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                  <div className="btn-cluster">
                    <button type="button" className={`arc-btn red${cabTheme === 'red' ? ' active' : ''}`} aria-label="Red theme" aria-pressed={cabTheme === 'red'} onClick={() => pickCabTheme('red')}/>
                    <button type="button" className={`arc-btn blue${cabTheme === 'blue' ? ' active' : ''}`} aria-label="Blue theme" aria-pressed={cabTheme === 'blue'} onClick={() => pickCabTheme('blue')}/>
                    <button type="button" className={`arc-btn yellow${cabTheme === 'yellow' ? ' active' : ''}`} aria-label="Yellow theme" aria-pressed={cabTheme === 'yellow'} onClick={() => pickCabTheme('yellow')}/>
                    <button type="button" className={`arc-btn white${cabTheme === 'white' ? ' active' : ''}`} aria-label="White theme" aria-pressed={cabTheme === 'white'} onClick={() => pickCabTheme('white')}/>
                  </div>
                </div>

                <div className="start-wrap">
                  <div className="start-btn-socket">
                    <button onClick={pressStart} className={`start-btn ${pressing ? 'press' : ''}`} aria-label="Press Start to enter">
                      <span className="start-ring"/>
                      START
                    </button>
                  </div>
                  <div className="start-label">PRESS TO PLAY</div>
                </div>
              </div>
              
              <div className="deck-front" />
            </div>

            {/* tall lower body with the coin door */}
            <div className="cab-lower">
              <div className="coin-module" aria-hidden="true">
                <span className="coin-led"/>
                <span className="coin-slit"/>
                <span className="coin-return"/>
              </div>
            </div>

            {/* base plinth resting on the floor */}
            <div className="cab-base">
              <span className="px cab-base-tag">TOBEADS · INSERT BEAD</span>
            </div>
          </div>

          <div className="cab-floor-shadow" aria-hidden="true"/>
        </div>
      </div>
    </div>
  );
}
window.ArcadeEntry = ArcadeEntry;
