// 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 };

// Busca tolerante: ignora acento e caixa e trata plural ("tutoriais" = "tutorial", "licitações" = "licitação").
// Cada termo digitado precisa aparecer no texto indexado; o índice é derivado do registro de módulos (nav.js) e do catálogo de tutoriais.
const vxNorm = s => (s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
const vxStem = w => { const r = w.replace(/ais$/, 'al').replace(/eis$/, 'el').replace(/ois$/, 'ol').replace(/(oes|aes|aos)$/, 'ao').replace(/([^s])s$/, '$1'); return r.length ? r : w; };
const vxWords = s => vxNorm(s).split(/[^a-z0-9]+/).filter(Boolean).map(vxStem);
function vxHas(q, text) {
  const qs = vxWords(q);
  if (!qs.length) return true;
  const hay = ' ' + vxWords(text).join(' ');
  return qs.every(t => hay.includes(t));
}
// Sinônimos que levam ao conteúdo de ajuda, além do que já está escrito no título e no resumo de cada tutorial.
const VX_HELP_WORDS = 'tutorial tutoriais ajuda como usar passo a passo aula video primeiros passos duvida suporte';

// 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.
// Módulos "hidden" aparecem na busca só quando marcados com `searchable` (Central de Ajuda, Meu perfil); `keywords` em nav.js amplia o que cada módulo responde.
function vxSearchGroups(q, allows) {
  const N = window.VX_NAV; // só dados reais: módulos, tutoriais e prospects (entidades ilustrativas não entram na busca)
  const visible = id => N.ready(id) && allows(N.meta[id]);
  const mods = Object.values(N.meta).filter(m => (!m.hidden || m.searchable) && m.id !== 'ajuda' && allows(m) && vxHas(q, [m.label, m.group, m.keywords].join(' ')));
  const tuts = (window.VxTutorials ? window.VxTutorials.list : []).filter(t => vxHas(q, [t.title, t.summary, (t.chapters || []).map(c => c.title).join(' '), VX_HELP_WORDS].join(' ')));
  const central = vxHas(q, ['Central de Ajuda', N.meta.ajuda && N.meta.ajuda.keywords, VX_HELP_WORDS].join(' '));
  const ajuda = [].concat(central ? [{ title: 'Central de Ajuda', sub: 'Todos os tutoriais, perguntas frequentes e contato', id: 'ajuda', icon: 'ph-lifebuoy' }] : [])
    .concat(tuts.map(t => ({ title: t.title, sub: 'Tutorial · Central de Ajuda', id: 'ajuda', params: { id: t.id }, icon: 'ph-play-circle' })));
  const byTitle = (a, b) => (vxHas(q, a.title) ? 0 : 1) - (vxHas(q, b.title) ? 0 : 1); // quem acerta no título vem antes de quem só acerta em sinônimo
  const g = [
    { label: 'MÓDULOS', items: mods.map(m => ({ title: m.label, sub: m.group, id: m.id, icon: m.icon })).sort(byTitle) },
    { label: 'AJUDA', id: 'ajuda', items: ajuda },
    { label: 'PROSPECTS', id: 'prospect', items: window.VXCommercial.PROSPECTS.filter(p => vxHas(q, 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(x => x.items.length && (!x.id || visible(x.id)));
  // Pergunta de ajuda ("tutorial", "como usar"): os resultados de ajuda vêm antes dos módulos.
  const askHelp = q.trim().length >= 3 && vxWords(q).every(t => vxWords(VX_HELP_WORDS).some(w => w.includes(t)));
  return askHelp ? g.sort((a, b) => (b.label === 'AJUDA') - (a.label === 'AJUDA')) : g;
}

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.trim(), has = s => vxHas(ql, s);
  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')],
    ['Abrir a Central de Ajuda (tutoriais)', 'ph-lifebuoy', null, () => go('ajuda')],
    ['Ver tutorial: Perfil do licitante', 'ph-play', 'capability_profiles.view', () => window.VxTutorials.open('perfil')],
    ['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 || (ql && r.searchable)) && r.id !== 'ajuda' && has([r.label, r.group, r.keywords].join(' ')) && 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: 'TUTORIAIS E AJUDA', it: ql ? (vxSearchGroups(q, allows).find(g => g.label === 'AJUDA') || { items: [] }).items.slice(0, 6).map(x => ({ title: x.title, sub: x.sub, icon: x.icon, run: () => go(x.id, x.params), kind: 'Abrir' })) : [] },
    { 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' && g.label !== 'AJUDA').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 });
