// Easter eggs — Konami code rave + slash-key command palette

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

const useKonami = (onTrigger) => {
  React.useEffect(() => {
    let idx = 0;
    const onKey = (e) => {
      const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;
      const expected = KONAMI[idx];
      if (k === expected || k === expected?.toLowerCase()) {
        idx++;
        if (idx === KONAMI.length) { onTrigger(); idx = 0; }
      } else {
        idx = (k === KONAMI[0]) ? 1 : 0;
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onTrigger]);
};

const fireConfetti = () => {
  const colors = ["#A0EEC0", "#8AE9C1", "#86CD82", "#72A276", "#C9F2D8"];
  for (let i = 0; i < 80; i++) {
    const c = document.createElement("div");
    c.className = "confetti";
    c.style.left = Math.random() * 100 + "vw";
    c.style.background = colors[Math.floor(Math.random() * colors.length)];
    c.style.animationDelay = Math.random() * 0.4 + "s";
    c.style.animationDuration = (1.8 + Math.random() * 1.5) + "s";
    c.style.transform = `rotate(${Math.random() * 360}deg)`;
    document.body.appendChild(c);
    setTimeout(() => c.remove(), 3500);
  }
};

const KonamiRave = ({ onDone }) => {
  React.useEffect(() => {
    document.body.classList.add("rave");
    fireConfetti();
    const t = setTimeout(() => {
      document.body.classList.remove("rave");
      onDone();
    }, 4500);
    return () => { clearTimeout(t); document.body.classList.remove("rave"); };
  }, [onDone]);
  return null;
};

// ---------- Command palette ----------

const buildCommands = ({ setTheme, openSection, downloadResume, fireKonami }) => [
  { id: "go-about", label: "Go to About", hint: "scroll", icon: "arrow-down", run: () => openSection("about") },
  { id: "go-exp", label: "Go to Experience", hint: "scroll", icon: "briefcase", run: () => openSection("experience") },
  { id: "go-skills", label: "Go to Skills", hint: "scroll", icon: "spark", run: () => openSection("skills") },
  { id: "go-contact", label: "Go to Contact", hint: "scroll", icon: "mail", run: () => openSection("contact") },
  { id: "theme-light", label: "Theme: Light", hint: "ui", icon: "sun", run: () => setTheme("light") },
  { id: "theme-dark", label: "Theme: Dark", hint: "ui", icon: "moon", run: () => setTheme("dark") },
  { id: "email", label: "Email Noah", hint: "external", icon: "mail", run: () => { window.location.href = "mailto:" + NOAH.email; } },
  { id: "github", label: "Open GitHub", hint: "external", icon: "github", run: () => window.open(NOAH.github, "_blank") },
  { id: "linkedin", label: "Open LinkedIn", hint: "external", icon: "linkedin", run: () => window.open(NOAH.linkedin, "_blank") },
  { id: "rave", label: "Activate rave mode", hint: "secret", icon: "spark", run: fireKonami },
];

const CommandPalette = ({ open, onClose, setTheme, fireKonami }) => {
  const [q, setQ] = React.useState("");
  const [active, setActive] = React.useState(0);
  const inputRef = React.useRef(null);

  const openSection = (id) => {
    onClose();
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    }, 50);
  };

  const commands = React.useMemo(
    () => buildCommands({ setTheme, openSection, fireKonami }),
    [setTheme, fireKonami]
  );

  const filtered = React.useMemo(() => {
    if (!q.trim()) return commands;
    const lq = q.toLowerCase();
    return commands.filter(c => c.label.toLowerCase().includes(lq));
  }, [q, commands]);

  React.useEffect(() => {
    if (open) {
      setQ(""); setActive(0);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  React.useEffect(() => { setActive(0); }, [q]);

  const handleKey = (e) => {
    if (e.key === "Escape") { onClose(); return; }
    if (e.key === "ArrowDown") { e.preventDefault(); setActive(a => Math.min(a + 1, filtered.length - 1)); }
    if (e.key === "ArrowUp") { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
    if (e.key === "Enter") {
      e.preventDefault();
      const cmd = filtered[active];
      if (cmd) { cmd.run(); onClose(); }
    }
  };

  if (!open) return null;
  return (
    <div className="cp-backdrop" onClick={onClose}>
      <div className="cp" onClick={(e) => e.stopPropagation()}>
        <div className="cp-input-row">
          <Icon name="search" />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={handleKey}
            placeholder="What do you need?"
          />
          <span className="kbd">Esc</span>
        </div>
        <div className="cp-list">
          {filtered.length === 0 && (
            <div style={{ padding: 16, color: "var(--text-mute)", fontSize: 14 }}>
              No commands. Try “theme”, “github”, or just type a section name.
            </div>
          )}
          {filtered.map((c, i) => (
            <div
              key={c.id}
              className={`cp-item ${i === active ? "is-active" : ""}`}
              onMouseEnter={() => setActive(i)}
              onClick={() => { c.run(); onClose(); }}
            >
              <span className="cp-ico"><Icon name={c.icon} size={14} /></span>
              <span className="cp-label">{c.label}</span>
              <span className="cp-hint">{c.hint}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const useSlashShortcut = (open, setOpen) => {
  React.useEffect(() => {
    const onKey = (e) => {
      const tag = document.activeElement?.tagName;
      const inField = tag === "INPUT" || tag === "TEXTAREA";
      if ((e.key === "/" || (e.key === "k" && (e.metaKey || e.ctrlKey))) && !inField) {
        e.preventDefault();
        setOpen(true);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [setOpen]);
};

Object.assign(window, { useKonami, KonamiRave, CommandPalette, useSlashShortcut });
