/* global React */
const { useEffect, useRef, useState } = React;

/* ============================================================
   PROJECT ART — cover image per project with arcade overlays
   ============================================================ */
function ProjectArt({ src, alt, tag, score }) {
  return (
    <div className="project-art">
      <img className="project-art-img pixelated" src={src} alt={alt} />
      <span className="label-tag">{tag}</span>
      <span className="score">{score}</span>
    </div>
  );
}

const PROJECTS = [
  {
    title: 'The Mines of White Label',
    platform: 'Steam',
    url: 'https://store.steampowered.com/app/2792840/The_Mines_of_White_Label/',
    Art: () => <ProjectArt src="assets/whitelabel.png" alt="The Mines of White Label" tag="1P · ARCADE" score="HI 999900" />,
  },
  {
    title: 'Mutant Hunter',
    platform: 'Steam',
    url: 'https://store.steampowered.com/app/3045220/Mutant_Hunter/',
    Art: () => <ProjectArt src="assets/mutanthunter.png" alt="Mutant Hunter" tag="SHOOTER" score="P1 · 045200" />,
  },
  {
    title: 'Varadia',
    platform: 'Web',
    url: 'https://www.varadia.com/',
    Art: () => <ProjectArt src="assets/varadia.png" alt="Varadia" tag="RPG · OPEN WORLD" score="LV 42" />,
  },
  {
    title: 'RareIcon',
    platform: 'Steam',
    url: 'https://store.steampowered.com/app/2238370/RareIcon/',
    Art: () => <ProjectArt src="assets/rareicon.png" alt="RareIcon" tag="SIMULATION" score="FPS · 60" />,
  },
];

/* ============================================================
   BREAKOUT — Konami code mini-game
   ============================================================ */
function Breakout({ onClose }) {
  const canvasRef = useRef(null);
  const [score, setScore] = useState(0);
  const [lives, setLives] = useState(3);
  const [status, setStatus] = useState('PLAY'); // PLAY | WIN | LOSE
  const stateRef = useRef({ paddle: 0, ball: null, bricks: [], keys: {}, score: 0, lives: 3 });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    canvas.width = 320;
    canvas.height = 240;
    const ctx = canvas.getContext('2d');
    const W = 320, H = 240;
    const PADDLE_W = 48, PADDLE_H = 6;

    const reset = () => {
      stateRef.current.paddle = (W - PADDLE_W) / 2;
      stateRef.current.ball = { x: W/2, y: H - 40, vx: 1.5, vy: -1.5, size: 4 };
      const bricks = [];
      const cols = 8, rows = 5;
      const bw = 36, bh = 10, gap = 2, top = 30, leftPad = (W - cols*(bw+gap) + gap) / 2;
      const colors = ['#ff5e8a','#ffb627','#5be7ff','#5cff9e','#c5cfee'];
      for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
        bricks.push({ x: leftPad + c*(bw+gap), y: top + r*(bh+gap), w: bw, h: bh, alive: true, color: colors[r] });
      }
      stateRef.current.bricks = bricks;
    };
    reset();

    const onKey = (e) => {
      stateRef.current.keys[e.key] = e.type === 'keydown';
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    window.addEventListener('keyup', onKey);

    const onMove = (e) => {
      const r = canvas.getBoundingClientRect();
      const x = (e.clientX - r.left) * (W / r.width);
      stateRef.current.paddle = Math.max(0, Math.min(W - PADDLE_W, x - PADDLE_W/2));
    };
    canvas.addEventListener('mousemove', onMove);
    canvas.addEventListener('touchmove', (e) => {
      const t = e.touches[0]; if (t) onMove(t);
    });

    let raf;
    let last = 0;
    const STEP = 32; // ~30fps frame-stepped
    const tick = (t) => {
      if (t - last >= STEP) {
        last = t;
        const s = stateRef.current;
        // Keyboard paddle
        if (s.keys['ArrowLeft']) s.paddle = Math.max(0, s.paddle - 8);
        if (s.keys['ArrowRight']) s.paddle = Math.min(W - PADDLE_W, s.paddle + 8);

        // Ball
        const b = s.ball;
        b.x += b.vx; b.y += b.vy;
        if (b.x < 0 || b.x > W - b.size) b.vx *= -1;
        if (b.y < 0) b.vy *= -1;
        // paddle collision
        if (b.y + b.size >= H - 14 && b.x + b.size >= s.paddle && b.x <= s.paddle + PADDLE_W && b.vy > 0) {
          b.vy *= -1;
          const offset = (b.x - s.paddle) / PADDLE_W - 0.5;
          b.vx = offset * 4;
        }
        // brick collisions
        for (const br of s.bricks) {
          if (!br.alive) continue;
          if (b.x + b.size >= br.x && b.x <= br.x + br.w && b.y + b.size >= br.y && b.y <= br.y + br.h) {
            br.alive = false;
            b.vy *= -1;
            s.score += 100;
            setScore(s.score);
            break;
          }
        }
        if (s.bricks.every(br => !br.alive)) { setStatus('WIN'); cancelAnimationFrame(raf); return; }
        // Lose
        if (b.y > H) {
          s.lives -= 1;
          setLives(s.lives);
          if (s.lives <= 0) { setStatus('LOSE'); cancelAnimationFrame(raf); return; }
          b.x = W/2; b.y = H - 40; b.vx = 1.5; b.vy = -1.5;
        }

        // Render
        ctx.fillStyle = '#000'; ctx.fillRect(0,0,W,H);
        // bricks
        for (const br of s.bricks) {
          if (!br.alive) continue;
          ctx.fillStyle = br.color;
          ctx.fillRect(br.x, br.y, br.w, br.h);
          ctx.fillStyle = 'rgba(0,0,0,0.3)';
          ctx.fillRect(br.x + br.w - 2, br.y, 2, br.h);
          ctx.fillRect(br.x, br.y + br.h - 2, br.w, 2);
        }
        // paddle
        ctx.fillStyle = '#5be7ff';
        ctx.fillRect(s.paddle, H - 14, PADDLE_W, PADDLE_H);
        // ball
        ctx.fillStyle = '#ffb627';
        ctx.fillRect(Math.floor(b.x), Math.floor(b.y), b.size, b.size);
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('keyup', onKey);
    };
  }, [onClose]);

  return (
    <div className="konami-overlay" role="dialog" aria-label="Bonus mini-game">
      <div className="konami-modal">
        <div className="konami-header">
          <div className="konami-title">★ BONUS LEVEL ★ BLAST-OUT</div>
          <button className="konami-close" onClick={onClose}>EXIT [ESC]</button>
        </div>
        <div className="konami-canvas-wrap">
          <canvas ref={canvasRef} className="konami-canvas" />
          {status !== 'PLAY' && (
            <div style={{
              position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
              background: 'rgba(0,0,0,0.85)', fontFamily: 'var(--bb-display)',
              color: status === 'WIN' ? '#5be7ff' : '#ff5e8a', textAlign: 'center', padding: 16,
            }}>
              <div>
                <div style={{ fontSize: 18, marginBottom: 12 }}>
                  {status === 'WIN' ? 'YOU WIN!' : 'GAME OVER'}
                </div>
                <div style={{ fontSize: 11, color: '#c5cfee' }}>SCORE {score}</div>
              </div>
            </div>
          )}
        </div>
        <div className="konami-info">
          <span>← → / MOUSE TO MOVE</span>
          <span>SCORE {String(score).padStart(6, '0')}</span>
          <span>LIVES {'♥'.repeat(lives)}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PROJECTS, Breakout });
