// ============================================================
// HUNGRY HOLE 3D — v2.0 OPEN-WORLD "RIVALS" screen (additive, flag-safe)
// Endless arena · streaming props (no walls) · 4 rival AI holes to race & swallow.
// Uses window.HoleEngineRivals (separate engine). Campaign untouched.
// ============================================================
const { useState: useStateRv, useEffect: useEffectRv, useRef: useRefRv } = React;

function EndlessBoard({ paused, onUpdate, onDead, engineRef }) {
  const canvasRef = useRefRv(null);
  const layerRef = useRefRv(null);
  const cb = useRefRv({}); cb.current = { onUpdate, onDead };

  useEffectRv(() => {
    if (!window.HoleEngineRivals) return;
    const eng = window.HoleEngineRivals(canvasRef.current, layerRef.current, {
      interactive: true,
      onUpdate: (s) => cb.current.onUpdate && cb.current.onUpdate(s),
      onDead: (r) => cb.current.onDead && cb.current.onDead(r),
    });
    if (engineRef) engineRef.current = eng;
    return () => { eng.destroy(); if (engineRef) engineRef.current = null; };
  }, []);

  useEffectRv(() => { if (engineRef && engineRef.current) engineRef.current.setPaused(!!paused); }, [paused]);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', touchAction: 'none', display: 'block' }}></canvas>
      <div ref={layerRef} style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none', zIndex: 40 }}></div>
    </div>
  );
}

function EndlessGame({ go }) {
  const engineRef = useRefRv(null);
  const [live, setLive] = useStateRv({ size: 2.1, score: 0, eaten: 0, rank: 5, rivals: 4, shield: false });
  const [paused, setPaused] = useStateRv(false);
  const [started, setStarted] = useStateRv(false);
  const [dead, setDead] = useStateRv(null);
  const [boardKey, setBoardKey] = useStateRv(0);  // bump to fully restart the run
  const bestRef = useRefRv(0);

  const replay = () => { setDead(null); setStarted(false); setPaused(false); setLive({ size: 2.1, score: 0, eaten: 0, rank: 5, rivals: 4, shield: false }); setBoardKey(k => k + 1); };

  // poll for "first touch" so the cue disappears the moment the player drags
  useEffectRv(() => {
    setStarted(false);
    const iv = setInterval(() => { const e = engineRef.current; if (e && e.state && e.state.touched) { setStarted(true); clearInterval(iv); } }, 150);
    return () => clearInterval(iv);
  }, [boardKey]);

  const onDead = (r) => {
    try { const b = parseInt(localStorage.getItem('hh_endless_best') || '0'); if (r.score > b) localStorage.setItem('hh_endless_best', String(r.score)); bestRef.current = Math.max(b, r.score); } catch (e) {}
    setDead(r);
  };

  const rankColor = live.rank === 1 ? 'var(--sun)' : live.rank <= 2 ? 'var(--mint)' : 'var(--ink)';

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,#8FE3FF,#E8F8FF)' }}>
      <EndlessBoard key={boardKey} paused={paused || !!dead} onUpdate={setLive} onDead={onDead} engineRef={engineRef} />

      {/* top HUD */}
      <div style={{ position: 'absolute', top: 46, left: 14, right: 14, zIndex: 50, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
          <div className="hh-level" style={{ background: 'linear-gradient(180deg,#9C82FF,var(--grape))' }}>OPEN WORLD</div>
          <div className="hh-sizepill"><i style={{ background: 'radial-gradient(circle at 35% 30%, #7FD2FF, var(--sky))' }} /> Size {live.size.toFixed(1)}</div>
          {live.shield && (
            <div className="hh-hudchip" style={{ gap: 6, background: 'linear-gradient(180deg,#34e0b6,var(--mint))', border: 'none', color: '#063b2c' }}>
              <span style={{ fontWeight: 800, fontSize: 13 }}>🛡 SHIELDED</span>
            </div>
          )}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
          <button className="hh-hudchip" onClick={() => setPaused(true)} style={{ cursor: 'pointer', fontSize: 14, fontWeight: 800 }}>❚❚</button>
          <div className="hh-hudchip" style={{ gap: 6 }}>
            <span style={{ fontFamily: 'var(--disp)', fontWeight: 800, fontSize: 13, color: rankColor }}>RANK #{live.rank}</span>
            <span style={{ color: 'var(--slate)', fontSize: 12, fontWeight: 700 }}>/ {live.rivals + 1}</span>
          </div>
        </div>
      </div>

      {/* big score */}
      <div style={{ position: 'absolute', top: 42, left: '50%', transform: 'translateX(-50%)', zIndex: 49, textAlign: 'center', pointerEvents: 'none' }}>
        <div className="num hh-outline" style={{ fontSize: 46, lineHeight: 0.9 }}>{live.score.toLocaleString()}</div>
      </div>

      {/* ready cue */}
      {!started && !dead && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 48, pointerEvents: 'none', display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 150 }}>
          <div className="hh-goalbanner" style={{ display: 'flex', alignItems: 'center', gap: 10, animation: 'hh-bob 2.2s ease-in-out infinite', fontSize: 15 }}>
            <span style={{ fontSize: 20 }}>👆</span>
            Drag to roam & eat — beat the <b>rivals</b>!
          </div>
        </div>
      )}

      {/* pause */}
      {paused && !dead && (
        <div className="hh-dialog-scrim">
          <div className="hh-dialog panel">
            <h2 className="hh-dialog-title">Paused</h2>
            <button className="btn block" onClick={() => setPaused(false)} style={{ marginBottom: 10 }}><I.play width={18} />Resume</button>
            <button className="btn ghost block" onClick={() => go('home')}>Quit to Home</button>
          </div>
        </div>
      )}

      {/* game over */}
      {dead && (
        <div className="hh-dialog-scrim">
          <div className="hh-dialog panel">
            <div className="eyebrow" style={{ color: 'var(--coral)' }}>Run over</div>
            <h2 className="hh-dialog-title" style={{ fontSize: 28 }}>{dead.by ? `Swallowed by ${dead.by}!` : 'Game over'}</h2>
            <div className="card" style={{ background: '#fff', padding: 16, margin: '14px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div><div className="num disp" style={{ fontSize: 26, color: 'var(--sky)' }}>{dead.score.toLocaleString()}</div><div className="eyebrow">Score</div></div>
              <div><div className="num disp" style={{ fontSize: 26, color: 'var(--mint)' }}>{dead.size.toFixed(1)}</div><div className="eyebrow">Final size</div></div>
              <div><div className="num disp" style={{ fontSize: 26, color: 'var(--grape)' }}>{dead.eaten}</div><div className="eyebrow">Eaten</div></div>
              <div><div className="num disp" style={{ fontSize: 26, color: 'var(--sun)' }}>#{dead.rank}</div><div className="eyebrow">Best rank</div></div>
            </div>
            {bestRef.current > 0 && <div style={{ fontWeight: 800, fontSize: 12.5, color: 'var(--slate)', marginBottom: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}><span style={{ color: 'var(--sun)' }}><I.star width={14} /></span>Personal best: <span className="num">{bestRef.current.toLocaleString()}</span></div>}
            <button className="btn sun block" onClick={replay} style={{ marginBottom: 10 }}><I.play width={18} />Play again</button>
            <button className="btn ghost block" onClick={() => go('home')}>Home</button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { EndlessGame, EndlessBoard });
