// Trove — search bar with smart suggestions
function SmartSearchBar({ value, onChange, onSubmit, autoFocus, big, placeholder, onFilterChip }) {
  const [open, setOpen] = React.useState(false);
  const [focused, setFocused] = React.useState(false);
  const inputRef = React.useRef(null);
  const wrapRef = React.useRef(null);

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

  React.useEffect(() => {
    function onDoc(e) { if (!wrapRef.current?.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const { results, suggestion, chips } = React.useMemo(
    () => window.troveSearch(value || '', window.RESOURCES),
    [value]
  );

  const showDropdown = open && (focused) && (value || '').trim().length > 0;
  const popular = ['Year 1 phonics', 'Year 5 fractions', 'Year 6 SATs revision', 'Iron Man', 'Times tables', 'Persuasive writing'];

  function handleKey(e) {
    if (e.key === 'Enter') { onSubmit?.(value); setOpen(false); inputRef.current?.blur(); }
    if (e.key === 'Escape') { setOpen(false); inputRef.current?.blur(); }
  }

  return (
    <div ref={wrapRef} style={{ position: 'relative', width: '100%', zIndex: showDropdown ? 200 : 'auto' }}>
      <div
        style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: big ? '4px 6px 4px 22px' : '4px 6px 4px 16px',
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: big ? 18 : 12,
          boxShadow: focused ? '0 0 0 4px var(--ring), 0 8px 30px -10px rgba(20,33,61,.18)' : 'var(--shadow-sm)',
          transition: 'box-shadow .2s, border-color .2s',
          borderColor: focused ? 'var(--accent)' : 'var(--border)',
        }}
      >
        <Icon.Search width={big ? 22 : 18} height={big ? 22 : 18} style={{ color: 'var(--fg-muted)' }} />
        <input
          ref={inputRef}
          value={value}
          onChange={(e) => { onChange(e.target.value); setOpen(true); }}
          onFocus={() => { setFocused(true); setOpen(true); }}
          onBlur={() => setFocused(false)}
          onKeyDown={handleKey}
          placeholder={placeholder || 'Search resources…'}
          style={{
            flex: 1, border: 0, outline: 0, background: 'transparent', color: 'var(--fg)',
            padding: big ? '16px 0' : '10px 0',
            fontSize: big ? 17 : 14, fontWeight: 500,
          }}
        />
        {value && (
          <button
            onClick={() => { onChange(''); inputRef.current?.focus(); }}
            className="btn btn-sm" style={{ padding: 6, color: 'var(--fg-muted)' }} aria-label="Clear">
            <Icon.X width="16" height="16" />
          </button>
        )}
        <button onClick={() => onSubmit?.(value)} className="btn btn-primary" style={big ? { padding: '12px 20px', borderRadius: 14 } : {}}>
          Search<Icon.ArrowRight width="16" height="16" />
        </button>
      </div>

      {showDropdown && (
        <div
          className="fade-in"
          style={{
            position: 'absolute', left: 0, right: 0, top: 'calc(100% + 8px)',
            zIndex: 200,
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 14, boxShadow: 'var(--shadow-lg)',
            padding: 8, zIndex: 40, maxHeight: 480, overflow: 'auto',
          }}
        >
          {suggestion && (
            <div style={{ padding: '10px 12px 8px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 8, color: 'var(--fg-muted)', fontSize: 13 }}>
              <Icon.Sparkle width="15" height="15" style={{ color: 'var(--gold-deep)' }} />
              <span>Did you mean</span>
              <button
                onClick={() => onChange(suggestion)}
                style={{ background: 'transparent', border: 0, color: 'var(--fg)', fontWeight: 600, textDecoration: 'underline', textUnderlineOffset: 3, cursor: 'pointer', padding: 0 }}>
                {suggestion}
              </button>
              <span>?</span>
            </div>
          )}

          {chips.length > 0 && (
            <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border)' }}>
              <div className="t-micro" style={{ color: 'var(--fg-subtle)', marginBottom: 8 }}>Apply filter</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {chips.map((c, i) => (
                  <button
                    key={i}
                    onClick={() => onFilterChip?.(c)}
                    className="pill pill-accent" style={{ cursor: 'pointer', padding: '5px 11px', fontWeight: 600 }}>
                    + {c.label}
                  </button>
                ))}
              </div>
            </div>
          )}

          {results.length > 0 ? (
            <div style={{ padding: 4 }}>
              <div className="t-micro" style={{ color: 'var(--fg-subtle)', padding: '8px 8px 4px' }}>
                {results.length} {results.length === 1 ? 'match' : 'matches'}
              </div>
              {results.slice(0, 6).map(r => (
                <button
                  key={r.id}
                  onClick={() => onSubmit?.(value, r)}
                  style={{
                    width: '100%', display: 'flex', gap: 12, padding: '8px 10px',
                    background: 'transparent', border: 0, borderRadius: 10,
                    cursor: 'pointer', alignItems: 'center', textAlign: 'left',
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-sunken)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                >
                  <div style={{ width: 36, height: 48, flexShrink: 0 }}>
                    <ResourceCover resource={r} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--fg-muted)', display: 'flex', gap: 8 }}>
                      <span>{r.year} · {r.subject}</span>
                      <span>·</span>
                      <span>{r.scheme}</span>
                    </div>
                  </div>
                  <Icon.ArrowRight width="15" height="15" style={{ color: 'var(--fg-subtle)' }} />
                </button>
              ))}
              {results.length > 6 && (
                <button
                  onClick={() => onSubmit?.(value)}
                  style={{ width: '100%', textAlign: 'left', padding: '10px 14px', background: 'transparent', border: 0, color: 'var(--fg-muted)', fontSize: 13, cursor: 'pointer', borderTop: '1px solid var(--border)', marginTop: 4, fontWeight: 500 }}>
                  See all {results.length} matches →
                </button>
              )}
            </div>
          ) : (
            <div style={{ padding: '14px 14px 8px' }}>
              <div className="t-micro" style={{ color: 'var(--fg-subtle)', marginBottom: 8 }}>
                {value ? 'No matches, try' : 'Popular searches'}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {popular.map(p => (
                  <button key={p} className="pill" style={{ cursor: 'pointer' }} onClick={() => onChange(p)}>{p}</button>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
window.SmartSearchBar = SmartSearchBar;
