// Tobeads — ArcadeHero
// Full arcade cabinet: marquee + CRT screen (bead-maze game) + angled control
// deck with a ball-top joystick (tilts on input), tactile START button,
// secondary arcade buttons, and a coin slot. Right: Tobeads title-screen logo.

const { useState: useStateHero, useRef: useRefHero, useEffect: useEffectHero, useCallback: useCbHero } = React;

const A = () => window.AudioManager || null;
const CT = () => window.CabTheme || null;

function ArcadeHero({ onNavigate }) {
  const [beads, setBeads] = useStateHero(0);
  const [tilt, setTilt] = useStateHero({ x: 0, y: 0 });   // joystick visual tilt
  const [pressing, setPressing] = useStateHero(false);
  const [cabTheme, setCabTheme] = useStateHero(() => (CT() && CT().read()) || null);
  const apiRef = useRefHero(null);
  const onReady = useCbHero((api) => { apiRef.current = api; }, []);

  function press(dx, dy) {
    apiRef.current && apiRef.current.setDir(dx, dy);
    setTilt({ x: dx, y: dy });
    A() && A().playMove();
  }
  // release tilt shortly after key taps
  const tiltTimer = useRefHero(null);
  function pressKey(dx, dy) {
    press(dx, dy);
    if (tiltTimer.current) clearTimeout(tiltTimer.current);
    tiltTimer.current = setTimeout(() => setTilt({ x: 0, y: 0 }), 180);
  }

  // eat sound: fire when bead count increases
  const prevBeads = useRefHero(0);
  function handleBeads(n) {
    if (n > prevBeads.current) { A() && A().playEat(); }
    prevBeads.current = n;
    setBeads(n);
  }

  // mirror arrow keys into joystick tilt
  useEffectHero(() => {
    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] };
      const d = map[e.key];
      if (!d) return;
      setTilt({ x: d[0], y: d[1] });
      A() && A().playMove();
      if (tiltTimer.current) clearTimeout(tiltTimer.current);
      tiltTimer.current = setTimeout(() => setTilt({ x: 0, y: 0 }), 180);
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

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

  function pressStart() {
    setPressing(true);
    A() && A().unlock();
    A() && A().playStart();
    setTimeout(() => {
      setPressing(false);
      const el = document.getElementById('modes');
      if (el) {
        A() && A().playTransition();
        const y = el.getBoundingClientRect().top + window.scrollY;
        window.scrollTo({ top: y, behavior: 'smooth' });
      }
    }, 260);
  }

  const beadStr = String(beads % 1000).padStart(3, '0');

  return (
    <section className="aw-stage aw-hero-stage" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 24px 54px', position: 'relative', overflowX: 'clip' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(60% 50% at 50% 38%, rgba(127,0,255,0.10), transparent 70%)', pointerEvents: 'none' }}/>
      <div style={{ width: '100%', maxWidth: 1200, display: 'grid', gridTemplateColumns: 'minmax(320px, 0.74fr) minmax(420px, 1fr)', gap: 'clamp(40px, 4.5vw, 64px)', alignItems: 'center', justifyContent: 'center', position: 'relative', margin: '0 auto' }} className="aw-hero-grid">

        {/* LEFT — compact arcade preview module (purpose-built, not a shrunk intro) */}
        <div className="aw-rise cab-persp hero-cab-col" style={{ display: 'flex', justifyContent: 'center' }}>
          <div className={`cab3d cab-mini${cabTheme ? ` cab-theme-${cabTheme}` : ''}`}>
            <div className="cab-side" aria-hidden="true"/>

            <div className="cab">
              {/* marquee head-box */}
              <div className="cab-marquee">
                <div className="cab-nameplate">TOBEADS</div>
                <div className="cab-bulbs"><span className="cab-bulb"/><span className="cab-bulb"/><span className="cab-bulb"/></div>
              </div>

              {/* recessed CRT screen */}
              <div className="cab-head">
                <div className="cab-bezel">
                  <div className="aw-screen">
                    <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)' }}>BEADS:{beadStr}</span>
                      <span style={{ color: 'var(--ylw)' }}>HI 999</span>
                    </div>
                    <div className="screen-padding">
                      <div className="maze-viewport">
                        {window.MiniBeadGame && <window.MiniBeadGame onBeads={handleBeads} onReady={onReady} paused={false} variant="compact"/>}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* control deck — same slanted front panel as the intro */}
              <div className="deck-joint" />
              <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="mini-joy-wrapper">
                    <div className="mini-joy-ball" style={{ transform: `translate(${(tilt.x||0)*4}px, ${(tilt.y||0)*4}px)` }}/>
                    <div className="mini-joy-shaft"/>
                    <div className="mini-joy-base"/>
                  </div>

                  <div style={{ display: 'flex', 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>

                  <button onClick={pressStart} className={`mini-start-btn ${pressing ? 'press' : ''}`} aria-label="Press Start">
                    START
                  </button>
                </div>
                <div className="deck-front" />
              </div>

              {/* thin contact base — the homepage module skips the full lower body
                  / coin door so it reads as a compact preview, not a shrunk intro */}
              <div className="cab-base" aria-hidden="true"/>
            </div>

            <div className="cab-floor-shadow" aria-hidden="true"/>
          </div>
        </div>

        {/* RIGHT — title-screen logo + copy (leads visual hierarchy) */}
        <div className="aw-rise hero-text-col" style={{ animationDelay: '.06s', maxWidth: 590 }}>
          <div className="aw-eyebrow hero-eyebrow" style={{ color: 'var(--ink2)' }}><span className="blk"/>PIXEL BEAD ARCADE</div>
          <div className="hero-logo-wrap">
            <window.TobeadsMark size={'clamp(40px, 7vw, 84px)'} block onLight/>
          </div>
          <h1 className="px hero-tagline" style={{ fontSize: 'clamp(10px, 3vw, 20px)', lineHeight: 1, color: 'var(--ink)' }}>
            Play beads like a game!
          </h1>
          <p className="px hero-lines" style={{ fontSize: 10, color: 'var(--ink2)', lineHeight: 1.8 }}>
            PICK A MODE.<br/>BUILD A BEAD WORLD.
          </p>
          <div className="hero-cta-row" style={{ display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center' }}>
            <button onClick={pressStart} className="pbtn pbtn-ylw pbtn-lg">▶ PRESS START</button>
            <button onClick={() => { A() && A().playSelect(); onNavigate('create'); }} className="pbtn" style={{ background: 'var(--lt2)', color: 'var(--ink)', borderColor: 'var(--ink)', boxShadow: '4px 4px 0 var(--v)' }}>CREATOR MODE</button>
          </div>
          <div className="px aw-hide-mob" style={{ marginTop: 26, fontSize: 8, color: 'var(--ink2)', lineHeight: 2 }}>
            ◀▲▼▶ ARROWS · WASD · DRAG JOYSTICK
          </div>
        </div>
      </div>

    </section>
  );
}
window.ArcadeHero = ArcadeHero;

// ---- Ball-top Joystick: drag → 4-way dir + visual tilt ----
function Joystick({ tilt, setTilt, onDir }) {
  const baseRef = useRefHero(null);
  const draggingRef = useRefHero(false);
  const lastDirRef = useRefHero({ x: 0, y: 0 });

  function handle(clientX, clientY) {
    const base = baseRef.current;
    const rect = base.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    let dx = clientX - cx, dy = clientY - cy;
    const dist = Math.hypot(dx, dy);
    if (dist > 14) {
      let nd;
      if (Math.abs(dx) > Math.abs(dy)) nd = { x: dx > 0 ? 1 : -1, y: 0 };
      else nd = { x: 0, y: dy > 0 ? 1 : -1 };
      setTilt(nd);
      if (nd.x !== lastDirRef.current.x || nd.y !== lastDirRef.current.y) {
        lastDirRef.current = nd;
        onDir(nd.x, nd.y);
      }
    }
  }
  useEffectHero(() => {
    function move(e) { if (!draggingRef.current) return; const pt = e.touches ? e.touches[0] : e; handle(pt.clientX, pt.clientY); }
    function up() { draggingRef.current = false; setTilt({ x: 0, y: 0 }); lastDirRef.current = { x: 0, y: 0 }; }
    window.addEventListener('mousemove', move);
    window.addEventListener('touchmove', move, { passive: false });
    window.addEventListener('mouseup', up);
    window.addEventListener('touchend', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchend', up);
    };
  }, []);

  // tilt → transforms. Shaft + ball lean toward direction.
  const lean = 16; // degrees
  const rx = (tilt.y || 0) * lean;     // tilt up/down → rotateX
  const ry = (tilt.x || 0) * lean;     // tilt left/right → rotateY
  const shaftTf = `rotate(${(tilt.x||0) * 10 + (tilt.y? 0:0)}deg)`;
  const ballTf = `translate(${(tilt.x||0)*10}px, ${(tilt.y||0)*8}px)`;

  return (
    <div
      ref={baseRef}
      className="joy"
      onMouseDown={(e) => { draggingRef.current = true; window.AudioManager && window.AudioManager.unlock(); handle(e.clientX, e.clientY); }}
      onTouchStart={(e) => { draggingRef.current = true; const t = e.touches[0]; handle(t.clientX, t.clientY); }}
    >
      <div className="joy-shaft" style={{ transform: shaftTf }}/>
      <div className="joy-ball" style={{ transform: ballTf }}/>
      <div className="joy-base"/>
    </div>
  );
}
window.Joystick = Joystick;
