/**
 * 全局搜索 — Ctrl+K 快捷键触发
 * 搜索范围：军令、将军、战法
 */

import { useState, useEffect } from 'react';
import { useStore } from '../store';

export default function GlobalSearch({ onClose }: { onClose: () => void }) {
  const [query, setQuery] = useState('');
  const liveStatus = useStore((s) => s.liveStatus);
  const officialsData = useStore((s) => s.officialsData);
  const setModalTaskId = useStore((s) => s.setModalTaskId);

  const tasks = liveStatus?.tasks || [];
  const officials = officialsData?.officials || [];

  const q = query.trim().toLowerCase();
  const matchedTasks = q ? tasks.filter((t) =>
    t.id.toLowerCase().includes(q) ||
    t.title.toLowerCase().includes(q)
  ).slice(0, 8) : [];

  const matchedAgents = q ? officials.filter((o) =>
    o.role.toLowerCase().includes(q) ||
    o.id.toLowerCase().includes(q)
  ).slice(0, 5) : [];

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);

  return (
    <div className="confirm-bg open" onClick={onClose}>
      <div className="confirm-box" style={{ maxWidth: 560 }} onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12 }}>
          <span style={{ fontSize: 14 }}>🔍</span>
          <input
            autoFocus
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="搜索军令、将军、战法..."
            style={{
              flex: 1, background: 'var(--panel2)', border: '1px solid var(--line)',
              borderRadius: 8, padding: '8px 12px', fontSize: 14, color: 'var(--text)', outline: 'none',
            }}
          />
          <span style={{ fontSize: 10, color: 'var(--muted)' }}>ESC 关闭</span>
        </div>

        {matchedTasks.length > 0 && (
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--muted)', marginBottom: 6 }}>📜 军令</div>
            {matchedTasks.map((t) => (
              <div
                key={t.id}
                style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '6px 10px', borderRadius: 6, cursor: 'pointer', border: '1px solid transparent' }}
                onClick={() => { setModalTaskId(t.id); onClose(); }}
                onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--panel2)'; e.currentTarget.style.borderColor = 'var(--line)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = 'transparent'; }}
              >
                <span style={{ fontSize: 10, color: 'var(--acc)', fontWeight: 600 }}>{t.id}</span>
                <span style={{ flex: 1, fontSize: 12 }}>{t.title.substring(0, 40)}</span>
                <span style={{ fontSize: 10, color: 'var(--muted)' }}>{t.state}</span>
              </div>
            ))}
          </div>
        )}

        {matchedAgents.length > 0 && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--muted)', marginBottom: 6 }}>⚔️ 将军</div>
            {matchedAgents.map((o) => (
              <div
                key={o.id}
                style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '6px 10px', borderRadius: 6 }}
              >
                <span>{o.emoji}</span>
                <span style={{ fontSize: 12, fontWeight: 600 }}>{o.role}</span>
                <span style={{ fontSize: 11, color: 'var(--muted)' }}>{o.model_short}</span>
              </div>
            ))}
          </div>
        )}

        {q && matchedTasks.length === 0 && matchedAgents.length === 0 && (
          <div style={{ fontSize: 12, color: 'var(--muted)', padding: '8px 0', textAlign: 'center' }}>
            未找到「{query}」相关结果
          </div>
        )}

        {!q && (
          <div style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'center', padding: '8px 0' }}>
            输入关键词搜索军令、将军
          </div>
        )}
      </div>
    </div>
  );
}
