"use client";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import type { Locale } from "@/i18n/routes";
import { publicPath } from "@/i18n/routes";

type Item = {
  id: string;
  label: string;
  hint?: string;
  group: "nav" | "project" | "action" | "easter";
  icon?: ReactNode;
  shortcut?: string;
  action: () => void;
};

export function CommandPalette({
  locale,
  projects,
}: {
  locale: Locale;
  projects: Array<{ slug: string; summary: string; category: string; status: string }>;
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [active, setActive] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const router = useRouter();

  // ⌘K / Ctrl+K öffnet das Palette. ESC schließt.
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen((v) => !v);
      } else if (e.key === "Escape" && open) {
        setOpen(false);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  // Bei Öffnen: Query zurücksetzen, Input fokussieren.
  useEffect(() => {
    if (open) {
      setQuery("");
      setActive(0);
      requestAnimationFrame(() => inputRef.current?.focus());
    }
  }, [open]);

  const items: Item[] = useMemo(() => {
    const closeAndGo = (href: string) => () => {
      setOpen(false);
      router.push(href);
    };
    const nav: Item[] = [
      { id: "nav-home", label: locale === "de" ? "Startseite" : "Home", hint: "/", group: "nav", action: closeAndGo(publicPath(locale, "home")) },
      { id: "nav-about", label: locale === "de" ? "Über mich" : "About", hint: publicPath(locale, "about"), group: "nav", action: closeAndGo(publicPath(locale, "about")) },
      { id: "nav-projects", label: locale === "de" ? "Projekte" : "Projects", hint: publicPath(locale, "projects"), group: "nav", action: closeAndGo(publicPath(locale, "projects")) },
      { id: "nav-contact", label: locale === "de" ? "Kontakt" : "Contact", hint: publicPath(locale, "contact"), group: "nav", action: closeAndGo(publicPath(locale, "contact")) },
      { id: "nav-en", label: "English version", hint: "/en", group: "nav", shortcut: "en", action: () => { setOpen(false); router.push("/en"); } },
      { id: "nav-de", label: "Deutsche Version", hint: "/", group: "nav", shortcut: "de", action: () => { setOpen(false); router.push("/"); } },
    ];
    const projectItems: Item[] = projects.map((p) => ({
      id: `proj-${p.slug}`,
      label: p.slug,
      hint: `${p.category} · ${p.status}`,
      group: "project",
      action: closeAndGo(publicPath(locale, "projectItem", p.slug)),
    }));
    const actions: Item[] = [
      { id: "act-source", label: locale === "de" ? "Quellcode öffnen" : "Open source code", hint: "Gitea", group: "action", shortcut: "g s", action: () => { setOpen(false); window.open("https://gitea.free-warez.win/eldov/eldov-win", "_blank"); } },
      { id: "act-admin", label: locale === "de" ? "Admin" : "Admin", hint: "/admin/login", group: "action", shortcut: "a", action: closeAndGo("/admin/login") },
      { id: "act-wmake", label: "w-make.com", hint: locale === "de" ? "Geschäftliche Site" : "Business site", group: "action", action: () => { setOpen(false); window.open("https://w-make.com", "_blank"); } },
    ];
    const easter: Item[] = [
      { id: "easter-theme", label: locale === "de" ? "Theme: Matrix" : "Theme: Matrix", hint: "Easter egg", group: "easter", shortcut: "matrix", action: () => { setOpen(false); document.documentElement.classList.toggle("theme-matrix"); } },
      { id: "easter-coffee", label: "☕ coffee", hint: "Just a message", group: "easter", action: () => { setOpen(false); alert("Kaffee wird gebrüht. Bitte warten."); } },
    ];
    return [...nav, ...projectItems, ...actions, ...easter];
  }, [locale, projects, router]);

  const filtered = useMemo(() => {
    if (!query.trim()) return items;
    const q = query.toLowerCase();
    return items.filter((i) =>
      [i.label, i.hint, i.group].filter(Boolean).some((s) => s!.toLowerCase().includes(q))
    );
  }, [items, query]);

  useEffect(() => { setActive(0); }, [query]);

  function onKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
    if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(filtered.length - 1, a + 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
    else if (e.key === "Enter") { e.preventDefault(); filtered[active]?.action(); }
  }

  if (!open) return null;
  const groups = ["nav", "project", "action", "easter"] as const;
  const groupLabels: Record<typeof groups[number], string> = {
    nav: locale === "de" ? "Navigation" : "Navigation",
    project: locale === "de" ? "Projekte" : "Projects",
    action: locale === "de" ? "Aktionen" : "Actions",
    easter: locale === "de" ? "Easter Eggs" : "Easter Eggs",
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Command palette"
      className="fixed inset-0 z-[300] flex items-start justify-center px-4 pt-[10vh]"
      onClick={() => setOpen(false)}
    >
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
      <div
        className="ascii-box relative z-10 w-full max-w-xl bg-[var(--bg-deep)] shadow-2xl"
        style={{ boxShadow: "0 24px 60px rgba(0,0,0,0.6), 0 0 0 1px var(--hairline)" }}
        onClick={(e) => e.stopPropagation()}
        onKeyDown={onKeyDown}
      >
        <div className="flex items-center gap-3 border-b border-hairline px-4 py-3">
          <span className="font-mono text-xs uppercase tracking-wider text-muted">⌘K</span>
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={locale === "de" ? "Suchen, navigieren, ausführen…" : "Search, navigate, run…"}
            className="flex-1 bg-transparent font-mono text-sm text-[var(--fg)] outline-none placeholder:text-muted"
            autoComplete="off"
            spellCheck={false}
          />
          <kbd className="rounded border border-hairline px-1.5 py-0.5 font-mono text-xs text-muted">esc</kbd>
        </div>
        <div ref={listRef} className="max-h-[55vh] overflow-y-auto py-2">
          {filtered.length === 0 ? (
            <div className="px-4 py-8 text-center font-mono text-xs text-muted">
              {locale === "de" ? "Keine Treffer für" : "No results for"} &quot;{query}&quot;
            </div>
          ) : (
            groups.map((g) => {
              const itemsInGroup = filtered.filter((i) => i.group === g);
              if (itemsInGroup.length === 0) return null;
              return (
                <div key={g} className="mb-1">
                  <div className="px-4 py-1 font-mono text-[10px] uppercase tracking-wider text-muted">
                    {groupLabels[g]}
                  </div>
                  {itemsInGroup.map((i) => {
                    const globalIndex = filtered.indexOf(i);
                    const isActive = globalIndex === active;
                    return (
                      <button
                        key={i.id}
                        type="button"
                        onMouseEnter={() => setActive(globalIndex)}
                        onClick={() => i.action()}
                        className={`flex w-full items-center gap-3 px-4 py-2 text-left transition-colors ${
                          isActive ? "bg-[color-mix(in_oklab,var(--accent)_10%,transparent)]" : ""
                        }`}
                      >
                        <span className={`flex h-5 w-5 items-center justify-center font-mono text-xs ${isActive ? "text-accent" : "text-muted"}`}>
                          {isActive ? "▶" : " "}
                        </span>
                        <span className={`flex-1 truncate text-sm ${isActive ? "text-[var(--fg)]" : "text-[var(--fg-dim)]"}`}>
                          {i.label}
                        </span>
                        {i.hint ? (
                          <span className="hidden font-mono text-xs text-muted sm:inline">{i.hint}</span>
                        ) : null}
                        {i.shortcut ? (
                          <kbd className="rounded border border-hairline px-1.5 py-0.5 font-mono text-[10px] text-muted">{i.shortcut}</kbd>
                        ) : null}
                      </button>
                    );
                  })}
                </div>
              );
            })
          )}
        </div>
        <div className="flex items-center justify-between border-t border-hairline px-4 py-2 font-mono text-[10px] uppercase tracking-wider text-muted">
          <span>{filtered.length} {locale === "de" ? "Treffer" : "matches"}</span>
          <span className="flex items-center gap-2">
            <kbd className="rounded border border-hairline px-1.5 py-0.5">↑↓</kbd>
            <kbd className="rounded border border-hairline px-1.5 py-0.5">↵</kbd>
            <span className="ml-1">{locale === "de" ? "Auswählen" : "Select"}</span>
          </span>
        </div>
      </div>
    </div>
  );
}
