const { useState, useEffect, useRef, useCallback, useMemo } = React;
const T = window.ArbiterTokens;

const CMD_ITEMS = [
  // Navigation
  { id: 'nav-dashboard', label: 'Go to Dashboard', category: 'Navigation', icon: '◫', action: 'navigate', target: 'dashboard' },
  { id: 'nav-matters', label: 'Go to Matters', category: 'Navigation', icon: '◰', action: 'navigate', target: 'matters' },
  { id: 'nav-documents', label: 'Go to Documents', category: 'Navigation', icon: '▤', action: 'navigate', target: 'documents' },
  { id: 'nav-calendar', label: 'Go to Calendar', category: 'Navigation', icon: '▦', action: 'navigate', target: 'calendar' },
  { id: 'nav-research', label: 'Go to Research', category: 'Navigation', icon: '◈', action: 'navigate', target: 'research' },
  { id: 'nav-billing', label: 'Go to Billing', category: 'Navigation', icon: '▣', action: 'navigate', target: 'billing' },
  // Matters
  { id: 'm-redstone', label: 'Redstone Capital v. Meridian Holdings', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0312' },
  { id: 'm-pacific', label: 'In re: Pacific Shipping Antitrust', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0298' },
  { id: 'm-thornton', label: 'Thornton Estate Probate Contest', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0284' },
  { id: 'm-blackwell', label: 'Blackwell IP Infringement', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0271' },
  { id: 'm-chen', label: 'Chen v. Atlas Financial Group', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0265' },
  { id: 'm-sterling', label: 'Sterling Pharma FCPA Investigation', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0259' },
  { id: 'm-harbor', label: 'Harbor District Eminent Domain', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0243' },
  { id: 'm-novatech', label: 'NovaTech Merger Review', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0230' },
  { id: 'm-greenfield', label: 'Greenfield Environmental Class Action', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0218' },
  { id: 'm-marshall', label: 'Marshall Employment Dispute', category: 'Matters', icon: '●', action: 'matter', target: 'M-2024-0201' },
  // Actions
  { id: 'act-newmatter', label: 'Create New Matter', category: 'Actions', icon: '+', action: 'action', target: 'new-matter' },
  { id: 'act-upload', label: 'Upload Document', category: 'Actions', icon: '↑', action: 'action', target: 'upload' },
  { id: 'act-newevent', label: 'Create Calendar Event', category: 'Actions', icon: '+', action: 'action', target: 'new-event' },
  { id: 'act-search', label: 'New Legal Research', category: 'Actions', icon: '◈', action: 'navigate', target: 'research' },
  // People
  { id: 'p-kirkland', label: 'M. Kirkland — Senior Partner', category: 'People', icon: '◔', action: 'person', target: 'kirkland' },
  { id: 'p-chen', label: 'S. Chen — Partner', category: 'People', icon: '◔', action: 'person', target: 'chen' },
  { id: 'p-vasquez', label: 'R. Vasquez — Partner', category: 'People', icon: '◔', action: 'person', target: 'vasquez' },
  { id: 'p-petrov', label: 'A. Petrov — Associate', category: 'People', icon: '◔', action: 'person', target: 'petrov' },
  { id: 'p-torres', label: 'L. Torres — Senior Associate', category: 'People', icon: '◔', action: 'person', target: 'torres' },
  { id: 'p-park', label: 'J. Park — Associate', category: 'People', icon: '◔', action: 'person', target: 'park' },
];

const cmdStyles = {
  overlay: {
    position: 'fixed', inset: 0, zIndex: 10000,
    background: 'rgba(10,22,40,0.4)', backdropFilter: 'blur(4px)',
    display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
    paddingTop: '15vh',
  },
  container: {
    width: '560px', maxHeight: '420px', background: T.color.bg.card,
    borderRadius: T.radius.xl, boxShadow: '0 16px 64px rgba(10,22,40,0.25)',
    border: `1px solid ${T.color.border.light}`, display: 'flex', flexDirection: 'column',
    overflow: 'hidden',
  },
  inputRow: {
    display: 'flex', alignItems: 'center', padding: '12px 16px', gap: '10px',
    borderBottom: `1px solid ${T.color.border.light}`,
  },
  inputIcon: { fontSize: '16px', color: T.color.text.tertiary, flexShrink: 0 },
  input: {
    flex: 1, border: 'none', outline: 'none', fontSize: T.font.size.md,
    fontFamily: T.font.family, color: T.color.text.primary, background: 'transparent',
  },
  kbd: {
    fontSize: T.font.size.xs, color: T.color.text.tertiary, fontFamily: T.font.mono,
    background: T.color.bg.secondary, border: `1px solid ${T.color.border.light}`,
    borderRadius: '3px', padding: '1px 5px',
  },
  results: { flex: 1, overflow: 'auto', padding: '4px 0' },
  category: {
    padding: '6px 16px 4px', fontSize: T.font.size.xs, fontWeight: T.font.weight.medium,
    color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps,
  },
  item: {
    display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 16px',
    cursor: 'pointer', transition: 'background 0.05s', fontSize: T.font.size.sm,
  },
  itemActive: { background: T.color.bg.hover },
  itemIcon: {
    width: '24px', height: '24px', borderRadius: T.radius.sm,
    background: T.color.bg.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: '11px', color: T.color.text.tertiary, flexShrink: 0,
  },
  itemLabel: { flex: 1, fontWeight: T.font.weight.medium, color: T.color.text.primary },
  itemHint: { fontSize: T.font.size.xs, color: T.color.text.tertiary },
  empty: { padding: '24px 16px', textAlign: 'center', fontSize: T.font.size.sm, color: T.color.text.tertiary },
};

function CommandPalette({ isOpen, onClose, onNavigate, onOpenMatter }) {
  const [query, setQuery] = useState('');
  const [activeIndex, setActiveIndex] = useState(0);
  const inputRef = useRef(null);
  const resultsRef = useRef(null);

  useEffect(() => {
    if (isOpen) { setQuery(''); setActiveIndex(0); setTimeout(() => inputRef.current?.focus(), 50); }
  }, [isOpen]);

  const filtered = useMemo(() => {
    if (!query.trim()) return CMD_ITEMS;
    const q = query.toLowerCase();
    return CMD_ITEMS.filter(item => item.label.toLowerCase().includes(q) || item.category.toLowerCase().includes(q));
  }, [query]);

  // Group by category
  const grouped = useMemo(() => {
    const map = {};
    filtered.forEach(item => {
      if (!map[item.category]) map[item.category] = [];
      map[item.category].push(item);
    });
    return map;
  }, [filtered]);

  const flatList = filtered;

  const execute = useCallback((item) => {
    if (!item) return;
    onClose();
    if (item.action === 'navigate') {
      onNavigate(item.target);
    } else if (item.action === 'matter') {
      const matter = window.MATTERS.find(m => m.id === item.target);
      if (matter) onOpenMatter(matter);
    }
  }, [onClose, onNavigate, onOpenMatter]);

  const handleKeyDown = (e) => {
    if (e.key === 'Escape') { onClose(); return; }
    if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIndex(i => Math.min(i + 1, flatList.length - 1)); }
    if (e.key === 'ArrowUp') { e.preventDefault(); setActiveIndex(i => Math.max(i - 1, 0)); }
    if (e.key === 'Enter') { e.preventDefault(); execute(flatList[activeIndex]); }
  };

  // Scroll active item into view
  useEffect(() => {
    const el = resultsRef.current?.querySelector(`[data-idx="${activeIndex}"]`);
    if (el) el.scrollIntoView({ block: 'nearest' });
  }, [activeIndex]);

  if (!isOpen) return null;

  let itemIdx = 0;

  return (
    <div style={cmdStyles.overlay} onClick={onClose}>
      <div style={cmdStyles.container} onClick={e => e.stopPropagation()}>
        <div style={cmdStyles.inputRow}>
          <span style={cmdStyles.inputIcon}></span>
          <input
            ref={inputRef}
            style={cmdStyles.input}
            placeholder="Search matters, people, actions..."
            value={query}
            onChange={e => { setQuery(e.target.value); setActiveIndex(0); }}
            onKeyDown={handleKeyDown}
          />
          <span style={cmdStyles.kbd}>esc</span>
        </div>
        <div style={cmdStyles.results} ref={resultsRef}>
          {flatList.length === 0 ? (
            <div style={cmdStyles.empty}>No results for "{query}"</div>
          ) : (
            Object.entries(grouped).map(([cat, items]) => (
              <div key={cat}>
                <div style={cmdStyles.category}>{cat}</div>
                {items.map(item => {
                  const idx = flatList.indexOf(item);
                  return (
                    <div
                      key={item.id}
                      data-idx={idx}
                      style={{...cmdStyles.item, ...(activeIndex === idx ? cmdStyles.itemActive : {})}}
                      onMouseEnter={() => setActiveIndex(idx)}
                      onClick={() => execute(item)}
                    >
                      <div style={cmdStyles.itemIcon}>{item.icon}</div>
                      <span style={cmdStyles.itemLabel}>{item.label}</span>
                      {activeIndex === idx && <span style={cmdStyles.itemHint}>↵</span>}
                    </div>
                  );
                })}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
