/* Search palette — ⌘K command palette. Wires to /api/species?search=
   for live results. The prototype renders inside a modal overlay; here
   we render it as a full-page so the spec is reviewable. */

const SEARCH_SECTIONS = [
  { id: 'jump', label: 'Jump to', static: [
    { route: '#dashboard', icon: 'home', label: 'Dashboard' },
    { route: '#library', icon: 'library', label: 'Species Library' },
    { route: '#displays', icon: 'monitor', label: 'Display screens' },
    { route: '#campaigns', icon: 'spark', label: 'Campaigns' },
    { route: '#users', icon: 'users', label: 'Users' },
    { route: '#settings', icon: 'settings', label: 'Settings' },
  ] },
];

function SearchScreen() {
  const [q, setQ] = useState('');
  const [species, setSpecies] = useState([]);
  const [loading, setLoading] = useState(false);
  const [cursor, setCursor] = useState(0);

  useEffect(() => {
    if (!q || q.length < 2) {
      setSpecies([]);
      return;
    }
    let cancelled = false;
    setLoading(true);
    apiFetch(`/api/species?search=${encodeURIComponent(q)}&limit=10`)
      .then((r) => { if (!cancelled) { setSpecies(r.species || []); setLoading(false); } })
      .catch(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [q]);

  const jumpResults = SEARCH_SECTIONS[0].static.filter(
    (s) => !q || s.label.toLowerCase().includes(q.toLowerCase())
  );

  /* Flatten species + jump-to into one navigable list. Each entry knows
     how to navigate when chosen. */
  const flat = useMemo(() => {
    const list = [];
    species.forEach((sp) => list.push({
      kind: 'species', label: sp.common_name, sub: sp.scientific_name,
      go: () => { window.location.hash = `#species/${sp.id}`; },
    }));
    jumpResults.forEach((r) => list.push({
      kind: 'jump', label: r.label, sub: r.route,
      go: () => { window.location.hash = r.route; },
    }));
    return list;
  }, [species, jumpResults]);

  /* Reset cursor when results change so it never points past the end. */
  useEffect(() => { setCursor(0); }, [q, flat.length]);

  function onKeyDown(e) {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setCursor((c) => Math.min(flat.length - 1, c + 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setCursor((c) => Math.max(0, c - 1));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      const item = flat[cursor];
      if (item) item.go();
    } else if (e.key === 'Escape') {
      window.history.length > 1 ? window.history.back() : (window.location.hash = '#dashboard');
    }
  }

  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 720 }}>
        <div className="aq-eyebrow" style={{ marginBottom: 16 }}>
          ⌘K palette · search across the workspace
        </div>

        <div className="x-card" style={{ overflow: 'visible', padding: 0 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 18px', borderBottom: '1px solid var(--aq-line)',
          }}>
            <Icon name="search" size={16} />
            <input
              autoFocus
              placeholder="Type to search species, screens, campaigns, people…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onKeyDown={onKeyDown}
              style={{
                flex: 1, background: 'transparent', border: 0, outline: 0,
                color: 'var(--aq-text)', fontFamily: 'inherit', fontSize: 14,
              }}
            />
            <span className="aq-kbd" style={{
              fontSize: 10, padding: '1px 6px', border: '1px solid var(--aq-line)',
              borderRadius: 4, color: 'var(--aq-text-faint)',
              fontFamily: 'var(--aq-ff-mono)',
            }}>esc</span>
          </div>

          <div style={{ maxHeight: 480, overflowY: 'auto' }}>
            {/* Species results */}
            {q.length >= 2 && (
              <div style={{ padding: '12px 8px 8px' }}>
                <div className="x-eyebrow" style={{ padding: '0 10px 6px' }}>
                  {loading ? 'Searching…' : `Species · ${species.length}`}
                </div>
                {species.map((sp, i) => (
                  <button
                    key={sp.id}
                    onClick={() => { window.location.hash = `#species/${sp.id}`; }}
                    onMouseEnter={() => setCursor(i)}
                    style={{
                      width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                      padding: '8px 10px', borderRadius: 6, border: 0,
                      background: cursor === i ? 'var(--aq-surface-2)' : 'transparent',
                      color: 'var(--aq-text)',
                      font: 'inherit', textAlign: 'left', cursor: 'pointer',
                    }}
                  >
                    <Icon name="fish" size={14} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13 }}>{sp.common_name}</div>
                      <div style={{
                        fontSize: 11, color: 'var(--aq-text-faint)',
                        fontStyle: 'italic',
                      }}>{sp.scientific_name}</div>
                    </div>
                    <span className={`aq-pill is-soft is-${sp.iucn_status === 'Least Concern' ? 'success' : 'neutral'}`}>
                      {sp.iucn_status}
                    </span>
                  </button>
                ))}
                {!loading && species.length === 0 && (
                  <div style={{ padding: '8px 10px', color: 'var(--aq-text-faint)', fontSize: 12 }}>
                    No species match "{q}"
                  </div>
                )}
              </div>
            )}

            {/* Jump-to results */}
            <div style={{ padding: '8px 8px 14px' }}>
              <div className="x-eyebrow" style={{ padding: '0 10px 6px' }}>Jump to</div>
              {jumpResults.map((r, j) => {
                const idx = species.length + j;
                return (
                <button
                  key={r.route}
                  onClick={() => { window.location.hash = r.route; }}
                  onMouseEnter={() => setCursor(idx)}
                  style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                    padding: '8px 10px', borderRadius: 6, border: 0,
                    background: cursor === idx ? 'var(--aq-surface-2)' : 'transparent',
                    color: 'var(--aq-text)',
                    font: 'inherit', textAlign: 'left', cursor: 'pointer',
                  }}
                >
                  <Icon name={r.icon} size={14} />
                  <span style={{ flex: 1, fontSize: 13 }}>{r.label}</span>
                  <span style={{
                    fontFamily: 'var(--aq-ff-mono)', fontSize: 10,
                    color: 'var(--aq-text-faint)',
                  }}>{r.route}</span>
                </button>
              );
              })}
            </div>
          </div>

          <div style={{
            display: 'flex', justifyContent: 'space-between',
            padding: '8px 16px', borderTop: '1px solid var(--aq-line)',
            fontFamily: 'var(--aq-ff-mono)', fontSize: 10.5,
            color: 'var(--aq-text-faint)', letterSpacing: '0.04em',
          }}>
            <span>↵ open · ↑↓ navigate · esc close</span>
            <span>{loading ? 'searching…' : 'ready'}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

window.SearchScreen = SearchScreen;
