// Global search — a ⌘K command palette over assets, routines, contacts,
// to-dos, household members, and quick screen navigation. Keyboard-driven.

const { FONT_DISPLAY: SE_DISPLAY, FONT_BODY: SE_BODY, FONT_MONO: SE_MONO } = window.HIFI;

const SCREEN_TARGETS = [
  { label: 'Dashboard', screen: 'dashboard', icon: 'home', keys: 'home overview' },
  { label: 'Assets', screen: 'assets', icon: 'grid', keys: 'things equipment appliances' },
  { label: 'Routines', screen: 'routines', icon: 'repeat', keys: 'calendar maintenance schedule reminders' },
  { label: 'Contacts', screen: 'contacts', icon: 'phone', keys: 'companies people vendors' },
  { label: 'To-Dos', screen: 'todos', icon: 'check', keys: 'tasks info gaps' },
  { label: 'Profile', screen: 'profile', icon: 'user', keys: 'settings account notifications calendar' },
];

// Build a flat, ranked result set for a query.
function searchAll(q) {
  const s = (q || '').trim().toLowerCase();
  if (!s) return [];
  const hit = (txt) => (txt || '').toLowerCase().includes(s);
  const out = [];

  ASSETS.forEach(a => {
    if (hit(a.name) || hit(a.cat) || hit(a.make) || hit(a.model)) {
      out.push({ group: 'Assets', icon: CAT_ICON[a.cat] || 'grid', title: a.name,
        sub: `${a.cat}${a.make && a.make !== '—' && !isGap(a.make) ? ' · ' + a.make : ''}`,
        run: (nav) => nav.openAsset(a.id) });
    }
  });
  ROUTINES.forEach(r => {
    if (hit(r.task) || hit((findAsset(r.asset) || {}).name)) {
      out.push({ group: 'Routines', icon: 'repeat', title: r.task,
        sub: `${(findAsset(r.asset) || {}).name || 'Routine'} · ${r.nextLabel}`,
        run: (nav) => nav.openRoutine(r.id) });
    }
  });
  CONTACTS.forEach(c => {
    const peopleHit = (c.people || []).some(p => hit(p.name) || hit(p.role));
    if (hit(c.co) || hit(c.cat) || peopleHit) {
      out.push({ group: 'Contacts', icon: 'phone', title: c.co,
        sub: `${c.cat}${(c.people || []).length ? ' · ' + c.people.length + ' contact' + (c.people.length > 1 ? 's' : '') : ''}`,
        run: (nav) => nav.openContact(c.id) });
    }
  });
  TODOS.forEach(td => {
    if (hit(td.title) || hit(td.type)) {
      out.push({ group: 'To-Dos', icon: td.type === 'Info Gap' ? 'search' : 'check', title: td.title,
        sub: `${td.type} · ${td.priority}${td.status === 'Done' ? ' · done' : ''}`,
        run: (nav) => nav.go('todos') });
    }
  });
  if (window.Account) {
    // No-op — single-user app, no household to search.
  }
  SCREEN_TARGETS.forEach(tg => {
    if (hit(tg.label) || hit(tg.keys)) {
      out.push({ group: 'Go to', icon: tg.icon, title: tg.label, sub: 'Open screen', run: (nav) => nav.go(tg.screen) });
    }
  });
  return out;
}

const SearchOverlay = ({ t, nav, initialQuery = '' }) => {
  const [q, setQ] = React.useState(initialQuery);
  const [sel, setSel] = React.useState(0);
  const inputRef = React.useRef(null);
  const listRef = React.useRef(null);

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

  const results = React.useMemo(() => searchAll(q), [q]);
  React.useEffect(() => { setSel(0); }, [q]);

  // group for display while keeping a flat index for keyboard nav
  const groups = [];
  const flat = [];
  results.forEach(r => {
    let g = groups.find(x => x.name === r.group);
    if (!g) { g = { name: r.group, items: [] }; groups.push(g); }
    g.items.push(r);
  });
  groups.forEach(g => g.items.forEach(it => { it._i = flat.length; flat.push(it); }));

  const activate = (it) => { if (!it) return; nav.closeSearch(); it.run(nav); };

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel(s => Math.min(s + 1, flat.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSel(s => Math.max(s - 1, 0)); }
    else if (e.key === 'Enter') { e.preventDefault(); activate(flat[sel]); }
    else if (e.key === 'Escape') { e.preventDefault(); nav.closeSearch(); }
  };

  React.useEffect(() => {
    const el = listRef.current && listRef.current.querySelector(`[data-i="${sel}"]`);
    if (el && el.scrollIntoView) el.scrollIntoView({ block: 'nearest' });
  }, [sel]);

  return (
    <div onClick={nav.closeSearch} style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: 'rgba(20,18,12,0.34)', backdropFilter: 'blur(2px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: '12vh 16px 16px',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 560, background: t.card, borderRadius: 16,
        border: `1px solid ${t.border}`, boxShadow: '0 24px 70px rgba(20,18,12,0.28)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden', maxHeight: '72vh',
      }}>
        {/* input */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '15px 18px', borderBottom: `1px solid ${t.divider}` }}>
          <HIcon kind="search" size={18} style={{ color: t.inkSoft, flex: '0 0 auto' }}/>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} onKeyDown={onKey}
            placeholder="Search assets, routines, contacts, to-dos, people…"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: SE_BODY, fontSize: 16, color: t.ink }}/>
          <span style={{ fontFamily: SE_MONO, fontSize: 11, color: t.inkFaint, border: `1px solid ${t.border}`, borderRadius: 6, padding: '2px 6px', flex: '0 0 auto' }}>esc</span>
        </div>

        {/* results */}
        <div ref={listRef} style={{ overflowY: 'auto', padding: '6px 8px 10px' }}>
          {q.trim() === '' && (
            <div style={{ padding: '26px 14px', textAlign: 'center', color: t.inkFaint, fontSize: 13.5 }}>
              Type to search across everything in your Hub.
              <div style={{ marginTop: 6, fontSize: 12.5 }}>Use <span style={{ fontFamily: SE_MONO }}>↑ ↓</span> to move, <span style={{ fontFamily: SE_MONO }}>↵</span> to open.</div>
            </div>
          )}
          {q.trim() !== '' && flat.length === 0 && (
            <div style={{ padding: '26px 14px', textAlign: 'center', color: t.inkFaint, fontSize: 13.5 }}>
              No matches for “<span style={{ color: t.inkSoft }}>{q}</span>”.
            </div>
          )}
          {groups.map(g => (
            <div key={g.name} style={{ marginTop: 6 }}>
              <div style={{ fontSize: 10.5, color: t.inkFaint, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', padding: '8px 12px 4px' }}>{g.name}</div>
              {g.items.map(it => {
                const active = it._i === sel;
                return (
                  <div key={it._i} data-i={it._i}
                    onClick={() => activate(it)} onMouseEnter={() => setSel(it._i)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 11, padding: '9px 12px', borderRadius: 9, cursor: 'pointer',
                      background: active ? t.hover : 'transparent',
                    }}>
                    <span style={{ width: 30, height: 30, borderRadius: 8, flex: '0 0 auto', background: t.inputBg, border: `1px solid ${t.border}`, color: t.inkSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><HIcon kind={it.icon} size={15}/></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, color: t.ink, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                      <div style={{ fontSize: 12, color: t.inkSoft, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.sub}</div>
                    </div>
                    {active && <HIcon kind="chev" size={14} style={{ color: t.inkFaint, flex: '0 0 auto' }}/>}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { searchAll, SearchOverlay });
