
/**
 * SearchBar — unified Spotify search component used across all pages.
 *
 * ⚠️  Reused identically on:
 *   - Homepage (Hero)
 *   - Services page (bottom CTA)
 *   - Results page (bottom CTA)
 *
 * Do not fork — configure via props (placeholder, caption, onSelect).
 */

function SearchSkeletonRow() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '12px 24px' }}>
      <div style={{ width: '40px', height: '40px', borderRadius: '8px', background: 'rgba(255,255,255,0.06)', flexShrink: 0, animation: 'skeletonPulse 1.4s ease-in-out infinite' }} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <div style={{ height: '12px', borderRadius: '4px', background: 'rgba(255,255,255,0.06)', width: '60%', animation: 'skeletonPulse 1.4s ease-in-out infinite' }} />
        <div style={{ height: '10px', borderRadius: '4px', background: 'rgba(255,255,255,0.04)', width: '40%', animation: 'skeletonPulse 1.4s ease-in-out infinite 0.2s' }} />
      </div>
    </div>
  );
}

function SearchBar({
  onSelect,
  placeholder = 'Search the track you want to promote',
  mobilePlaceholder = 'Search a track or artist',
  ariaLabel = 'Search Spotify',
}) {
  const w = useWindowWidth();
  const mobile = w < 768;
  const [query, setQuery] = React.useState('');
  const [results, setResults] = React.useState([]);
  const [status, setStatus] = React.useState('idle'); // idle | loading | empty | error
  const [open, setOpen] = React.useState(false);
  const [focused, setFocused] = React.useState(false);
  const [activeIdx, setActiveIdx] = React.useState(-1);
  const timerRef = React.useRef(null);

  React.useEffect(() => {
    clearTimeout(timerRef.current);
    if (query.trim().length < 2) { setResults([]); setOpen(false); setStatus('idle'); return; }
    setStatus('loading'); setOpen(true); setResults([]);
    timerRef.current = setTimeout(async () => {
      try {
        const data = await SpotifyAPI.search(query.trim());
        if (data.length === 0) { setStatus('empty'); } else { setResults(data); setStatus('idle'); }
        setActiveIdx(-1);
      } catch (e) {
        setStatus('error'); setResults([]);
      }
    }, 300);
    return () => clearTimeout(timerRef.current);
  }, [query]);

  function handleKey(e) {
    if (!open) return;
    if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIdx(i => Math.min(i + 1, results.length - 1)); }
    if (e.key === 'ArrowUp')   { e.preventDefault(); setActiveIdx(i => Math.max(i - 1, 0)); }
    if (e.key === 'Enter' && activeIdx >= 0) { pick(results[activeIdx]); }
    if (e.key === 'Escape') setOpen(false);
  }

  function pick(item) {
    if (onSelect) onSelect(item);
    setOpen(false); setQuery('');
  }

  const showDropdown = open && (status === 'loading' || status === 'empty' || status === 'error' || results.length > 0);

  return (
    <div style={{ position: 'relative', width: '100%', maxWidth: mobile ? '100%' : '660px', margin: '0 auto' }}>
      {/* Ambient glow behind the bar */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        width: '130%', height: '300%',
        background: 'radial-gradient(ellipse 55% 55% at 50% 50%, rgba(201,76,255,0.13) 0%, rgba(94,43,255,0.07) 40%, transparent 70%)',
        pointerEvents: 'none', zIndex: 0,
      }} />

      <div style={{
        position: 'relative', zIndex: 1,
        display: 'flex', alignItems: 'center',
        background: focused ? 'rgba(11,11,18,0.98)' : 'rgba(11,11,18,0.72)',
        border: `1px solid ${focused ? 'rgba(94,43,255,0.6)' : 'rgba(255,255,255,0.08)'}`,
        borderRadius: showDropdown ? '18px 18px 0 0' : '18px',
        boxShadow: focused
          ? '0 0 0 4px rgba(94,43,255,0.12), 0 0 48px rgba(201,76,255,0.1)'
          : '0 8px 40px rgba(0,0,0,0.4)',
        transition: 'all 350ms cubic-bezier(0.16,1,0.3,1)',
        backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
        height: mobile ? '60px' : '68px', padding: mobile ? '0 16px' : '0 24px',
        transform: focused ? 'scale(1.008)' : 'scale(1)',
      }}>
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style={{ flexShrink: 0 }}>
          <circle cx="8" cy="8" r="5.5" stroke={focused ? '#C94CFF' : '#7C7C90'} strokeWidth="1.5" style={{ transition: 'stroke 300ms' }}/>
          <path d="M12.5 12.5L16 16" stroke={focused ? '#C94CFF' : '#7C7C90'} strokeWidth="1.5" strokeLinecap="round" style={{ transition: 'stroke 300ms' }}/>
        </svg>
        <input
          aria-label={ariaLabel}
          value={query}
          onChange={e => setQuery(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => { setTimeout(() => { setFocused(false); setOpen(false); }, 220); }}
          onKeyDown={handleKey}
          placeholder={mobile ? mobilePlaceholder : placeholder}
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: '#F5F2FF', fontSize: mobile ? '15px' : '16px',
            padding: '0 12px', fontFamily: 'inherit', letterSpacing: '-0.01em',
          }}
        />
        {status === 'loading'
          ? <div style={{ width: '18px', height: '18px', border: '2px solid rgba(201,76,255,0.3)', borderTopColor: '#C94CFF', borderRadius: '50%', animation: 'spin 0.7s linear infinite', flexShrink: 0 }} />
          : !mobile && (
            <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)', borderRadius: '7px', padding: '3px 7px', flexShrink: 0 }}>
              <span style={{ color: '#7C7C90', fontSize: '11px', fontFamily: "'JetBrains Mono', monospace" }}>⌘K</span>
            </div>
          )
        }
      </div>

      {showDropdown && (
        <div style={{
          position: 'absolute', left: 0, right: 0, zIndex: 50,
          background: 'rgba(11,11,18,0.99)', backdropFilter: 'blur(24px)', WebkitBackdropFilter: 'blur(24px)',
          border: '1px solid rgba(255,255,255,0.06)', borderTop: 'none',
          borderRadius: '0 0 18px 18px', overflow: 'hidden',
          boxShadow: '0 32px 80px rgba(0,0,0,0.7)',
        }}>
          {status === 'loading' && [0,1,2].map(i => <SearchSkeletonRow key={i} />)}
          {status === 'empty' && (
            <div style={{ padding: '20px 24px', color: '#7C7C90', fontSize: '13px', letterSpacing: '-0.01em' }}>
              Nothing found. Try another search.
            </div>
          )}
          {status === 'error' && (
            <div style={{ padding: '20px 24px', color: '#7C7C90', fontSize: '13px', letterSpacing: '-0.01em' }}>
              Search temporarily unavailable.
            </div>
          )}
          {results.map((item, i) => (
            <div key={`${item.kind}-${item.id}`}
              onMouseDown={() => pick(item)}
              style={{
                display: 'flex', alignItems: 'center', gap: '14px',
                padding: mobile ? '10px 16px' : '10px 24px',
                cursor: 'pointer',
                background: i === activeIdx ? 'rgba(94,43,255,0.1)' : 'transparent',
                borderTop: i > 0 ? '1px solid rgba(255,255,255,0.04)' : 'none',
                transition: 'background 150ms',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(94,43,255,0.08)'}
              onMouseLeave={e => e.currentTarget.style.background = i === activeIdx ? 'rgba(94,43,255,0.1)' : 'transparent'}
            >
              {item.artworkSmall
                ? <img src={item.artworkSmall} alt="" style={{
                    width: '40px', height: '40px',
                    borderRadius: item.kind === 'artist' ? '50%' : '6px',
                    objectFit: 'cover', flexShrink: 0,
                  }} />
                : <div style={{
                    width: '40px', height: '40px',
                    borderRadius: item.kind === 'artist' ? '50%' : '6px',
                    background: 'linear-gradient(135deg, rgba(94,43,255,0.4), rgba(201,76,255,0.2))',
                    flexShrink: 0,
                  }} />
              }
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ color: '#F5F2FF', fontSize: '14px', fontWeight: 700, letterSpacing: '-0.02em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.name}</div>
                <div style={{ color: '#7C7C90', fontSize: '12px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {item.kind === 'artist' ? 'Artist' : item.allArtists}
                </div>
              </div>
              <span style={{
                color: '#C94CFF', fontSize: '10px', fontFamily: "'JetBrains Mono', monospace",
                flexShrink: 0, letterSpacing: '0.08em', textTransform: 'uppercase',
                background: 'rgba(201,76,255,0.08)',
                border: '1px solid rgba(201,76,255,0.15)',
                padding: '3px 8px', borderRadius: '6px',
              }}>{item.kind}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { SearchBar });
