// Full-screen search overlay — live-filters the live tile catalogue.
const { useEffect, useMemo, useRef, useState } = React;

function SearchOverlay({ open, onClose, tiles, navigate }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      setTimeout(() => inputRef.current?.focus(), 50);
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      window.addEventListener('keydown', onKey);
      return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
    } else {
      document.body.style.overflow = '';
      setQ('');
    }
  }, [open, onClose]);

  // Search across the new-schema fields (collection, variantLabel,
  // multi-value finishes / sizes / colours / styles). Falls back to
  // legacy single-value fields so older catalogue records still match.
  const results = useMemo(() => {
    const query = q.trim().toLowerCase();
    if (!query) return tiles.slice(0, 18);
    const hayOf = (t) => [
      t.name, t.collection, t.variantLabel,
      ...(Array.isArray(t.finishes) ? t.finishes : [t.finish]),
      ...(Array.isArray(t.sizes)    ? t.sizes    : [t.size]),
      ...(Array.isArray(t.colours)  ? t.colours  : [t.colour]),
      ...(Array.isArray(t.styles)   ? t.styles   : [t.style]),
    ].filter(Boolean).join(' ').toLowerCase();
    return tiles.filter(t => hayOf(t).includes(query)).slice(0, 48);
  }, [q, tiles]);

  if (!open) return null;

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--cream)', zIndex: 210, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: 'clamp(14px, 3vw, 18px) clamp(16px, 4vw, 36px)', display: 'flex', alignItems: 'center', gap: 'clamp(10px, 2vw, 20px)', borderBottom: '1px solid var(--cream-deep)' }}>
        <span style={{ fontFamily: 'var(--sans)', fontSize: '12px', letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--dark-mid)' }}>Search</span>
        <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="What are you looking for?" style={{
          flex: 1, minWidth: 0,
          border: 'none', outline: 'none', background: 'transparent', padding: '10px 0',
          fontFamily: 'var(--serif)', fontSize: 'clamp(22px, 4vw, 48px)', fontWeight: 300, color: 'var(--dark)',
        }}/>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: '22px', color: 'var(--dark-mid)', flexShrink: 0 }}>✕</button>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: 'clamp(20px, 4vw, 32px) clamp(16px, 4vw, 36px)' }}>
        <p className="t-label" style={{ color: 'var(--dark-mid)', marginBottom: '18px' }}>
          {q.trim() ? `${results.length} result${results.length === 1 ? '' : 's'}` : 'Featured'}
        </p>
        {results.length === 0 ? (
          <p style={{ fontFamily: 'var(--serif)', fontSize: '22px', fontWeight: 300, color: 'var(--dark-mid)' }}>
            Nothing matching "{q}". Try a collection, finish, or size.
          </p>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: '18px 14px' }}>
            {results.map(t => {
              const thumb = (Array.isArray(t.sightImages) && t.sightImages[0]) || t.img || '';
              const sub   = [t.collection, (Array.isArray(t.sizes) && t.sizes[0]) || t.size].filter(Boolean).join(' · ');
              return (
                <button key={t.id} onClick={() => { onClose(); navigate('product', t); }} style={{
                  background: 'none', border: 'none', padding: 0, cursor: 'pointer', textAlign: 'left',
                }}>
                  <div className="tile-frame" style={{ aspectRatio: '1', overflow: 'hidden' }}>
                    <img src={thumb} alt={t.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={e => e.target.style.display='none'}/>
                  </div>
                  <p style={{ fontFamily: 'var(--serif)', fontSize: '15px', marginTop: '10px' }}>{t.name}</p>
                  <p style={{ fontFamily: 'var(--sans)', fontSize: '11px', color: 'var(--dark-mid)', marginTop: '2px' }}>{sub || '—'}</p>
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SearchOverlay });
