"use client";
import { useEffect, useRef, useState, useCallback } from "react";

// Konami-Code Easter Egg: ↑↑↓↓←→←→BA aktiviert einen "Matrix-Mode" mit
// fallenden Glyphen über dem ganzen Bildschirm. Konami-Code ist seit 1986
// ein Running-Gag — passt zum Terminal-/Hacker-Theme. reduced-motion
// respektiert (Konami-Code wird gar nicht erst aktiviert).

const KONAMI = [
  "ArrowUp", "ArrowUp", "ArrowDown", "ArrowDown",
  "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight",
  "b", "a",
] as const;

const GLYPHS = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン日月火水木金土山川海空0123456789".split("");

type Drop = { x: number; y: number; speed: number; length: number; chars: string[] };

export function KonamiMatrix() {
  const [armed, setArmed] = useState(false);
  const [progress, setProgress] = useState(0);
  const buf = useRef<string[]>([]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) return;
    function onKey(e: KeyboardEvent) {
      // Akzeptiere sowohl ArrowUp als auch "w" für ↑, "s" für ↓, "a" für ←, "d" für →
      const k = e.key === "w" ? "ArrowUp"
              : e.key === "s" ? "ArrowDown"
              : e.key === "a" ? "ArrowLeft"
              : e.key === "d" ? "ArrowRight"
              : e.key;
      buf.current.push(k);
      if (buf.current.length > KONAMI.length) buf.current.shift();
      const p = buf.current.filter((x, i) => x === KONAMI[i]).length;
      setProgress(p);
      if (buf.current.length === KONAMI.length && p === KONAMI.length) {
        setArmed((a) => !a);
        buf.current = [];
        setProgress(0);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Wenn aktiv: Konami-Hint oben rechts für 3s sichtbar
  const [showHint, setShowHint] = useState(false);
  useEffect(() => {
    if (armed) {
      setShowHint(true);
      const t = setTimeout(() => setShowHint(false), 3500);
      return () => clearTimeout(t);
    }
  }, [armed]);

  if (!armed) return null;
  return (
    <>
      <MatrixRain />
      {showHint ? (
        <div
          aria-live="polite"
          className="pointer-events-none fixed right-4 top-4 z-[400] rounded border border-accent bg-[color-mix(in_oklab,var(--bg-deep)_85%,transparent)] px-3 py-2 font-mono text-xs text-accent backdrop-blur-md"
        >
          <span className="mr-2 text-muted">//</span>matrix mode active
        </div>
      ) : null}
    </>
  );
}

function MatrixRain() {
  const ref = useRef<HTMLCanvasElement>(null);
  const raf = useRef<number | null>(null);
  const drops = useRef<Drop[]>([]);

  const init = useCallback(() => {
    const c = ref.current;
    if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    c.width = window.innerWidth * dpr;
    c.height = window.innerHeight * dpr;
    const ctx = c.getContext("2d");
    if (!ctx) return;
    ctx.scale(dpr, dpr);
    const cols = Math.ceil(window.innerWidth / 14);
    drops.current = Array.from({ length: cols }, (_, i) => spawn(i * 14, window.innerHeight));
    function spawn(x: number, y: number): Drop {
      return {
        x,
        y,
        speed: 0.6 + Math.random() * 1.4,
        length: 6 + Math.floor(Math.random() * 18),
        chars: Array.from({ length: 24 }, () => GLYPHS[Math.floor(Math.random() * GLYPHS.length)]),
      };
    }
    return { ctx, w: window.innerWidth, h: window.innerHeight, spawn };
  }, []);

  useEffect(() => {
    const c = ref.current;
    if (!c) return;
    const ctx = c.getContext("2d");
    if (!ctx) return;
    const dpr = window.devicePixelRatio || 1;
    c.width = window.innerWidth * dpr;
    c.height = window.innerHeight * dpr;
    ctx.scale(dpr, dpr);
    const cols = Math.ceil(window.innerWidth / 14);
    drops.current = Array.from({ length: cols }, (_, i) => ({
      x: i * 14,
      y: Math.random() * window.innerHeight,
      speed: 0.6 + Math.random() * 1.4,
      length: 6 + Math.floor(Math.random() * 18),
      chars: Array.from({ length: 24 }, () => GLYPHS[Math.floor(Math.random() * GLYPHS.length)]),
    }));

    function frame() {
      if (!ctx || !c) return;
      ctx.fillStyle = "rgba(10, 10, 16, 0.08)";
      ctx.fillRect(0, 0, c.width / dpr, c.height / dpr);
      const accent = getComputedStyle(document.documentElement).getPropertyValue("--accent").trim() || "#e84a8f";
      for (const d of drops.current) {
        for (let i = 0; i < d.length; i++) {
          const y = d.y - i * 14;
          if (y < 0) continue;
          const fade = 1 - i / d.length;
          ctx.fillStyle = accent;
          ctx.globalAlpha = fade * 0.85;
          ctx.font = "14px ui-monospace, monospace";
          const ch = d.chars[(Math.floor(d.y / 14) + i) % d.chars.length];
          ctx.fillText(ch, d.x, y);
        }
        d.y += d.speed;
        if (d.y - d.length * 14 > window.innerHeight) {
          d.y = -d.length * 14 + Math.random() * 200;
          d.length = 6 + Math.floor(Math.random() * 18);
        }
      }
      ctx.globalAlpha = 1;
      raf.current = requestAnimationFrame(frame);
    }
    raf.current = requestAnimationFrame(frame);
    function onResize() {
      if (!c || !ctx) return;
      c.width = window.innerWidth * dpr;
      c.height = window.innerHeight * dpr;
      ctx.scale(dpr, dpr);
      const cols = Math.ceil(window.innerWidth / 14);
      drops.current = Array.from({ length: cols }, (_, i) => ({
        x: i * 14,
        y: Math.random() * window.innerHeight,
        speed: 0.6 + Math.random() * 1.4,
        length: 6 + Math.floor(Math.random() * 18),
        chars: Array.from({ length: 24 }, () => GLYPHS[Math.floor(Math.random() * GLYPHS.length)]),
      }));
    }
    window.addEventListener("resize", onResize);
    return () => {
      if (raf.current) cancelAnimationFrame(raf.current);
      window.removeEventListener("resize", onResize);
    };
  }, []);

  return (
    <canvas
      ref={ref}
      aria-hidden
      className="pointer-events-none fixed inset-0 z-[300]"
      style={{ mixBlendMode: "screen" }}
    />
  );
}
