/* eagle-launcher.jsx — Alert Launcher. A command-palette / scenario-gallery
   modal: search + keyboard-navigable list of preset SIEM alerts, plus a
   "paste your own" option. onSelect(alert) pre-loads it everywhere. */

function AlertLauncher({ open, onClose, onSelect, currentId }) {
  const E = useE();
  const [q, setQ] = React.useState("");
  const [active, setActive] = React.useState(0);
  const [custom, setCustom] = React.useState(false);
  const [customText, setCustomText] = React.useState(window.ALERTS[0].alertText);
  const inputRef = React.useRef(null);

  const filtered = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    return window.ALERTS.filter((a) => !s || (a.id + a.rule + a.host + a.user + a.descriptor).toLowerCase().includes(s));
  }, [q]);

  React.useEffect(() => { if (open) { setQ(""); setActive(0); setCustom(false); setTimeout(() => inputRef.current && inputRef.current.focus(), 60); } }, [open]);
  React.useEffect(() => { setActive(0); }, [q]);

  React.useEffect(() => {
    if (!open) return;
    const h = (e) => {
      if (e.key === "Escape") { e.preventDefault(); onClose(); }
      else if (e.key === "ArrowDown") { e.preventDefault(); setActive((i) => Math.min(filtered.length - 1, i + 1)); }
      else if (e.key === "ArrowUp") { e.preventDefault(); setActive((i) => Math.max(0, i - 1)); }
      else if (e.key === "Enter" && !custom && filtered[active]) { e.preventDefault(); pick(filtered[active]); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, filtered, active, custom]);

  function pick(a) { onSelect(a); onClose(); }
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center px-4 pt-[8vh] a-fade" style={{ background: "rgba(2,2,6,0.62)", backdropFilter: "blur(4px)" }} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="w-full max-w-2xl overflow-hidden rounded-2xl a-pop" style={{ background: E.surface, border: `1px solid ${E.borderStrong}`, boxShadow: "0 40px 90px -30px rgba(0,0,0,0.7)" }}>
        {/* search */}
        <div className="flex items-center gap-3 border-b px-4 py-3" style={{ borderColor: E.border }}>
          <window.Icon name="Search" size={17} style={{ color: E.muted }} />
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search alerts by rule, host, user…"
            className="flex-1 bg-transparent text-[14px] outline-none" style={{ color: E.text }} />
          <span className="rounded-md px-2 py-1 text-[10px] font-bold uppercase tracking-wider" style={{ background: E.fill, color: E.muted, fontFamily: E.mono }}>Alert Launcher</span>
          <button onClick={onClose} className="flex h-7 w-7 items-center justify-center rounded-lg transition-colors hover:opacity-70" style={{ color: E.muted, border: `1px solid ${E.border}` }}><window.Icon name="X" size={15} /></button>
        </div>

        {!custom ? (
          <>
            <div className="lr-scroll max-h-[52vh] overflow-y-auto p-2">
              <div className="px-2 py-1.5 text-[10px] font-bold uppercase tracking-[0.16em]" style={{ color: E.muted, fontFamily: E.mono }}>Preset scenarios</div>
              {filtered.map((a, i) => {
                const sel = a.id === currentId, hot = i === active;
                return (
                  <button key={a.id} onMouseEnter={() => setActive(i)} onClick={() => pick(a)}
                    className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-colors"
                    style={{ background: hot ? E.hover : "transparent", border: `1px solid ${hot ? E.border : "transparent"}` }}>
                    <SevChip sev={a.sev} size="lg" />
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="truncate text-[13px] font-bold" style={{ color: E.text }}>{a.title}</span>
                        {a.hero && <span className="rounded px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider" style={{ background: E.guard + "22", color: E.guard }}>Hero</span>}
                        <span className="shrink-0 whitespace-nowrap rounded px-1.5 py-0.5 text-[10px] font-semibold" style={{ background: E.fill, color: E.muted }}>{a.category}</span>
                      </div>
                      <div className="truncate text-[11px]" style={{ fontFamily: E.mono, color: E.muted }}>#{a.code} · {a.rule} · {a.host}</div>
                    </div>
                    {sel ? <window.Icon name="Check" size={16} style={{ color: E.success }} /> : <window.Icon name="CornerDownLeft" size={14} style={{ color: hot ? E.text2 : "transparent" }} />}
                  </button>
                );
              })}
              {filtered.length === 0 && <div className="px-3 py-8 text-center text-[13px]" style={{ color: E.muted }}>No alerts match “{q}”.</div>}
            </div>
            <div className="flex items-center justify-between border-t px-4 py-2.5" style={{ borderColor: E.border }}>
              <div className="flex items-center gap-3 text-[10.5px]" style={{ color: E.muted, fontFamily: E.mono }}>
                <span><kbd style={{ color: E.text2 }}>↑↓</kbd> navigate</span><span><kbd style={{ color: E.text2 }}>↵</kbd> select</span><span><kbd style={{ color: E.text2 }}>esc</kbd> close</span>
              </div>
              <button onClick={() => setCustom(true)} className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-semibold transition-colors hover:opacity-80" style={{ color: E.gateway, border: `1px solid ${E.gateway}55` }}>
                <window.Icon name="FilePlus2" size={14} /> Paste your own
              </button>
            </div>
          </>
        ) : (
          <div className="p-4">
            <div className="mb-2 flex items-center justify-between">
              <span className="text-[12px] font-bold uppercase tracking-[0.14em]" style={{ color: E.muted, fontFamily: E.mono }}>Custom alert</span>
              <button onClick={() => setCustom(false)} className="inline-flex items-center gap-1.5 text-[12px]" style={{ color: E.muted }}><window.Icon name="ArrowLeft" size={13} /> presets</button>
            </div>
            <textarea value={customText} onChange={(e) => setCustomText(e.target.value)} spellCheck={false} rows={10}
              className="lr-scroll w-full resize-none rounded-xl p-3 text-[12px] leading-relaxed outline-none" style={{ fontFamily: E.mono, color: E.text, background: E.elevated, border: `1px solid ${E.border}` }} />
            <div className="mt-3 flex justify-end">
              <button onClick={() => pick(window.makeCustomAlert(customText))} className="inline-flex items-center gap-2 rounded-lg px-4 py-2 text-[13px] font-bold transition-all active:scale-95" style={{ background: E.gateway, color: E.isDark ? "#04110f" : "#fff" }}>
                <window.Icon name="Play" size={14} /> Use this alert
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.AlertLauncher = AlertLauncher;
