// Command Palette — Cmd+K
const CPIcons = window.Icons;

const VIEWS = [
  { id: 'dashboard', label: 'Panel',          icon: 'Dashboard'    },
  { id: 'all-tasks', label: 'Tüm Görevler',   icon: 'CheckSquare'  },
  { id: 'table',     label: 'Tablo Görünümü', icon: 'Table'        },
  { id: 'calendar',  label: 'Takvim',         icon: 'Calendar'     },
  { id: 'gantt',     label: 'Gantt',          icon: 'GanttChart'   },
  { id: 'content',   label: 'İçerik Takvimi', icon: 'Instagram'    },
  { id: 'reports',   label: 'Raporlar',       icon: 'TrendingUp'   },
  { id: 'team',      label: 'Ekip',           icon: 'Users'        },
  { id: 'profile',   label: 'Profil',         icon: 'User'         },
];

function CommandPalette({ state, onClose, onNavigate, onSelectTask, onCreateTask, onSetTheme }) {
  const [query, setQuery] = React.useState('');
  const [sel,   setSel]   = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => { setTimeout(() => inputRef.current?.focus(), 10); }, []);

  const results = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    const items = [];

    if (!q) {
      // Quick actions
      items.push({ type: 'action', label: 'Yeni Görev', icon: 'Plus', hint: 'N', run: () => onCreateTask() });
      VIEWS.forEach(v => items.push({ type: 'view', label: v.label, icon: v.icon, run: () => onNavigate(v.id) }));
      items.push({ type: 'action', label: 'Temayı Değiştir', icon: 'Sun', run: () => { const n={auto:'light',light:'dark',dark:'auto'}; onSetTheme(n[state.theme]||'light'); } });
      state.projects.filter(p => !p.archived).slice(0, 5).forEach(p => {
        items.push({ type: 'project', label: p.name, color: p.color, run: () => onNavigate('kanban', p.id) });
      });
      return items;
    }

    // Search tasks — tüm firmalar genelinde: başlık, açıklama ve etiketlerde ara
    const tagById = Object.fromEntries((state.tags || []).map(t => [t.id, t]));
    state.tasks
      .filter(t => !t.archived && (
        t.title.toLowerCase().includes(q) ||
        (t.description || '').toLowerCase().includes(q) ||
        (t.tags || []).some(tid => (tagById[tid]?.name || '').toLowerCase().includes(q))
      ))
      .slice(0, 10)
      .forEach(t => {
        const proj = state.projects.find(p => p.id === t.projectId);
        items.push({ type: 'task', label: t.title, meta: proj?.name, color: proj?.color, id: t.id, run: () => onSelectTask(t.id) });
      });

    // Search projects
    state.projects.filter(p => p.name.toLowerCase().includes(q)).forEach(p => {
      items.push({ type: 'project', label: p.name, color: p.color, run: () => onNavigate('kanban', p.id) });
    });

    // Search views
    VIEWS.filter(v => v.label.toLowerCase().includes(q)).forEach(v => {
      items.push({ type: 'view', label: v.label, icon: v.icon, run: () => onNavigate(v.id) });
    });

    return items;
  }, [query, state]);

  React.useEffect(() => { setSel(0); }, [query]);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape')    { onClose(); return; }
      if (e.key === 'ArrowDown') { setSel(s => Math.min(s + 1, results.length - 1)); e.preventDefault(); }
      if (e.key === 'ArrowUp')   { setSel(s => Math.max(s - 1, 0)); e.preventDefault(); }
      if (e.key === 'Enter' && results[sel]) { results[sel].run(); onClose(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [results, sel, onClose]);

  const typeLabel = { task: 'Görev', project: 'Proje', view: 'Sayfa', action: 'Aksiyon' };

  return (
    <div className="cmd-overlay" onClick={onClose}>
      <div className="cmd-palette" onClick={e => e.stopPropagation()}>
        <div className="cmd-input-row">
          <CPIcons.Search size={16} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
          <input
            ref={inputRef}
            className="cmd-input"
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Görev ara, sayfa geç, aksiyon çalıştır..."
          />
          {query ? (
            <button className="cmd-clear" onClick={() => setQuery('')}><CPIcons.X size={13} /></button>
          ) : (
            <kbd className="cmd-esc">Esc</kbd>
          )}
        </div>

        <div className="cmd-results">
          {!query && (
            <div className="cmd-section-label">Hızlı Erişim</div>
          )}
          {results.length === 0 && (
            <div className="cmd-empty">"{query}" için sonuç bulunamadı</div>
          )}
          {results.map((r, i) => {
            const Icon = r.icon ? CPIcons[r.icon] : null;
            return (
              <button
                key={i}
                className={`cmd-result ${sel === i ? 'active' : ''}`}
                onClick={() => { r.run(); onClose(); }}
                onMouseEnter={() => setSel(i)}
              >
                <span className="cmd-result-icon">
                  {r.type === 'project' || r.type === 'task' ? (
                    <span className="cmd-dot" style={{ background: r.color || 'var(--text-faint)' }} />
                  ) : Icon ? (
                    <Icon size={14} />
                  ) : null}
                </span>
                <span className="cmd-result-label">{r.label}</span>
                {r.meta && <span className="cmd-result-meta">{r.meta}</span>}
                <span className="cmd-result-type">{typeLabel[r.type]}</span>
                {r.hint && <kbd className="cmd-hint">{r.hint}</kbd>}
              </button>
            );
          })}
        </div>

        <div className="cmd-footer">
          <span><kbd>↑↓</kbd> Gezin</span>
          <span><kbd>Enter</kbd> Seç</span>
          <span><kbd>Esc</kbd> Kapat</span>
        </div>
      </div>
    </div>
  );
}

function ShortcutsOverlay({ onClose }) {
  React.useEffect(() => {
    const fn = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [onClose]);

  const shortcuts = [
    { keys: ['⌘', 'K'], label: 'Komut paleti' },
    { keys: ['N'],        label: 'Yeni görev' },
    { keys: ['/'],        label: 'Arama odağı' },
    { keys: ['?'],        label: 'Kısayolları göster' },
    { keys: ['⌘', 'Z'],  label: 'Son işlemi geri al' },
    { keys: ['Esc'],      label: 'Kapat / Geri' },
    { keys: ['←', '→'],  label: 'Görevler arası gezin' },
  ];

  return (
    <div className="cmd-overlay" onClick={onClose}>
      <div className="shortcuts-panel" onClick={e => e.stopPropagation()}>
        <div className="shortcuts-header">
          <h3>Klavye Kısayolları</h3>
          <button className="icon-btn icon-btn-sm" onClick={onClose}><CPIcons.X size={16} /></button>
        </div>
        <div className="shortcuts-grid">
          {shortcuts.map((s, i) => (
            <div key={i} className="shortcut-row">
              <span className="shortcut-label">{s.label}</span>
              <div className="shortcut-keys">
                {s.keys.map((k, j) => <kbd key={j} className="shortcut-key">{k}</kbd>)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.CommandPalette  = CommandPalette;
window.ShortcutsOverlay = ShortcutsOverlay;
