// --- Mini-game: Catch the Pension Check ---
// Click falling "€" and "☕" to score. Avoid "💀" (boss).

function MiniGame({ onClose }) {
  const [score, setScore] = useState(0);
  const [time, setTime] = useState(30);
  const [items, setItems] = useState([]);
  const [gameOver, setGameOver] = useState(false);
  const [hi, setHi] = useState(() => Number(localStorage.getItem('gg_highscore') || 0));
  const idRef = useRef(0);

  useEffect(() => {
    if (gameOver) return;
    const spawn = setInterval(() => {
      const roll = Math.random();
      let kind = 'coin';
      if (roll < 0.12) kind = 'boss';
      else if (roll < 0.35) kind = 'coffee';
      setItems(prev => [...prev, {
        id: ++idRef.current,
        kind,
        x: 4 + Math.random() * 92,
        y: -10,
        v: 0.3 + Math.random() * 0.6,
      }]);
    }, 520);
    return () => clearInterval(spawn);
  }, [gameOver]);

  useEffect(() => {
    if (gameOver) return;
    let last = performance.now();
    let raf;
    const loop = (t) => {
      const dt = t - last; last = t;
      setItems(prev => prev
        .map(it => ({ ...it, y: it.y + it.v * dt * 0.06 }))
        .filter(it => it.y < 110));
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [gameOver]);

  useEffect(() => {
    if (gameOver) return;
    const id = setInterval(() => setTime(t => {
      if (t <= 1) { setGameOver(true); return 0; }
      return t - 1;
    }), 1000);
    return () => clearInterval(id);
  }, [gameOver]);

  useEffect(() => {
    if (gameOver && score > hi) {
      localStorage.setItem('gg_highscore', String(score));
      setHi(score);
    }
  }, [gameOver]);

  const hit = (it) => {
    setItems(prev => prev.filter(p => p.id !== it.id));
    if (it.kind === 'coin') setScore(s => s + 10);
    else if (it.kind === 'coffee') setScore(s => s + 25);
    else if (it.kind === 'boss') setScore(s => Math.max(0, s - 20));
  };

  const restart = () => {
    setScore(0); setTime(30); setItems([]); setGameOver(false);
  };

  const icon = (k) => k === 'coin' ? '€' : k === 'coffee' ? '☕' : '💀';
  const color = (k) => k === 'coin' ? 'var(--amber)' : k === 'coffee' ? 'var(--ink-bright)' : 'var(--red)';

  return (
    <div className="modal" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="mg-box">
        <div className="mg-head">
          <span>◉ ΣΥΝΤΑΞΗ RUSH — catch the € and ☕, dodge 💀</span>
          <button onClick={onClose}>[ESC]</button>
        </div>
        <div className="mg-stage">
          {!gameOver && items.map(it => (
            <div key={it.id} className="mg-item"
              style={{ left: it.x + '%', top: it.y + '%', color: color(it.kind), textShadow: '0 0 8px ' + color(it.kind) }}
              onMouseDown={() => hit(it)}
            >{icon(it.kind)}</div>
          ))}
          {gameOver && (
            <div style={{position:'absolute', inset:0, display:'grid', placeItems:'center', background:'rgba(0,0,0,0.7)'}}>
              <div style={{textAlign:'center'}}>
                <div className="pixel-label amber" style={{fontSize:16, marginBottom:10}}>GAME OVER</div>
                <div className="hero-title" style={{fontSize:28, margin:'4px 0'}}>SCORE {score}</div>
                <div className="mono" style={{textShadow:'none', color:'var(--ink-dim)'}}>HIGH SCORE: {hi}</div>
                <button className="btn amber" style={{marginTop:18}} onClick={restart}>AGAIN</button>
              </div>
            </div>
          )}
        </div>
        <div className="mg-hud">
          <span>SCORE <span className="amber">{score}</span></span>
          <span>HI <span className="bright">{hi}</span></span>
          <span>TIME <span className="red" style={{textShadow:'none'}}>{time}s</span></span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MiniGame });
