// Command palette (⌘K) — Luma / Linear / Raycast-inspired
const CommandPalette = ({ open, onClose, onNavigate }) => {
  const [q, setQ] = React.useState('');
  const [idx, setIdx] = React.useState(0);
  const inputRef = React.useRef(null);
  const render = useDelayUnmount(open, MOTION.dur.base);

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

  const commands = [
    { section: 'Quick actions' },
    { id: 'create',    label: 'Create new event',           icon: 'plus',     kbd: 'C',      onClick: () => onNavigate?.('create') },
    { id: 'import',    label: 'Import events from CSV',     icon: 'upload' },
    { id: 'scan',      label: 'Start check-in scanner',     icon: 'qr',       kbd: 'S' },
    { section: 'Navigate' },
    { id: 'dashboard', label: 'Go to Dashboard',            icon: 'dashboard', kbd: 'G D', onClick: () => onNavigate?.('dashboard') },
    { id: 'events',    label: 'Go to Events',               icon: 'calendar',  kbd: 'G E', onClick: () => onNavigate?.('events') },
    { id: 'bookings',  label: 'Go to Bookings',             icon: 'ticket',    kbd: 'G B', onClick: () => onNavigate?.('bookings') },
    { id: 'ds',        label: 'Open Design System',         icon: 'grid',             onClick: () => onNavigate?.('design') },
    { section: 'Your events' },
    { id: 'e1', label: 'Apparat · LP5 Berghain',        icon: 'sparkles', hint: '24. Mai', onClick: () => onNavigate?.('event') },
    { id: 'e2', label: 'Hot Chip Live · Astra',           icon: 'sparkles', hint: '12. Jun' },
    { id: 'e3', label: 'Open Air · Tempelhof 2026',       icon: 'sparkles', hint: '28. Jul' },
    { section: 'Settings' },
    { id: 'team',     label: 'Invite team member',         icon: 'users' },
    { id: 'payout',   label: 'Payout settings',            icon: 'money' },
    { id: 'theme',    label: 'Toggle dark mode',           icon: 'sun',      kbd: '⌘⇧L' },
  ];

  const flat = commands.filter(c => !c.section);
  const filtered = q ? flat.filter(c => c.label.toLowerCase().includes(q.toLowerCase())) : commands;
  const selectable = filtered.filter(c => !c.section);
  const activeId = selectable[idx]?.id;

  const onKey = e => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setIdx(i => Math.min(selectable.length - 1, i + 1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setIdx(i => Math.max(0, i - 1)); }
    if (e.key === 'Enter')     { e.preventDefault(); selectable[idx]?.onClick?.(); onClose?.(); }
    if (e.key === 'Escape')    onClose?.();
  };

  if (!render) return null;
  return (
    <Portal>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 1500,
        background: 'oklch(0.1 0.01 60 / 0.4)', backdropFilter: 'blur(6px)',
        display: 'flex', justifyContent: 'center', paddingTop: '12vh',
        opacity: open ? 1 : 0, transition: `opacity ${MOTION.dur.base}ms ${MOTION.ease.out}`,
      }}>
        <div onClick={e => e.stopPropagation()} style={{
          width: '100%', maxWidth: 620, height: 'fit-content', maxHeight: '72vh',
          background: 'var(--bg-raised)', border: '1px solid var(--line-2)',
          borderRadius: 16, overflow: 'hidden', boxShadow: 'var(--shadow-lg)',
          display: 'flex', flexDirection: 'column',
          transform: open ? 'translateY(0) scale(1)' : 'translateY(-10px) scale(0.98)',
          opacity: open ? 1 : 0,
          transition: `transform ${MOTION.dur.base}ms ${MOTION.ease.out}, opacity ${MOTION.dur.base}ms ${MOTION.ease.out}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
            <Icon name="search" size={18} style={{ color: 'var(--ink-3)' }}/>
            <input ref={inputRef} value={q} onChange={e => { setQ(e.target.value); setIdx(0); }} onKeyDown={onKey}
              placeholder="Search commands, events, attendees..."
              style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontSize: 16, fontFamily: 'inherit', color: 'var(--ink)' }}/>
            <Kbd>esc</Kbd>
          </div>
          <div style={{ overflow: 'auto', padding: 6 }}>
            {filtered.length === 0 && <div style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>No results for "{q}"</div>}
            {filtered.map((c, i) => c.section ? (
              <div key={'s'+i} style={{ padding: '10px 10px 4px', fontSize: 10.5, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{c.section}</div>
            ) : (
              <button key={c.id}
                onMouseEnter={() => setIdx(selectable.indexOf(c))}
                onClick={() => { c.onClick?.(); onClose?.(); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12, width: '100%',
                  padding: '10px 12px', border: 0, borderRadius: 8,
                  background: c.id === activeId ? 'var(--bg-muted)' : 'transparent',
                  color: 'var(--ink)', fontFamily: 'inherit', fontSize: 14, cursor: 'pointer', textAlign: 'left',
                }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 7,
                  background: 'var(--bg-muted)', color: 'var(--ink-2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}><Icon name={c.icon} size={15}/></div>
                <span style={{ flex: 1 }}>{c.label}</span>
                {c.hint && <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>{c.hint}</span>}
                {c.kbd && <Kbd>{c.kbd}</Kbd>}
              </button>
            ))}
          </div>
          <div style={{
            padding: '8px 14px', borderTop: '1px solid var(--line)',
            background: 'var(--bg-sunken)',
            display: 'flex', alignItems: 'center', gap: 14, fontSize: 11, color: 'var(--ink-3)',
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Kbd>↑</Kbd><Kbd>↓</Kbd> navigate</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Kbd>↵</Kbd> open</span>
            <div style={{ flex: 1 }}/>
            <span>Powered by Tixwerk</span>
          </div>
        </div>
      </div>
    </Portal>
  );
};

window.CommandPalette = CommandPalette;
