/* crm-cmdk.jsx — Command palette (⌘K) */

function CommandPalette({open, onClose, onNav, onOpenContract, onOpenCustomer}) {
  const [q, setQ] = React.useState('');
  const [sel, setSel] = React.useState(0);
  const inputRef = React.useRef();

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

  if (!open) return null;

  // Build searchable items
  const navCommands = NAV_ITEMS.map(n => ({
    type: 'nav', id: 'nav-' + n.k, label: 'Ir para ' + n.label, hint: 'Navegação',
    icon: n.icon, run: () => { onNav(n.k); onClose(); },
  }));
  const actionCommands = [
    {type:'action', id:'act-new-contract', label:'Novo contrato',          hint:'Ação', icon:'plus',     run:() => { onNav('contracts'); onClose(); }},
    {type:'action', id:'act-new-customer', label:'Novo cliente',           hint:'Ação', icon:'customers',run:() => { onNav('customers'); onClose(); }},
    {type:'action', id:'act-renew',        label:'Renovar contrato…',      hint:'Ação', icon:'contracts',run:() => { onNav('contracts'); onClose(); }},
    {type:'action', id:'act-close-cycle',  label:'Fechar ciclo Q3',        hint:'Ação', icon:'cycle',    run:() => { onNav('cycle'); onClose(); }},
    {type:'action', id:'act-toggle-theme', label:'Trocar tema · claro / escuro', hint:'Ação', icon:'sun', run:() => {
      const t = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
      document.documentElement.setAttribute('data-theme', t);
      onClose();
    }},
  ];
  const contractCommands = CRM_CONTRACTS.map(c => ({
    type:'contract', id:'contract-' + c.id, label: CRM_BY_ID[c.id]?.name, sub: c.id, hint: c.state,
    icon:'contracts', run:() => { onOpenContract(c.id); onClose(); },
  }));
  const customerCommands = CRM_CUSTOMERS.map(c => ({
    type:'customer', id:'customer-' + c.id, label: c.name, sub: c.loc + ' · ' + c.kind, hint: 'cliente',
    icon:'customers', run:() => { onOpenCustomer && onOpenCustomer(c.id); onClose(); },
  }));

  const ql = q.trim().toLowerCase();
  const matches = (s) => !ql || s.toLowerCase().includes(ql);

  const filtered = [
    {label:'Navegação',   items: navCommands.filter(c => matches(c.label))},
    {label:'Ações',       items: actionCommands.filter(c => matches(c.label))},
    {label:'Contratos',   items: contractCommands.filter(c => matches(c.label || '') || matches(c.sub) || matches(c.hint))},
    {label:'Clientes',    items: customerCommands.filter(c => matches(c.label || '') || matches(c.sub))},
  ].filter(g => g.items.length > 0);

  const flat = filtered.flatMap(g => g.items);
  const cur = flat[sel];

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel(s => Math.min(flat.length - 1, s + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSel(s => Math.max(0, s - 1)); }
    else if (e.key === 'Enter') { e.preventDefault(); cur?.run(); }
    else if (e.key === 'Escape') { e.preventDefault(); onClose(); }
  };

  return (
    <div className="cmdk-back" onClick={onClose}>
      <div className="cmdk" onClick={e => e.stopPropagation()}>
        <div className="input-row">
          <Icon k="search" size={16} color="var(--ink-3)"/>
          <input
            ref={inputRef}
            placeholder="Pesquisar contratos, clientes, ações…"
            value={q}
            onChange={e => { setQ(e.target.value); setSel(0); }}
            onKeyDown={onKey}
          />
          <span style={{fontFamily:'var(--mono)', fontSize:10.5, color:'var(--ink-3)', border:'0.5px solid var(--rule)', borderRadius:3, padding:'1px 5px'}}>esc</span>
        </div>
        <div className="results">
          {filtered.length === 0 && (
            <div style={{padding:'24px 14px', textAlign:'center'}}>
              <div className="display ink-3" style={{fontSize:18, fontStyle:'italic'}}>Sem resultados.</div>
              <div className="ink-3 mt-2" style={{fontSize:12}}>Tenta um ID, nome de cliente ou ação.</div>
            </div>
          )}
          {filtered.map((g, gi) => (
            <div key={g.label}>
              <div className="grp-label">{g.label}</div>
              {g.items.map((it) => {
                const isSel = it === cur;
                return (
                  <div key={it.id} className={'item' + (isSel ? ' sel' : '')}
                       onMouseEnter={() => setSel(flat.indexOf(it))}
                       onClick={it.run}>
                    <span className="icon"><Icon k={it.icon} size={14}/></span>
                    <span className="grow truncate">
                      {it.label}
                      {it.sub && <span className="mono ink-3" style={{fontSize:11, marginLeft:8}}>{it.sub}</span>}
                    </span>
                    {it.hint && <span className="desc">{it.hint}</span>}
                    {isSel && <Icon k="arrow-r" size={12} color="var(--clay)"/>}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        <div className="flex between items-c" style={{padding:'8px 14px', borderTop:'0.5px solid var(--rule)', fontSize:10.5, color:'var(--ink-3)', fontFamily:'var(--mono)'}}>
          <span>↑↓ navegar · ↵ abrir</span>
          <span>{flat.length} resultados</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CommandPalette });
