"use client";
import { useState, useEffect, type ReactNode } from "react";

// ⌘K-Bar im Header. Klick öffnet das Command-Palette (das selbst
// auch auf ⌘K hört). Hier nur visuelle Anzeige + Hint.

export function CommandBar({ triggerLabel = "⌘K", children }: { triggerLabel?: string; children: ReactNode }) {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen(true);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="flex items-center gap-2 rounded border border-hairline bg-[color-mix(in_oklab,var(--panel)_50%,transparent)] px-2.5 py-1 font-mono text-xs text-muted transition-colors hover:border-accent hover:text-[var(--fg)]"
        aria-label="Command palette öffnen"
      >
        <span className="font-mono text-sm leading-none">⌘</span>
        <span>K</span>
        <span className="hidden text-muted sm:inline">search</span>
      </button>
      {open ? <div onClick={() => setOpen(false)}>{children}</div> : null}
    </>
  );
}
