// Command palette (⌘K / Ctrl+K), central de notificações e busca global do Control Center.
const vxMix = (c, p) => 'color-mix(in srgb, ' + c + ' ' + p + '%, transparent)';
const VX_TONE = { success: 'var(--status-success)', info: 'var(--status-info)', warning: 'var(--status-warning)', danger: 'var(--status-danger)', neutral: 'var(--status-neutral-text)', active: 'var(--status-active)', proposal: 'var(--status-proposal)', muted: 'var(--text-muted)' };
const vxEyebrow = { fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600 };

// Grupos de resultado da busca global. Cada item leva ao módulo (id) que o exibe; módulos ausentes ou ocultos pelo RBAC ficam de fora.
function vxSearchGroups(q, allows) {
  const ql = (q || '').toLowerCase().trim(), has = s => s.toLowerCase().includes(ql);
  const N = window.VX_NAV; // só dados reais: módulos e prospects (entidades ilustrativas não entram na busca)
  const visible = id => N.ready(id) && allows(N.meta[id]);
  return [
    { label: 'MÓDULOS', items: Object.values(N.meta).filter(m => !m.hidden && allows(m) && has(m.label + ' ' + m.group)).map(m => ({ title: m.label, sub: m.group, id: m.id, icon: m.icon })) },
    { label: 'PROSPECTS', id: 'prospect', items: window.VXCommercial.PROSPECTS.filter(p => has(p.name + ' ' + p.city + ' ' + p.sector)).slice(0, 3).map(p => ({ title: p.name, sub: p.city + ' - ' + p.uf + ' · ' + p.sector, icon: 'ph-database', id: 'prospect', params: { id: p.id } })) },
  ].filter(g => g.items.length && (!g.id || visible(g.id)));
}

function CommandPalette({ onClose, go, toast }) {
  const { EmptyState } = window.VRticeDesignSystem_d763eb;
  const { can, allows } = useAccess();
  const [q, setQ] = React.useState(''), [i, setI] = React.useState(0);
  const ql = q.toLowerCase().trim(), has = s => !ql || s.toLowerCase().includes(ql);
  const actions = [
    ['Novo prospect', 'ph-plus-circle', 'commercial_intelligence.create', () => go('prospects')],
    ['Registrar contato (CRM)', 'ph-phone-call', 'commercial_intelligence.edit', () => go('crm')],
    ['Nova campanha', 'ph-megaphone', 'commercial_intelligence.create', () => go('campaigns')],
    ['Exportar prospects (abre a lista)', 'ph-export', 'commercial_intelligence.export', () => go('prospects')],
    ['Abrir configurações', 'ph-gear-six', 'settings.view', () => go('config')],
    ['Alternar tema claro/escuro', 'ph-circle-half', null, () => window.VRticeDesignSystem_d763eb.VxTheme.toggle()],
  ];
  const groups = [
    { t: 'AÇÕES', it: actions.filter(a => has(a[0])).map(([title, icon, perm, run]) => ({ title, icon, perm, run, kind: 'Ação' })) },
    { t: 'NAVEGAR', it: Object.values(window.VX_NAV.meta).filter(r => !r.hidden && has(r.label) && allows(r)).slice(0, ql ? 6 : 5).map(r => ({ title: r.label, sub: r.group, icon: r.icon, perm: r.deny === 'lock' ? r.perm : null, run: () => go(r.id), kind: 'Ir para' })) },
    { t: 'PROSPECTS', it: ql ? (vxSearchGroups(q, allows).find(g => g.label === 'PROSPECTS') || { items: [] }).items.map(x => ({ title: x.title, sub: x.sub, icon: x.icon, run: () => go(x.id, x.params), kind: 'Abrir' })) : [] },
    { t: 'OUTRAS ENTIDADES', it: ql ? vxSearchGroups(q, allows).filter(g => g.label !== 'MÓDULOS' && g.label !== 'PROSPECTS').flatMap(g => g.items.map(x => ({ title: x.title, sub: g.label[0] + g.label.slice(1).toLowerCase() + ' · ' + x.sub, icon: x.icon, run: () => go(x.id, x.params), kind: 'Abrir' }))).slice(0, 4) : [] },
  ].filter(g => g.it.length);
  const flat = groups.flatMap(g => g.it);
  const run = it => { if (!it) return; if (it.perm && !can(it.perm)) { toast('Sem permissão: ' + it.perm, 'ph-lock-simple'); return; } onClose(); it.run(); };
  React.useEffect(() => { setI(0); }, [q]);
  const key = e => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setI(x => Math.min(flat.length - 1, x + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setI(x => Math.max(0, x - 1)); }
    else if (e.key === 'Enter') run(flat[i]);
    else if (e.key === 'Escape') onClose();
  };
  let n = -1;
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 400, display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: '12vh 16px 0', background: 'var(--bg-overlay)' }} onMouseDown={e => e.target === e.currentTarget && onClose()}>
      <div role="dialog" aria-modal="true" aria-label="Command palette" style={{ width: 'min(640px,100%)', maxHeight: '70vh', display: 'flex', flexDirection: 'column', background: 'var(--surface-dialog)', border: '1px solid var(--border-field)', borderRadius: 20, boxShadow: 'var(--shadow-modal)', overflow: 'hidden', animation: 'vx-menu-in .14s ease' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 20px', borderBottom: '1px solid var(--border-default)' }}>
          <i className="ph ph-magnifying-glass" style={{ fontSize: 20, color: 'var(--text-muted)' }} />
          <input autoFocus value={q} onChange={e => setQ(e.target.value)} onKeyDown={key} aria-label="Buscar, navegar ou executar uma ação" placeholder="Buscar, navegar ou executar uma ação…" style={{ all: 'unset', flex: 1, height: 60, fontSize: 16, color: 'var(--text-primary)', fontFamily: 'inherit' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-subtle)', border: '1px solid var(--border-control)', borderRadius: 6, padding: '3px 6px' }}>ESC</span>
        </div>
        <div style={{ overflowY: 'auto', padding: 8 }}>
          {!flat.length && <EmptyState>Nada encontrado para “{q}”.</EmptyState>}
          {groups.map(g => (
            <div key={g.t} style={{ display: 'flex', flexDirection: 'column', gap: 2, paddingBottom: 6 }}>
              <span style={{ ...vxEyebrow, padding: '10px 12px 6px' }}>{g.t}</span>
              {g.it.map(it => {
                n++; const k = n, off = it.perm && !can(it.perm), sel = k === i;
                return (
                  <button key={g.t + it.title} type="button" onMouseEnter={() => setI(k)} onClick={() => run(it)} style={{ all: 'unset', boxSizing: 'border-box', cursor: off ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', gap: 12, minHeight: 48, padding: '0 12px', borderRadius: 10, background: sel ? 'var(--action-selected-bg)' : 'transparent', opacity: off ? 0.55 : 1 }}>
                    <span style={{ width: 32, height: 32, flex: 'none', borderRadius: 8, background: 'var(--overlay-05)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className={'ph ' + (off ? 'ph-lock-simple' : it.icon)} style={{ fontSize: 17, color: sel ? 'var(--action-selected-icon)' : 'var(--text-muted)' }} /></span>
                    <span style={{ display: 'flex', flexDirection: 'column', gap: 1, flex: 1, minWidth: 0 }}><span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>{it.title}</span>{it.sub && <span style={{ fontSize: 12, color: 'var(--text-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.sub}</span>}</span>
                    {off ? <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>sem permissão</span> : sel && <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{it.kind} ↵</span>}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 18, padding: '12px 20px', borderTop: '1px solid var(--border-default)', fontSize: 12, color: 'var(--text-subtle)', flexWrap: 'wrap' }}><span>↑ ↓ navegar</span><span>↵ executar</span><span>Ações respeitam suas permissões</span></div>
      </div>
    </div>
  );
}

const VX_NOTIF_CATS = ['Todas', 'Sistema', 'Segurança', 'Comercial', 'Oportunidades', 'Tarefas', 'Integrações', 'Erros'];
const VX_PRI_TONE = { Alta: 'danger', Média: 'warning', Baixa: 'neutral' };

function NotificationCenter({ notifs, setNotifs, onClose }) {
  const { Drawer, FilterChip, Switch, Button, EmptyState, Badge } = window.VRticeDesignSystem_d763eb;
  const [cat, setCat] = React.useState('Todas'), [only, setOnly] = React.useState(false);
  const unread = notifs.filter(n => n.unread).length;
  const list = notifs.filter(n => (cat === 'Todas' || n.cat === cat) && (!only || n.unread));
  const read = id => setNotifs(ns => ns.map(n => n.id === id ? { ...n, unread: false } : n));
  return (
    <Drawer kicker="Notificações" title={unread + (unread === 1 ? ' não lida' : ' não lidas')} onClose={onClose} width={460}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>{VX_NOTIF_CATS.map(c => <FilterChip key={c} label={c} count={c === 'Todas' ? notifs.length : notifs.filter(n => n.cat === c).length} selected={cat === c} onClick={() => setCat(c)} />)}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <Switch label="Somente não lidas" checked={only} onChange={setOnly} />
        <Button variant="link" onClick={() => setNotifs(ns => ns.map(n => ({ ...n, unread: false })))}>Marcar todas como lidas</Button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {!list.length && <EmptyState variant="block" icon="ph-bell-simple-slash" title="Nada por aqui">Nenhuma notificação com esses filtros.</EmptyState>}
        {list.map(n => (
          <a key={n.id} href="#" onClick={e => { e.preventDefault(); read(n.id); }} className="vx-hovercard" style={{ textDecoration: 'none', color: 'var(--text-primary)', display: 'flex', gap: 14, alignItems: 'flex-start', padding: 14, borderRadius: 14, background: n.unread ? 'var(--action-primary-tint)' : 'transparent', border: '1px solid ' + (n.unread ? vxMix('var(--status-info)', 25) : 'var(--overlay-06)') }}>
            <span style={{ width: 38, height: 38, flex: 'none', borderRadius: 10, background: 'var(--overlay-05)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className={'ph ' + n.icon} style={{ fontSize: 19, color: VX_TONE[n.tone] }} /></span>
            <span style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: 1, minWidth: 0 }}>
              <span style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}><span style={{ fontSize: 14, fontWeight: 600 }}>{n.t}</span><span style={{ fontSize: 12, color: 'var(--text-subtle)', whiteSpace: 'nowrap' }}>{n.when}</span></span>
              <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{n.d}</span>
              <span style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Badge variant="meta" tone={VX_PRI_TONE[n.pri]}>Prioridade {n.pri.toLowerCase()}</Badge><span style={vxEyebrow}>{n.cat}</span></span>
            </span>
            {n.unread && <span style={{ width: 8, height: 8, flex: 'none', marginTop: 6, borderRadius: '50%', background: 'var(--status-info)' }} />}
          </a>
        ))}
      </div>
    </Drawer>
  );
}

Object.assign(window, { vxMix, VX_TONE, vxSearchGroups, CommandPalette, NotificationCenter });
