// ZION SearchOverlay — full-screen search that filters the catalog live.
// Opens from the header SEARCH link. Esc or backdrop click closes.
function SearchOverlay({ open, onClose, onOpen }) {
  const [q, setQ] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const inputRef = React.useRef(null);

  // Combined catalog: the two balls + apparel — all from the shared data so
  // results carry real images and open the product page with photos.
  const catalog = React.useMemo(() => {
    const apparel = (window.ZION_SHOW_APPAREL === false) ? [] : (window.ZION_PRODUCTS || []);
    const balls = window.ZION_FIREBALLS || [];
    return [...balls, ...apparel];
  }, []);

  const results = q.trim()
    ? catalog.filter(p => (p.name + ' ' + (p.sub || '')).toLowerCase().includes(q.trim().toLowerCase()))
    : catalog;

  React.useEffect(() => {
    if (open) { setQ(''); setTimeout(() => inputRef.current && inputRef.current.focus(), 60); }
  }, [open]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(8,8,8,0.8)', backdropFilter: 'blur(16px)',
      display: 'flex', justifyContent: 'center', alignItems: 'flex-start',
      padding: '11vh 20px 40px', overflowY: 'auto',
    }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 620 }}>

        {/* Search bar — rounded field with icon */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          background: 'rgba(255,255,255,0.05)',
          border: `1px solid ${focused ? 'rgba(247,89,31,0.6)' : 'rgba(255,255,255,0.14)'}`,
          borderRadius: 16, padding: '15px 16px',
          boxShadow: focused ? '0 0 0 4px rgba(247,89,31,0.12)' : '0 10px 40px rgba(0,0,0,0.4)',
          transition: 'border-color 160ms, box-shadow 220ms',
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.55)" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
            <circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" />
          </svg>
          <input
            ref={inputRef}
            value={q}
            onChange={e => setQ(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            placeholder="Search products…"
            style={{
              flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none',
              color: '#fff', fontFamily: 'Poppins, sans-serif', fontWeight: 500, fontSize: 18, letterSpacing: '-0.01em',
            }}
          />
          {q && (
            <button onClick={() => { setQ(''); inputRef.current && inputRef.current.focus(); }} aria-label="Clear" style={{
              background: 'rgba(255,255,255,0.08)', border: 'none', cursor: 'pointer',
              width: 22, height: 22, borderRadius: '50%', color: 'rgba(255,255,255,0.7)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, flexShrink: 0,
            }}>✕</button>
          )}
          <span style={{ width: 1, height: 22, background: 'rgba(255,255,255,0.12)', flexShrink: 0 }} />
          <button onClick={onClose} aria-label="Close search" style={{
            background: 'transparent', border: 'none', color: 'rgba(255,255,255,0.7)',
            fontFamily: 'Poppins', fontWeight: 800, fontSize: 18, cursor: 'pointer', flexShrink: 0, lineHeight: 1,
          }}>✕</button>
        </div>

        {/* Result count */}
        <div style={{
          fontFamily: 'Poppins', fontWeight: 600, fontSize: 11, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)', margin: '24px 4px 12px',
        }}>
          {results.length} {results.length === 1 ? 'result' : 'results'}
        </div>

        {/* Results */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {results.map(p => <SearchResult key={p.id} p={p} onOpen={onOpen} onClose={onClose} />)}
          {results.length === 0 && (
            <div style={{
              fontFamily: 'Poppins', fontSize: 15, color: 'rgba(255,255,255,0.5)', padding: '22px 8px',
            }}>
              Nothing matches “{q}”. Try another word.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function SearchResult({ p, onOpen, onClose }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={() => { onOpen(p); onClose(); }}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 14, width: '100%', textAlign: 'left',
        background: hover ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.02)',
        border: `1px solid ${hover ? 'rgba(247,89,31,0.45)' : 'rgba(255,255,255,0.07)'}`,
        borderRadius: 14, padding: '12px 14px', cursor: 'pointer',
        transform: hover ? 'translateX(3px)' : 'translateX(0)',
        transition: 'background 150ms, border-color 150ms, transform 200ms cubic-bezier(0.16,1,0.3,1)',
      }}>
      <div style={{
        width: 52, height: 52, flexShrink: 0, borderRadius: 11, overflow: 'hidden',
        background: p.bg || '#141414', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {p.img ? (
          <img src={p.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <img src={p.logo} alt="" style={{ width: '58%', filter: p.invert ? 'brightness(0) invert(1)' : 'none' }} />
        )}
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: 'Poppins, sans-serif', fontWeight: 700, fontSize: 14.5, letterSpacing: '0.01em',
          color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{p.name}</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 12, color: 'rgba(255,255,255,0.5)', marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {p.sub}
        </div>
      </div>

      <div style={{ flexShrink: 0, textAlign: 'right' }}>
        {p.byRequest ? (
          <span style={{ fontFamily: 'Poppins', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#F7591F' }}>Sold out</span>
        ) : (
          <span style={{ fontFamily: 'JetBrains Mono', fontSize: 14, fontWeight: 700, color: '#fff' }}>${p.price}</span>
        )}
      </div>

      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={hover ? '#F7591F' : 'rgba(255,255,255,0.3)'} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, transition: 'stroke 150ms' }} aria-hidden="true">
        <path d="M9 6l6 6-6 6" />
      </svg>
    </button>
  );
}

window.SearchOverlay = SearchOverlay;
