// Hero search — naive client-side substring + word-prefix match over
// categories and the hardware sample products. Dropdown of 5 results.
// Empty-result state offers a WhatsApp fallback.
//
// No backend; this is honest about scope.

(function () {
  function tokenize(s) {
    return (s || '').toLowerCase().split(/\s+/).filter(Boolean);
  }

  function matchScore(query, target) {
    const q = tokenize(query);
    const t = (target || '').toLowerCase();
    let score = 0;
    for (const tok of q) {
      const idx = t.indexOf(tok);
      if (idx < 0) return 0;                         // missing token kills the match
      score += (idx === 0 || /[\s\-]/.test(t.charAt(idx - 1))) ? 3 : 1;
    }
    return score;
  }

  function search(query) {
    if (!query || query.trim().length < 2) return [];
    const cats = window.NAJMAT_DATA.categories.map(c => ({
      kind: 'category', label: c.name, sub: `Category · ${c.count.toLocaleString()} SKUs`, href: `#/c/${c.slug}`, score: matchScore(query, c.name),
    }));
    const prods = window.NAJMAT_DATA.products.map(p => ({
      kind: 'product', label: p.name, sub: `${p.brand} · ${p.sku}`, href: `#/p/${p.sku}`, score: matchScore(query, `${p.name} ${p.brand} ${p.sku}`),
    }));
    return [...cats, ...prods].filter(r => r.score > 0).sort((a, b) => b.score - a.score).slice(0, 5);
  }

  window.HeroSearch = function HeroSearch() {
    const [q, setQ] = React.useState('');
    const [open, setOpen] = React.useState(false);
    const [active, setActive] = React.useState(0);
    const results = React.useMemo(() => search(q), [q]);

    function go(item) {
      if (item) window.location.hash = item.href;
      setOpen(false);
      setQ('');
    }

    function onKeyDown(e) {
      if (!open || results.length === 0) {
        if (e.key === 'Enter' && q.trim().length >= 2) {
          // No results → fall back to WhatsApp
          window.open(window.waUrl(`Looking for "${q.trim()}" — please check stock.`), '_blank', 'noopener');
        }
        return;
      }
      if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(a + 1, results.length - 1)); }
      else if (e.key === 'ArrowUp')   { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
      else if (e.key === 'Enter')     { e.preventDefault(); go(results[active]); }
      else if (e.key === 'Escape')    { setOpen(false); }
    }

    return (
      <form className="hero-search" role="search" onSubmit={e => { e.preventDefault(); go(results[active]); }}>
        <label htmlFor="hero-q" className="sr-only">Search the catalogue</label>
        <span className="hero-search-icon" aria-hidden="true">{window.Icon.search({ size: 18 })}</span>
        <input
          id="hero-q"
          autoComplete="off"
          spellCheck="false"
          className="hero-search-input"
          placeholder={`Search 11,894 SKUs — try "mortise lock" or "16mm anchor"`}
          value={q}
          onChange={e => { setQ(e.target.value); setOpen(true); setActive(0); }}
          onFocus={() => setOpen(true)}
          onBlur={() => setTimeout(() => setOpen(false), 150)}
          onKeyDown={onKeyDown}
          aria-controls="hero-q-results"
          aria-autocomplete="list"
        />
        <button type="submit" className="hero-search-btn">Search</button>

        {open && q.trim().length >= 2 && (
          <ul id="hero-q-results" className="hero-search-results" role="listbox">
            {results.length === 0 && (
              <li className="hero-search-empty" role="status">
                couldn't find <strong>"{q.trim()}"</strong>.{' '}
                <a href={window.waUrl(`Looking for "${q.trim()}" — please check stock.`)} target="_blank" rel="noopener noreferrer">whatsapp us — we'll check stock →</a>
              </li>
            )}
            {results.map((r, i) => (
              <li
                key={r.href + i}
                role="option"
                aria-selected={i === active}
                className={`hero-search-row ${i === active ? 'is-active' : ''}`}
                onMouseDown={() => go(r)}
                onMouseEnter={() => setActive(i)}
              >
                <span className="hero-search-row-label">{r.label}</span>
                <span className="hero-search-row-sub label-mono">{r.sub}</span>
              </li>
            ))}
          </ul>
        )}
      </form>
    );
  };
})();
