/* global React, Icon, Pill, fmt,
   AGENCY_CLIENTS, MODULES, CRM_CLIENTS, TASKS, PAUTA_CLIENTS,
   HOOKS_LIBRARY, CONTENT_INSIGHTS, PROPOSALS, SMART_ALERTS,
   CHANNEL_META */
const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS, useRef: useRefS } = React;

/* ============================================================
   GLOBAL SEARCH · ⌘K command palette
   ============================================================ */
function CommandPalette({ open, onClose, onNavigate }) {
  const [query, setQuery] = useStateS('');
  const [selectedIdx, setSelectedIdx] = useStateS(0);
  const inputRef = useRefS(null);

  // Reset ao abrir
  useEffectS(() => {
    if (open) {
      setQuery('');
      setSelectedIdx(0);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  // Esc + Enter + navegação
  useEffectS(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') { e.preventDefault(); onClose(); }
      if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedIdx(i => Math.min(filteredResults.length - 1, i + 1)); }
      if (e.key === 'ArrowUp')   { e.preventDefault(); setSelectedIdx(i => Math.max(0, i - 1)); }
      if (e.key === 'Enter')     {
        e.preventDefault();
        const item = filteredResults[selectedIdx];
        if (item?.action) item.action();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  });

  // Compila índice de busca
  const allResults = useMemoS(() => {
    if (!open) return [];
    const results = [];

    // Módulos do painel
    (MODULES || []).forEach(m => {
      results.push({
        kind: 'modulo',
        kindLabel: 'Módulo',
        kindColor: 'var(--accent)',
        title: m.label,
        subtitle: m.kicker,
        action: () => { onNavigate(m.id); onClose(); },
      });
    });

    // Clientes
    (window.CRM_CLIENTS || AGENCY_CLIENTS || []).forEach(c => {
      results.push({
        kind: 'cliente',
        kindLabel: 'Cliente',
        kindColor: '#9A9BE5',
        title: c.brand,
        subtitle: c.responsible + ' · ' + (c.segment || ''),
        action: () => { onNavigate('crm', { clientSlug: c.slug }); onClose(); },
      });
    });

    // Tarefas (top 15)
    (window.TASKS || []).slice(0, 15).forEach(t => {
      results.push({
        kind: 'tarefa',
        kindLabel: 'Tarefa',
        kindColor: t.typeColor,
        title: t.title,
        subtitle: t.clientBrand + ' · ' + t.typeLabel + ' · vence ' + t.dueDay,
        action: () => { onNavigate('pauta'); onClose(); },
      });
    });

    // Hooks
    (window.HOOKS_LIBRARY || []).forEach(h => {
      results.push({
        kind: 'hook',
        kindLabel: 'Hook',
        kindColor: '#F3AE4D',
        title: '"' + h.text + '"',
        subtitle: h.client + ' · ' + h.format + ' · ' + fmt.k(h.reach) + ' alcance',
        action: () => { onNavigate('intel'); onClose(); },
      });
    });

    // Insights
    (window.CONTENT_INSIGHTS || []).forEach(i => {
      results.push({
        kind: 'insight',
        kindLabel: 'Insight',
        kindColor: '#6FC878',
        title: i.title,
        subtitle: i.description?.slice(0, 100) + '...',
        action: () => { onNavigate('intel'); onClose(); },
      });
    });

    // Propostas
    (window.PROPOSALS || []).forEach(p => {
      results.push({
        kind: 'proposta',
        kindLabel: 'Proposta',
        kindColor: '#77B8F1',
        title: p.lead,
        subtitle: p.segment + ' · R$ ' + (p.monthly || 0).toLocaleString('pt-BR'),
        action: () => { onNavigate('team'); onClose(); },
      });
    });

    // Alertas
    (window.SMART_ALERTS || []).forEach(a => {
      results.push({
        kind: 'alerta',
        kindLabel: 'Alerta',
        kindColor: a.severity === 'high' ? '#F34D4D' : a.severity === 'medium' ? '#F3AE4D' : '#77B8F1',
        title: a.title,
        subtitle: a.detail?.slice(0, 100) + '...',
        action: () => { onNavigate('team'); onClose(); },
      });
    });

    return results;
  }, [open]);

  const filteredResults = useMemoS(() => {
    if (!query.trim()) return allResults.slice(0, 12);
    const q = query.toLowerCase()
      .normalize('NFD').replace(/[\u0300-\u036f]/g, '');
    return allResults.filter(r => {
      const haystack = (r.title + ' ' + r.subtitle + ' ' + r.kindLabel).toLowerCase()
        .normalize('NFD').replace(/[\u0300-\u036f]/g, '');
      return haystack.includes(q);
    }).slice(0, 30);
  }, [allResults, query]);

  // Reset selection quando filtro muda
  useEffectS(() => { setSelectedIdx(0); }, [query]);

  // Agrupa por kind
  const grouped = useMemoS(() => {
    const groups = {};
    filteredResults.forEach((r, idx) => {
      groups[r.kindLabel] = groups[r.kindLabel] || [];
      groups[r.kindLabel].push({ ...r, globalIdx: idx });
    });
    return groups;
  }, [filteredResults]);

  if (!open) return null;

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(8,8,12,0.55)',
        backdropFilter: 'blur(6px)',
        zIndex: 100,
        animation: 'fadeUp 200ms var(--ease-out)',
      }} />
      <div style={{
        position: 'fixed',
        top: '12vh', left: '50%', transform: 'translateX(-50%)',
        width: 'min(680px, calc(100vw - 32px))',
        maxHeight: '76vh',
        background: 'var(--bg-flat)',
        border: '1px solid var(--border-strong)',
        borderRadius: 'var(--r-card-lg)',
        boxShadow: '0 32px 64px rgba(26,26,26,0.32), 0 0 0 1px rgba(154,155,229,0.20)',
        zIndex: 101,
        overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
        animation: 'fadeUp 280ms var(--ease-out)',
      }}>
        {/* Input */}
        <div style={{
          padding: '14px 18px',
          borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span style={{ fontSize: 18, color: 'var(--accent)' }}>⌘</span>
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Buscar cliente, tarefa, hook, proposta, módulo..."
            style={{
              flex: 1, appearance: 'none', border: 'none',
              background: 'transparent', color: 'var(--text)',
              fontSize: 17, fontFamily: 'inherit',
              outline: 'none',
            }}
          />
          <kbd style={{
            fontSize: 10, padding: '2px 6px',
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 4, color: 'var(--text-faint)',
            fontFamily: 'monospace',
          }}>esc</kbd>
        </div>

        {/* Results */}
        <div style={{ flex: 1, overflow: 'auto', padding: '8px 0' }}>
          {filteredResults.length === 0 ? (
            <div style={{ padding: 'var(--space-6)', textAlign: 'center', color: 'var(--text-faint)' }}>
              <div style={{ fontSize: 24, marginBottom: 8 }}>🔍</div>
              <div style={{ fontSize: 13 }}>Nenhum resultado para "{query}"</div>
            </div>
          ) : (
            Object.entries(grouped).map(([label, items]) => (
              <div key={label} style={{ marginBottom: 6 }}>
                <div style={{
                  padding: '8px 18px 4px',
                  fontSize: 10, fontWeight: 500,
                  letterSpacing: '0.10em', textTransform: 'uppercase',
                  color: 'var(--text-faint)',
                }}>
                  {label} · {items.length}
                </div>
                {items.map(r => {
                  const isSelected = r.globalIdx === selectedIdx;
                  return (
                    <div
                      key={r.globalIdx}
                      onClick={r.action}
                      onMouseEnter={() => setSelectedIdx(r.globalIdx)}
                      style={{
                        padding: '10px 18px',
                        background: isSelected ? 'var(--accent-soft)' : 'transparent',
                        borderLeft: `3px solid ${isSelected ? r.kindColor : 'transparent'}`,
                        cursor: 'pointer',
                        display: 'grid', gridTemplateColumns: '10px 1fr auto', gap: 14, alignItems: 'center',
                      }}>
                      <span style={{
                        width: 6, height: 6, borderRadius: '50%',
                        background: r.kindColor,
                      }} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{
                          fontSize: 14, fontWeight: 500, color: 'var(--text)',
                          lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                        }}>
                          {r.title}
                        </div>
                        <div style={{
                          fontSize: 12, color: 'var(--text-muted)',
                          marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                        }}>
                          {r.subtitle}
                        </div>
                      </div>
                      {isSelected && (
                        <kbd style={{
                          fontSize: 10, padding: '2px 6px',
                          background: 'var(--accent)', color: '#fff',
                          borderRadius: 4, fontFamily: 'monospace',
                        }}>↵</kbd>
                      )}
                    </div>
                  );
                })}
              </div>
            ))
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: '8px 18px',
          borderTop: '1px solid var(--border)',
          background: 'var(--surface-soft)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, fontSize: 11, color: 'var(--text-faint)',
        }}>
          <span style={{ display: 'inline-flex', gap: 14, flexWrap: 'wrap' }}>
            <span><kbd style={miniKbd}>↑↓</kbd> navegar</span>
            <span><kbd style={miniKbd}>↵</kbd> abrir</span>
            <span><kbd style={miniKbd}>esc</kbd> fechar</span>
          </span>
          <span style={{ color: 'var(--accent)', fontWeight: 500 }}>
            {filteredResults.length} resultado{filteredResults.length === 1 ? '' : 's'}
          </span>
        </div>
      </div>
    </>
  );
}

const miniKbd = {
  fontSize: 9, padding: '1px 5px',
  background: 'var(--surface)', border: '1px solid var(--border)',
  borderRadius: 3, color: 'var(--text-muted)',
  fontFamily: 'monospace',
};

/* ============================================================
   Hook · listen for ⌘K / Ctrl+K
   ============================================================ */
function useCommandPalette() {
  const [open, setOpen] = useStateS(false);

  useEffectS(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setOpen(o => !o);
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  return [open, setOpen];
}

/* ============================================================
   DARK MODE · toggle persistente
   ============================================================ */
const THEME_LS_KEY = 'beza_theme_v1';

function loadTheme() {
  try { return localStorage.getItem(THEME_LS_KEY) || 'claro'; } catch { return 'claro'; }
}
function saveTheme(t) {
  try { localStorage.setItem(THEME_LS_KEY, t); } catch (e) {}
}

function ThemeToggle({ theme, onToggle }) {
  return (
    <button onClick={onToggle} title={`Mudar para ${theme === 'claro' ? 'escuro' : 'claro'}`} style={{
      appearance: 'none', border: '1px solid var(--border)',
      background: 'var(--surface)', color: 'var(--text-muted)',
      width: 36, height: 36, borderRadius: '50%',
      cursor: 'pointer', fontFamily: 'inherit',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 16, transition: 'all var(--t-fast)',
    }}
    onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent)'}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border)'}>
      {theme === 'claro' ? '🌙' : '☀'}
    </button>
  );
}

/* ============================================================
   SEARCH BUTTON · trigger no header
   ============================================================ */
function SearchTrigger({ onOpen }) {
  const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.userAgent);
  return (
    <button onClick={onOpen} style={{
      appearance: 'none', border: '1px solid var(--border)',
      background: 'var(--surface-soft)', color: 'var(--text-muted)',
      padding: '7px 12px', borderRadius: 999,
      fontSize: 13, fontFamily: 'inherit', cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', gap: 10,
      transition: 'border-color var(--t-fast)',
    }}
    onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent)'}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border)'}>
      <span>🔍 Buscar</span>
      <kbd style={miniKbd}>{isMac ? '⌘K' : 'Ctrl K'}</kbd>
    </button>
  );
}

Object.assign(window, { CommandPalette, useCommandPalette, ThemeToggle, SearchTrigger, loadTheme, saveTheme });
