// ============================================================================
// COMPONENT: CommandPalette.jsx (Raycast / Linear style Cmd+K Palette)
// Búsqueda global, navegación instantánea y atajos rápidos de teclado
// ============================================================================

const { useState, useEffect, useRef, useMemo } = React;

function CommandPalette({ isOpen, onClose, onSelectTab, onOpenNewTx }) {
  const { 
    isAdmin,
    theme, 
    toggleTheme, 
    setDetailTx, 
    setModalRecurringOpen, 
    setModalServiceOpen, 
    setModalTagOpen, 
    setIsWhatsAppModalOpen 
  } = window.useFinance();
  
  const [query, setQuery] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [allTransactions, setAllTransactions] = useState([]);
  const [loadingTx, setLoadingTx] = useState(false);
  const inputRef = useRef(null);

  // Carga transacciones para búsqueda rápida cuando se abre
  useEffect(() => {
    if (isOpen) {
      setQuery('');
      setSelectedIndex(0);
      setLoadingTx(true);
      window.Api.getTransactions({ month: '' })
        .then(txs => {
          setAllTransactions(txs || []);
          setLoadingTx(false);
        })
        .catch(() => setLoadingTx(false));

      setTimeout(() => {
        if (inputRef.current) inputRef.current.focus();
      }, 50);
    }
  }, [isOpen]);

  // Lista de comandos estáticos
  const baseNavItems = [
    { id: 'nav-dash', category: 'Navegación', title: 'Ir al Dashboard Principal', icon: '📊', action: () => onSelectTab('dashboard') },
    { id: 'nav-mov', category: 'Navegación', title: 'Ir a Movimientos y Extracto', icon: '📑', action: () => onSelectTab('lancamentos') },
    { id: 'nav-proy', category: 'Navegación', title: 'Ir a Proyecciones & Simulador Futuro', icon: '🔮', action: () => onSelectTab('proyecciones') },
    { id: 'nav-srv', category: 'Navegación', title: 'Ir a Catálogo de Servicios y Reglas', icon: '✨', action: () => onSelectTab('servicos') },
    { id: 'nav-print', category: 'Navegación', title: 'Imprimir Rendición de Cuentas (A4)', icon: '🖨️', action: () => onSelectTab('imprimir') },
    { id: 'nav-cfg', category: 'Navegación', title: 'Ir a Configuración del Sistema', icon: '⚙️', action: () => onSelectTab('configuracoes'), adminOnly: true }
  ];

  const navigationItems = baseNavItems.filter(item => !item.adminOnly || isAdmin);

  const baseActionItems = [
    { id: 'act-new-tx', category: 'Acciones Rápidas', title: 'Registrar Nuevo Movimiento / Servicio', icon: '➕', action: () => onOpenNewTx(), adminOnly: true },
    { id: 'act-wa', category: 'Acciones Rápidas', title: 'Generar y Copiar Resumen para WhatsApp', icon: '📲', action: () => setIsWhatsAppModalOpen && setIsWhatsAppModalOpen(true), adminOnly: true },
    { id: 'act-new-rec', category: 'Acciones Rápidas', title: 'Crear Regla Recurrente Mensual (Cuota)', icon: '⚡', action: () => setModalRecurringOpen(true), adminOnly: true },
    { id: 'act-new-srv', category: 'Acciones Rápidas', title: 'Agregar Servicio al Catálogo', icon: '📦', action: () => setModalServiceOpen(true), adminOnly: true },
    { id: 'act-new-tag', category: 'Acciones Rápidas', title: 'Crear Nueva Etiqueta de Clasificación', icon: '🏷️', action: () => setModalTagOpen(true), adminOnly: true },
    { id: 'act-theme', category: 'Acciones Rápidas', title: `Cambiar a Modo ${theme === 'dark' ? 'Claro' : 'Oscuro'}`, icon: theme === 'dark' ? '☀️' : '🌙', action: () => toggleTheme() }
  ];

  const actionItems = baseActionItems.filter(item => !item.adminOnly || isAdmin);

  const normalize = (t) => {
    return (t || '')
      .toString()
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .trim();
  };

  // Filtra elementos según el texto (sin importar acentos)
  const filteredList = useMemo(() => {
    const qNorm = normalize(query);
    let res = [];

    // Si no hay búsqueda, muestra navegación y acciones
    if (!qNorm) {
      return [...actionItems, ...navigationItems];
    }

    // Filtrar acciones y navegación
    const matchedActions = actionItems.filter(item => normalize(item.title).includes(qNorm));
    const matchedNav = navigationItems.filter(item => normalize(item.title).includes(qNorm));
    res = [...matchedActions, ...matchedNav];

    // Buscar en movimientos (título, descripción, tags, monto)
    const matchedTxs = allTransactions
      .filter(tx => {
        const titleMatch = normalize(tx.title).includes(qNorm);
        const descMatch = normalize(tx.description).includes(qNorm);
        const docMatch = normalize(tx.document_ref).includes(qNorm);
        const tagMatch = (tx.tags || []).some(t => normalize(t.name).includes(qNorm));
        const amountMatch = String(tx.amount || '').includes(qNorm);
        return titleMatch || descMatch || docMatch || tagMatch || amountMatch;
      })
      .slice(0, 15)
      .map(tx => ({
        id: `tx-${tx.id}`,
        category: 'Movimientos Encontrados',
        title: tx.title,
        subtitle: `${window.formatDateBR ? window.formatDateBR(tx.date) : tx.date} • ${window.formatCurrencyPYG(tx.amount)} • ${tx.type === 'CREDIT' ? 'Servicio' : 'Cuota / Débito'}`,
        icon: tx.type === 'CREDIT' ? '🎬' : (tx.type === 'DEBIT' ? '🎓' : '💵'),
        action: () => {
          if (setDetailTx) setDetailTx(tx);
        }
      }));

    return [...res, ...matchedTxs];
  }, [query, allTransactions, theme]);

  // Manejo de teclas de navegación (flechas, Enter, Esc)
  const handleKeyDown = (e) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setSelectedIndex(prev => (prev + 1) % (filteredList.length || 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setSelectedIndex(prev => (prev - 1 + filteredList.length) % (filteredList.length || 1));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (filteredList[selectedIndex]) {
        filteredList[selectedIndex].action();
        onClose();
      }
    } else if (e.key === 'Escape') {
      e.preventDefault();
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="cmd-palette-backdrop" onClick={onClose}>
      <div className="cmd-palette-box" onClick={(e) => e.stopPropagation()}>
        {/* BUSCADOR INPUT */}
        <div className="flex items-center gap-3 px-4 py-3 border-b border-zinc-200 dark:border-zinc-800">
          <span className="text-zinc-400 text-base">🔍</span>
          <input
            ref={inputRef}
            type="text"
            className="flex-1 bg-transparent text-sm text-zinc-950 dark:text-white placeholder-zinc-400 focus:outline-none font-medium"
            placeholder="Buscar acción, pantalla, servicio o movimiento... (o 'Esc' para salir)"
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setSelectedIndex(0);
            }}
            onKeyDown={handleKeyDown}
          />
          <kbd className="px-1.5 py-0.5 text-[10px] font-mono font-semibold text-zinc-400 bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded shadow-2xs">
            ESC
          </kbd>
        </div>

        {/* LISTADO DE RESULTADOS */}
        <div className="max-h-[380px] overflow-y-auto p-2 divide-y divide-zinc-100 dark:divide-zinc-800/60">
          {filteredList.length === 0 ? (
            <div className="py-8 text-center text-xs text-zinc-400">
              No se encontraron resultados para "{query}"
            </div>
          ) : (
            filteredList.map((item, idx) => {
              const isSelected = idx === selectedIndex;
              return (
                <div
                  key={item.id}
                  onClick={() => {
                    item.action();
                    onClose();
                  }}
                  onMouseEnter={() => setSelectedIndex(idx)}
                  className={`flex items-center justify-between px-3 py-2.5 rounded-lg text-xs cursor-pointer transition-colors ${
                    isSelected 
                      ? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-950 font-medium' 
                      : 'text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800'
                  }`}
                >
                  <div className="flex items-center gap-2.5 truncate">
                    <span className="text-sm shrink-0">{item.icon}</span>
                    <div className="truncate">
                      <div className="truncate font-medium">{item.title}</div>
                      {item.subtitle && (
                        <div className={`text-[11px] truncate font-mono ${isSelected ? 'text-zinc-300 dark:text-zinc-600' : 'text-zinc-400'}`}>
                          {item.subtitle}
                        </div>
                      )}
                    </div>
                  </div>
                  <span className={`text-[10px] font-mono shrink-0 ml-2 px-1.5 py-0.5 rounded ${
                    isSelected 
                      ? 'bg-zinc-800 text-zinc-300 dark:bg-zinc-200 dark:text-zinc-800' 
                      : 'bg-zinc-100 text-zinc-400 dark:bg-zinc-800'
                  }`}>
                    {item.category}
                  </span>
                </div>
              );
            })
          )}
        </div>

        {/* PIE DE PÁGINA DEL PALETTE */}
        <div className="px-4 py-2 bg-zinc-50 dark:bg-zinc-900 border-t border-zinc-200 dark:border-zinc-800 flex items-center justify-between text-[11px] text-zinc-400">
          <div className="flex items-center gap-3">
            <span>↑↓ Navegar</span>
            <span>↵ Seleccionar</span>
          </div>
          <span>Paleta de Comandos ⌘K</span>
        </div>
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
