// Easter eggs:
//   01 — Konami (↑↑↓↓←→←→BA) → playable Asteroids
//   02 — Type "sudo" → dev mode (CSS reveal + git ribbon + footer)
//   03 — Shift + S → cursor satellite (8s SVG orbit)
//
// All eggs no-op on coarse pointers (touch-only) and on prefers-reduced-motion.
// Keystroke listeners ignore events while the user is in an input/textarea/contentEditable.

// ─── Egg root: one component that wires all three ──────────
function EasterEggs() {
  const enabled = useEggsEnabled();
  const [konamiHits, setKonamiHits] = React.useState(0);
  const [asteroidsOn, setAsteroidsOn] = React.useState(false);
  const [satellite, setSatellite] = React.useState(false);
  const [sudoBuf, setSudoBuf] = React.useState('');
  const [bestScore, setBestScore] = React.useState(() => Number(localStorage.getItem('asteroids-best') || 0));
  const [showBest, setShowBest] = React.useState(false);

  // ── Keystroke router ─────────────────────────────────────
  React.useEffect(() => {
    if (!enabled) return;

    const KONAMI = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'KeyB', 'KeyA'];
    let konamiIdx = 0;
    let sudoTimeout;

    function ignoreTarget(e) {
      const t = e.target;
      if (!t) return false;
      const tag = (t.tagName || '').toLowerCase();
      if (tag === 'input' || tag === 'textarea' || tag === 'select') return true;
      if (t.isContentEditable) return true;
      return false;
    }

    function onKey(e) {
      if (asteroidsOn) return; // asteroids has its own loop
      if (ignoreTarget(e)) return;

      // ── Konami ──
      // A key that advances the sequence belongs to it, so it isn't typed text for sudo.
      let konamiKey = false;
      if (e.code === KONAMI[konamiIdx]) {
        konamiKey = true;
        konamiIdx += 1;
        setKonamiHits(konamiIdx);
        if (konamiIdx === KONAMI.length) {
          konamiIdx = 0;
          setKonamiHits(0);
          // The listener is removed while the game runs, which also cancels the buffer's
          // decay timer, so clear the buffer here or its indicator sits over the game.
          setSudoBuf('');
          setAsteroidsOn(true);
          return;
        }
      } else {
        // restart count: if the new key matches index 0, set to 1
        konamiIdx = e.code === KONAMI[0] ? 1 : 0;
        setKonamiHits(konamiIdx);
      }

      // ── Sudo ──
      // capture printable single-character keys
      if (!konamiKey && e.key && e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
        setSudoBuf((b) => {
          const next = (b + e.key).slice(-12); // keep last 12 chars
          if (sudoTimeout) clearTimeout(sudoTimeout);
          sudoTimeout = setTimeout(() => setSudoBuf(''), 1800); // decay buffer
          // trigger on "sudo"
          if (next.endsWith('sudo') && document.documentElement.dataset.sudo !== 'on') {
            document.documentElement.dataset.sudo = 'on';
            setTimeout(() => setSudoBuf(''), 1200);
          }
          // trigger off on "exit"
          if (next.endsWith('exit') && document.documentElement.dataset.sudo === 'on') {
            document.documentElement.dataset.sudo = 'off';
            setTimeout(() => setSudoBuf(''), 1200);
          }
          return next;
        });
      }

      // ── Shift + S ──
      if (e.key === 'S' && e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
        setSatellite(true);
        setTimeout(() => setSatellite(false), 8000);
      }

      // ── Esc closes dev mode ──
      if (e.key === 'Escape' && document.documentElement.dataset.sudo === 'on') {
        document.documentElement.dataset.sudo = 'off';
      }
    }

    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('keydown', onKey);
      if (sudoTimeout) clearTimeout(sudoTimeout);
    };
  }, [enabled, asteroidsOn]);

  function handleAsteroidsExit(score) {
    setAsteroidsOn(false);
    if (score > bestScore) {
      localStorage.setItem('asteroids-best', String(score));
      setBestScore(score);
    }
    setShowBest(true);
    setTimeout(() => setShowBest(false), 5500);
  }

  if (!enabled) return null;

  return (
    <>
      {/* Konami sequence indicator */}
      {konamiHits > 0 && konamiHits < 10 && <KonamiHint hits={konamiHits} />}

      {/* Sudo buffer indicator */}
      {sudoBuf && <SudoBuffer buf={sudoBuf} />}

      {/* Asteroids overlay */}
      {asteroidsOn && <Asteroids onExit={handleAsteroidsExit} bestScore={bestScore} />}

      {/* Best-score badge after exit */}
      {showBest && (
        <div className="asteroids-best">★ BEST {bestScore}</div>
      )}

      {/* Cursor satellite */}
      {satellite && <Satellite />}
    </>
  );
}

function useEggsEnabled() {
  const [enabled, setEnabled] = React.useState(true);
  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const coarse = window.matchMedia('(pointer: coarse)').matches;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    setEnabled(!coarse && !reduced);
  }, []);
  return enabled;
}

// ─── Konami sequence hint ──────────────────────────────────
function KonamiHint({ hits }) {
  const keys = ['↑', '↑', '↓', '↓', '←', '→', '←', '→', 'B', 'A'];
  return (
    <div className="konami-hint" role="status" aria-live="polite">
      {keys.map((k, i) => (
        <span key={i} className={'k' + (i < hits ? ' hit' : '')}>{k}</span>
      ))}
    </div>
  );
}

// ─── Sudo buffer indicator ─────────────────────────────────
function SudoBuffer({ buf }) {
  // Highlight the "sudo" substring when it appears at the end
  const ends = buf.endsWith('sudo');
  return (
    <div className="sudo-buffer" role="status" aria-live="polite">
      <span>
        <span className="hint">$ </span>
        {ends ? (
          <>
            <span>{buf.slice(0, -4)}</span>
            <span className="typed">sudo</span>
          </>
        ) : (
          <span>{buf}</span>
        )}
        <span style={{ background: 'var(--sk-ink)', color: 'var(--sk-paper)', marginLeft: 1 }}>_</span>
      </span>
      <span className="hint">type ‘sudo’ to enter, ‘exit’ to leave</span>
    </div>
  );
}

// ─── Cursor satellite ──────────────────────────────────────
function Satellite() {
  const wrapRef = React.useRef(null);
  const pos = React.useRef({ x: -200, y: -200 });
  const tgt = React.useRef({ x: -200, y: -200 });
  const angle = React.useRef(0);
  const opacity = React.useRef(0);
  const fadeIn = React.useRef(true);

  React.useEffect(() => {
    function onMove(e) {
      tgt.current.x = e.clientX;
      tgt.current.y = e.clientY;
    }
    window.addEventListener('mousemove', onMove);
    let raf;
    const start = performance.now();
    function loop(t) {
      // lerp position toward target with momentum
      pos.current.x += (tgt.current.x - pos.current.x) * 0.18;
      pos.current.y += (tgt.current.y - pos.current.y) * 0.18;
      angle.current += 0.07;
      const el = wrapRef.current;
      if (el) {
        const rx = 26;
        const ry = 14;
        const ox = Math.cos(angle.current) * rx;
        const oy = Math.sin(angle.current) * ry;
        const ellipse = el.querySelector('ellipse');
        const sat = el.querySelector('circle');
        if (ellipse) {
          ellipse.setAttribute('cx', pos.current.x);
          ellipse.setAttribute('cy', pos.current.y);
        }
        if (sat) {
          sat.setAttribute('cx', pos.current.x + ox);
          sat.setAttribute('cy', pos.current.y + oy);
        }
        // fade in/out
        const elapsed = t - start;
        if (elapsed > 7400) {
          opacity.current = Math.max(0, opacity.current - 0.04);
        } else {
          opacity.current = Math.min(1, opacity.current + 0.08);
        }
        el.style.opacity = opacity.current;
      }
      raf = requestAnimationFrame(loop);
    }
    raf = requestAnimationFrame(loop);
    return () => {
      window.removeEventListener('mousemove', onMove);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <svg ref={wrapRef} className="sat-svg" width="100" height="60" style={{ left: 0, top: 0, opacity: 0 }}>
      <ellipse cx={-200} cy={-200} rx={26} ry={14} fill="none" stroke="var(--sk-peri-strong)" strokeWidth="0.6" strokeDasharray="2 3" />
      <circle cx={-200} cy={-200} r={3} fill="var(--sk-peri-strong)" />
    </svg>
  );
}

// ─── Asteroids ────────────────────────────────────────────
function Asteroids({ onExit, bestScore }) {
  const cvsRef = React.useRef(null);
  const [score, setScore] = React.useState(0);
  const [lives, setLives] = React.useState(3);
  const [paused, setPaused] = React.useState(false);
  const [over, setOver] = React.useState(false);
  const stateRef = React.useRef({
    ship: null,
    bullets: [],
    asteroids: [],
    keys: {},
    score: 0,
    lives: 3,
    over: false,
    paused: false,
    lastShot: 0,
    invincibleUntil: 0,
  });

  React.useEffect(() => {
    const cvs = cvsRef.current;
    const wPx = Math.min(window.innerWidth - 80, 960);
    const hPx = Math.min(window.innerHeight - 140, 600);
    cvs.width = wPx;
    cvs.height = hPx;
    const ctx = cvs.getContext('2d');

    const S = stateRef.current;
    S.ship = newShip(wPx / 2, hPx / 2);
    S.asteroids = spawnInitialAsteroids(5, wPx, hPx);

    // While the game is open it owns the keyboard: these listeners run in the capture phase,
    // so they see keys before anything else, and they stop them there, so nothing reaches the
    // page underneath (no scrolling, no focus moving to hidden links, no other shortcuts).
    // Keys with Cmd/Ctrl/Alt are left to the browser and OS.
    function swallow(e) {
      if (e.metaKey || e.ctrlKey || e.altKey) return false;
      e.preventDefault();
      e.stopImmediatePropagation();
      return true;
    }
    function onKD(e) {
      if (!swallow(e)) return;
      if (e.key === 'Escape') { onExit(S.score); return; }
      if (e.key === 'p' || e.key === 'P') { S.paused = !S.paused; setPaused(S.paused); return; }
      if (e.key === ' ') {
        if (S.over) {
          resetGame(wPx, hPx);
          return;
        }
        S.keys.fire = true;
      }
      if (e.key === 'ArrowUp') S.keys.up = true;
      if (e.key === 'ArrowLeft') S.keys.left = true;
      if (e.key === 'ArrowRight') S.keys.right = true;
    }
    function onKU(e) {
      // Release keys even when a modifier is down, or a held key would stick.
      swallow(e);
      if (e.key === ' ') S.keys.fire = false;
      if (e.key === 'ArrowUp') S.keys.up = false;
      if (e.key === 'ArrowLeft') S.keys.left = false;
      if (e.key === 'ArrowRight') S.keys.right = false;
    }
    function resetGame(w, h) {
      S.ship = newShip(w / 2, h / 2);
      S.bullets = [];
      S.asteroids = spawnInitialAsteroids(5, w, h);
      S.score = 0;
      S.lives = 3;
      S.over = false;
      S.invincibleUntil = performance.now() + 1500;
      setScore(0); setLives(3); setOver(false);
    }

    window.addEventListener('keydown', onKD, true);
    window.addEventListener('keyup', onKU, true);

    let raf;
    let last = performance.now();
    function loop(t) {
      const dt = Math.min(48, t - last) / 16; // normalised dt (1 ≈ 60fps frame)
      last = t;
      if (!S.paused && !S.over) update(dt, t, cvs.width, cvs.height);
      draw(ctx, cvs.width, cvs.height, t);
      raf = requestAnimationFrame(loop);
    }

    function update(dt, now, W, H) {
      // ship
      const sh = S.ship;
      if (S.keys.left) sh.a -= 0.08 * dt;
      if (S.keys.right) sh.a += 0.08 * dt;
      if (S.keys.up) {
        sh.vx += Math.cos(sh.a) * 0.12 * dt;
        sh.vy += Math.sin(sh.a) * 0.12 * dt;
        sh.thrust = true;
      } else { sh.thrust = false; }
      sh.vx *= Math.pow(0.99, dt);
      sh.vy *= Math.pow(0.99, dt);
      sh.x = wrap(sh.x + sh.vx * dt, W);
      sh.y = wrap(sh.y + sh.vy * dt, H);

      // fire
      if (S.keys.fire && now - S.lastShot > 220) {
        S.bullets.push({
          x: sh.x + Math.cos(sh.a) * 12,
          y: sh.y + Math.sin(sh.a) * 12,
          vx: Math.cos(sh.a) * 6 + sh.vx,
          vy: Math.sin(sh.a) * 6 + sh.vy,
          life: 60,
        });
        S.lastShot = now;
      }
      // bullets
      S.bullets = S.bullets.filter((b) => b.life > 0);
      for (const b of S.bullets) {
        b.x = wrap(b.x + b.vx * dt, W);
        b.y = wrap(b.y + b.vy * dt, H);
        b.life -= dt;
      }
      // asteroids
      for (const a of S.asteroids) {
        a.x = wrap(a.x + a.vx * dt, W);
        a.y = wrap(a.y + a.vy * dt, H);
        a.rot += a.spin * dt;
      }
      // collisions: bullet × asteroid
      const newAst = [];
      for (const a of S.asteroids) {
        let hit = false;
        for (const b of S.bullets) {
          if (dist2(b.x, b.y, a.x, a.y) < a.r * a.r) {
            hit = true;
            b.life = 0;
            // award points
            S.score += a.size === 3 ? 20 : a.size === 2 ? 50 : 100;
            // split
            if (a.size > 1) {
              for (let i = 0; i < 2; i++) {
                newAst.push(makeAsteroid(a.x, a.y, a.size - 1));
              }
            }
            break;
          }
        }
        if (!hit) newAst.push(a);
      }
      S.asteroids = newAst;
      setScore(S.score);

      // ship × asteroid
      if (now > S.invincibleUntil) {
        for (const a of S.asteroids) {
          if (dist2(sh.x, sh.y, a.x, a.y) < (a.r + 8) * (a.r + 8)) {
            S.lives -= 1;
            setLives(S.lives);
            if (S.lives <= 0) {
              S.over = true;
              setOver(true);
            } else {
              S.ship = newShip(W / 2, H / 2);
              S.invincibleUntil = now + 1500;
            }
            break;
          }
        }
      }

      // respawn if all cleared
      if (S.asteroids.length === 0) {
        const next = Math.min(10, 5 + Math.floor(S.score / 1000));
        S.asteroids = spawnInitialAsteroids(next, W, H);
      }
    }

    function draw(ctx, W, H, now) {
      // bg
      const paper = getCssVar('--sk-paper');
      const ink = getCssVar('--sk-ink');
      const leaf = getCssVar('--sk-leaf-strong');
      const carrot = getCssVar('--sk-carrot-strong');
      const peri = getCssVar('--sk-peri-strong');
      const slate = getCssVar('--sk-slate-strong');
      const inkFaint = getCssVar('--sk-ink-faint');

      ctx.fillStyle = paper;
      ctx.fillRect(0, 0, W, H);

      // subtle scanline grid for vibes (very low contrast)
      ctx.strokeStyle = inkFaint;
      ctx.globalAlpha = 0.08;
      ctx.lineWidth = 1;
      for (let y = 0; y < H; y += 40) {
        ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke();
      }
      for (let x = 0; x < W; x += 40) {
        ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke();
      }
      ctx.globalAlpha = 1;

      // asteroids — each gets a hue based on size
      ctx.strokeStyle = ink;
      ctx.lineWidth = 1.5;
      for (const a of S.asteroids) {
        ctx.save();
        ctx.translate(a.x, a.y);
        ctx.rotate(a.rot);
        ctx.strokeStyle = a.size === 3 ? carrot : a.size === 2 ? peri : slate;
        ctx.fillStyle = withAlpha(a.size === 3 ? carrot : a.size === 2 ? peri : slate, 0.08);
        ctx.beginPath();
        for (let i = 0; i < a.shape.length; i++) {
          const p = a.shape[i];
          if (i === 0) ctx.moveTo(p.x, p.y); else ctx.lineTo(p.x, p.y);
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        ctx.restore();
      }

      // bullets
      ctx.fillStyle = leaf;
      for (const b of S.bullets) {
        ctx.beginPath();
        ctx.arc(b.x, b.y, 2.2, 0, Math.PI * 2);
        ctx.fill();
      }

      // ship
      const sh = S.ship;
      const isInvincible = now < S.invincibleUntil;
      const blink = isInvincible && Math.floor(now / 100) % 2 === 0;
      if (!blink) {
        ctx.save();
        ctx.translate(sh.x, sh.y);
        ctx.rotate(sh.a);
        ctx.strokeStyle = ink;
        ctx.fillStyle = withAlpha(leaf, 0.18);
        ctx.lineWidth = 1.6;
        ctx.beginPath();
        ctx.moveTo(14, 0);
        ctx.lineTo(-10, 8);
        ctx.lineTo(-6, 0);
        ctx.lineTo(-10, -8);
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        // thrust
        if (sh.thrust && Math.floor(now / 60) % 2 === 0) {
          ctx.strokeStyle = carrot;
          ctx.beginPath();
          ctx.moveTo(-6, -4);
          ctx.lineTo(-14, 0);
          ctx.lineTo(-6, 4);
          ctx.stroke();
        }
        ctx.restore();
      }

      // game over
      if (S.over) {
        ctx.fillStyle = withAlpha(ink, 0.78);
        ctx.fillRect(0, 0, W, H);
        ctx.fillStyle = leaf;
        ctx.font = '500 36px Roboto, sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('GAME OVER', W / 2, H / 2 - 12);
        ctx.font = '12px IBM Plex Mono, monospace';
        ctx.fillStyle = paper;
        ctx.fillText(`SCORE ${S.score}   ·   BEST ${bestScore}`, W / 2, H / 2 + 18);
        ctx.fillStyle = withAlpha(paper, 0.7);
        ctx.fillText('SPACE to restart   ·   ESC to leave', W / 2, H / 2 + 44);
      }
    }

    raf = requestAnimationFrame(loop);
    return () => {
      window.removeEventListener('keydown', onKD, true);
      window.removeEventListener('keyup', onKU, true);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <div className="asteroids" onClick={(e) => { if (e.target.classList.contains('asteroids')) onExit(stateRef.current.score); }}>
      <canvas ref={cvsRef} />
      <div className="asteroids-hud">
        <span>SCORE {String(score).padStart(5, '0')}</span>
        <span>LIVES {'▲'.repeat(Math.max(0, lives))}</span>
        <span>BEST {bestScore}</span>
        {paused && <span style={{ color: 'var(--sk-carrot-strong)' }}>PAUSED</span>}
      </div>
      <div className="asteroids-help">
        ← → rotate · ↑ thrust · SPACE fire · P pause · ESC leave
      </div>
    </div>
  );
}

// ─── Game helpers ──────────────────────────────────────────
function newShip(x, y) {
  return { x, y, vx: 0, vy: 0, a: -Math.PI / 2, thrust: false };
}
function spawnInitialAsteroids(n, W, H) {
  const out = [];
  for (let i = 0; i < n; i++) {
    // spawn away from center
    let x, y;
    do {
      x = Math.random() * W;
      y = Math.random() * H;
    } while (dist2(x, y, W / 2, H / 2) < 140 * 140);
    out.push(makeAsteroid(x, y, 3));
  }
  return out;
}
function makeAsteroid(x, y, size) {
  const r = size === 3 ? 36 : size === 2 ? 22 : 12;
  const sides = 9 + Math.floor(Math.random() * 4);
  const shape = [];
  for (let i = 0; i < sides; i++) {
    const ang = (i / sides) * Math.PI * 2;
    const rr = r * (0.78 + Math.random() * 0.38);
    shape.push({ x: Math.cos(ang) * rr, y: Math.sin(ang) * rr });
  }
  const v = (size === 3 ? 0.7 : size === 2 ? 1.1 : 1.6) * (1 + Math.random() * 0.4);
  const dir = Math.random() * Math.PI * 2;
  return {
    x, y, r, size, shape,
    vx: Math.cos(dir) * v,
    vy: Math.sin(dir) * v,
    rot: Math.random() * Math.PI * 2,
    spin: (Math.random() - 0.5) * 0.04,
  };
}
function wrap(v, max) {
  if (v < 0) return v + max;
  if (v > max) return v - max;
  return v;
}
function dist2(x1, y1, x2, y2) {
  const dx = x1 - x2, dy = y1 - y2;
  return dx * dx + dy * dy;
}
function getCssVar(name) {
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || '#222';
}
function withAlpha(color, a) {
  // works with oklch() strings: wrap in color-mix
  return `color-mix(in oklab, ${color} ${Math.round(a * 100)}%, transparent)`;
}

Object.assign(window, { EasterEggs });
