// Search.jsx — Premium search with backend-honest progress phases.
// Wired to window.cifraClubAPI (api-mock.jsx). Each render-phase reflects a
// real backend stage: Solr query → Vagalume parallel enrichment → results.
// On select, we fetch /acordes (snippet, key, chords_used) before navigating.

const SEARCH_PHASES = [
  { id: 'solr',   label: 'Buscando coincidencias en CifraClub' },
  { id: 'enrich', label: 'Recopilando datos de artistas' },
];

// -- Phase progress checklist -------------------------------------------

function PhaseList({ active, done, sublabels }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {SEARCH_PHASES.map(p => {
        const isDone    = done.includes(p.id);
        const isActive  = active === p.id && !isDone;
        const isPending = !isDone && !isActive;
        return (
          <div key={p.id} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '12px 14px', borderRadius: 14,
            background: isActive
              ? 'linear-gradient(135deg, rgba(180,94,255,0.12), rgba(79,31,203,0.08))'
              : 'rgba(255,255,255,0.03)',
            border: `1px solid ${isActive ? 'rgba(192,132,252,0.4)' : 'rgba(255,255,255,0.06)'}`,
            transition: 'all 0.3s cubic-bezier(0.22, 1, 0.36, 1)',
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: isDone
                ? 'linear-gradient(135deg, #34D399, #059669)'
                : isActive
                  ? 'linear-gradient(135deg, #B45EFF, #7C3AED)'
                  : 'rgba(255,255,255,0.08)',
              boxShadow: isActive ? '0 0 14px rgba(168,85,247,0.5)' : 'none',
              animation: isActive ? 'hlbreathe 1.4s ease-in-out infinite' : 'none',
            }}>
              {isDone && (
                <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
                  <path d="M2 6l3 3 5-6" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
              {isActive && (
                <div style={{
                  width: 8, height: 8, borderRadius: '50%', background: 'white',
                  animation: 'hlpulse 1.2s ease-in-out infinite',
                }} />
              )}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                color: isPending ? 'rgba(255,255,255,0.45)' : '#fff',
                fontSize: 14, fontWeight: 500, letterSpacing: -0.2,
              }}>{p.label}</div>
              {sublabels[p.id] && (
                <div style={{
                  marginTop: 2, fontSize: 11, color: 'rgba(255,255,255,0.45)',
                  fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.2,
                }}>{sublabels[p.id]}</div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// -- Result card --------------------------------------------------------

function ResultCard({ song, isFirst, index, loading, onClick }) {
  // Show pills only when we actually have the data (real backend currently
  // returns just name/slug/artist/genre — duration/bpm come from MusicKit later).
  const meta = [];
  if (song.duration) meta.push(song.duration);
  if (song.bpm)      meta.push(`${song.bpm} BPM`);

  return (
    <button onClick={onClick} disabled={loading} style={{
      width: '100%', textAlign: 'left', border: 'none',
      background: isFirst
        ? 'linear-gradient(135deg, rgba(180,94,255,0.14), rgba(79,31,203,0.06) 65%)'
        : 'rgba(255,255,255,0.04)',
      backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
      borderRadius: 16, padding: '12px 14px',
      display: 'flex', alignItems: 'center', gap: 14,
      marginBottom: 8, marginTop: 0,
      cursor: loading ? 'wait' : 'pointer',
      position: 'relative',
      opacity: loading ? 0.65 : 1,
      boxShadow: isFirst
        ? '0 0 0 1px rgba(192,132,252,0.45), 0 10px 28px rgba(168,85,247,0.16)'
        : '0 0 0 1px rgba(255,255,255,0.06)',
      animation: 'hlfadeUp 0.45s cubic-bezier(0.22, 1, 0.36, 1) backwards',
      animationDelay: `${0.04 + index * 0.05}s`,
      transition: 'opacity 0.2s ease',
    }}>
      {/* Cover with optional top-match star */}
      <div style={{
        width: 52, height: 52, borderRadius: 12, flexShrink: 0,
        position: 'relative',
        background: song.cover?.startsWith('http') ? `url(${song.cover}) center/cover` : song.cover,
        boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.25), 0 4px 12px rgba(0,0,0,0.3)',
      }}>
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, height: '50%',
          borderRadius: '12px 12px 0 0',
          background: 'linear-gradient(180deg, rgba(255,255,255,0.18), transparent)',
          pointerEvents: 'none',
        }} />
        {isFirst && (
          <div title="Mejor coincidencia" style={{
            position: 'absolute', top: -5, right: -5,
            width: 22, height: 22, borderRadius: '50%',
            background: 'linear-gradient(135deg, #FBBF24, #F59E0B)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 4px 12px rgba(251,191,36,0.5), inset 0 1px 0 rgba(255,255,255,0.4)',
            border: '2px solid #0E0726',
          }}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="white">
              <path d="M12 2.6l2.65 6.45 6.95.55-5.3 4.55 1.65 6.85-5.95-3.7-5.95 3.7 1.65-6.85L2.4 9.6l6.95-.55z"/>
            </svg>
          </div>
        )}
      </div>

      {/* Title block */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          color: '#fff', fontSize: 15, fontWeight: 600,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.3, lineHeight: 1.2,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{song.name}</div>
        <div style={{
          marginTop: 3, display: 'flex', alignItems: 'center', gap: 6,
          fontSize: 12, color: 'rgba(255,255,255,0.6)', letterSpacing: -0.1,
          whiteSpace: 'nowrap', overflow: 'hidden',
        }}>
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{song.artist.name}</span>
          {song.genre && (
            <>
              <span style={{ color: 'rgba(255,255,255,0.25)' }}>·</span>
              <span style={{ color: 'rgba(192,132,252,0.85)', fontSize: 11 }}>{song.genre}</span>
            </>
          )}
        </div>
        {meta.length > 0 && (
          <div style={{ marginTop: 6, display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {meta.map(m => (
              <span key={m} style={{
                fontSize: 9, padding: '2px 6px', borderRadius: 4,
                background: 'rgba(255,255,255,0.06)',
                color: 'rgba(255,255,255,0.65)',
                fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.4, fontWeight: 500,
              }}>{m}</span>
            ))}
          </div>
        )}
      </div>

      {/* Chevron */}
      <div style={{
        flexShrink: 0, color: isFirst ? 'rgba(192,132,252,0.85)' : 'rgba(255,255,255,0.3)',
        transition: 'color 0.2s ease',
      }}>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
          <path d="M5 2l5 5-5 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>

      {loading && (
        <div style={{
          position: 'absolute', inset: 0, borderRadius: 16,
          background: 'rgba(14,7,38,0.6)',
          backdropFilter: 'blur(3px)', WebkitBackdropFilter: 'blur(3px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          fontSize: 12, color: '#fff', fontFamily: 'var(--hl-font-ui)', fontWeight: 500,
          letterSpacing: -0.1,
        }}>
          <div style={{
            width: 14, height: 14, borderRadius: '50%',
            border: '2px solid rgba(255,255,255,0.25)',
            borderTopColor: 'var(--hl-accent-light)',
            animation: 'hlspin 0.8s linear infinite',
          }} />
          Cargando letra y acordes…
        </div>
      )}
    </button>
  );
}

function Pill({ children, accent = false }) {
  return (
    <span style={{
      fontSize: 9, padding: '3px 7px', borderRadius: 5,
      background: accent ? 'rgba(168,85,247,0.18)' : 'rgba(255,255,255,0.06)',
      color: accent ? 'var(--hl-accent-light)' : 'rgba(255,255,255,0.7)',
      fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.5, fontWeight: 500,
    }}>{children}</span>
  );
}

// -- SearchScreen --------------------------------------------------------

function SearchScreen({ onBack, onSelect }) {
  const [query, setQuery] = React.useState('');
  // 'idle' | 'searching' | 'results' | 'empty'
  const [phase, setPhase] = React.useState('idle');
  const [results, setResults] = React.useState([]);
  const [activePhase, setActivePhase] = React.useState(null);
  const [donePhases, setDonePhases] = React.useState([]);
  const [sublabels, setSublabels] = React.useState({});
  const [loadingSongId, setLoadingSongId] = React.useState(null);

  const debounceRef = React.useRef(null);
  const reqIdRef = React.useRef(0);  // ignore stale responses on rapid typing

  // Debounced search trigger
  React.useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (query.trim().length < 2) {
      setPhase('idle');
      setResults([]);
      setActivePhase(null); setDonePhases([]); setSublabels({});
      return;
    }
    debounceRef.current = setTimeout(() => runSearch(query), 320);
    return () => clearTimeout(debounceRef.current);
  }, [query]);

  const runSearch = async (q) => {
    const myReq = ++reqIdRef.current;
    setPhase('searching');
    setActivePhase(null); setDonePhases([]); setSublabels({});
    try {
      const res = await window.cifraClubAPI.buscarCanciones(q, {
        onProgress: ({ phase: p, label, done }) => {
          if (reqIdRef.current !== myReq) return;
          if (done) {
            setDonePhases(prev => [...prev, p]);
            setSublabels(prev => ({ ...prev, [p]: label }));
            setActivePhase(null);
          } else {
            setActivePhase(p);
          }
        },
      });
      if (reqIdRef.current !== myReq) return;
      setResults(res);
      setPhase(res.length === 0 ? 'empty' : 'results');
    } catch (e) {
      if (reqIdRef.current !== myReq) return;
      setPhase('empty');
      setResults([]);
    }
  };

  const handleSelect = async (song) => {
    if (loadingSongId) return;
    setLoadingSongId(song.slug);
    try {
      const acordes = await window.cifraClubAPI.obtenerAcordes(
        song.artist.slug, song.slug, 'completo'
      );
      window.cifraClubAPI.addToHistory(song);
      onSelect && onSelect({ ...song, ...acordes });
    } finally {
      setLoadingSongId(null);
    }
  };

  return (
    <div style={{
      height: '100%', background: 'linear-gradient(180deg, #0E0726 0%, #08051A 100%)',
      display: 'flex', flexDirection: 'column', position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: -120, left: -100, width: 380, height: 380,
        borderRadius: '50%', filter: 'blur(100px)', opacity: 0.3, pointerEvents: 'none',
        background: 'radial-gradient(circle, #A855F7, transparent 65%)',
        animation: 'hldrift 18s ease-in-out infinite',
      }} />

      <div style={{ height: 'calc(var(--safe-top, 44px) + 14px)', flexShrink: 0 }} />

      <div className="hl-stagger" style={{ position: 'relative', zIndex: 2, padding: '14px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
          <button type="button" aria-label="Atrás" onClick={onBack} style={{
            width: 38, height: 38, borderRadius: 12,
            background: 'rgba(255,255,255,0.06)',
            backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
            border: '1px solid rgba(255,255,255,0.08)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M9 2L3 7l6 5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          <div style={{
            fontFamily: 'var(--hl-font-display)', fontSize: 28, fontWeight: 300,
            color: '#fff', letterSpacing: -0.8,
          }}>Buscar <span style={{ fontStyle: 'italic', fontWeight: 400 }}>canción</span></div>
        </div>

        <div style={{
          height: 54, borderRadius: 16, position: 'relative',
          background: 'rgba(255,255,255,0.05)',
          backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
          border: '1px solid rgba(192,132,252,0.35)',
          boxShadow: '0 0 0 4px rgba(168,85,247,0.10), inset 0 1px 0 rgba(255,255,255,0.06)',
          display: 'flex', alignItems: 'center', padding: '0 16px', gap: 10,
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <circle cx="7" cy="7" r="5" stroke="rgba(192,132,252,0.85)" strokeWidth="1.8"/>
            <path d="M11 11l3 3" stroke="rgba(192,132,252,0.85)" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
          <input value={query} onChange={e => setQuery(e.target.value)}
            placeholder="Nombre de la canción o artista"
            autoComplete="off" autoCorrect="off" spellCheck={false}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: '#fff', fontSize: 15, fontFamily: 'var(--hl-font-ui)',
              fontWeight: 500, letterSpacing: -0.2,
            }}/>
          {phase === 'searching' && (
            <div style={{
              width: 14, height: 14, borderRadius: '50%',
              border: '2px solid rgba(255,255,255,0.2)',
              borderTopColor: 'var(--hl-accent-light)',
              animation: 'hlspin 0.8s linear infinite',
            }} />
          )}
        </div>

        {phase === 'results' && (
          <div style={{
            marginTop: 12, display: 'flex', alignItems: 'center', gap: 8,
            fontSize: 10, color: 'rgba(255,255,255,0.5)',
            fontFamily: 'var(--hl-font-mono)', letterSpacing: 1.4, textTransform: 'uppercase',
          }}>
            <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#34D399', boxShadow: '0 0 8px #34D399' }} />
            {results.length} resultados · CifraClub · enriquecido con Vagalume
          </div>
        )}
      </div>

      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '12px 16px 24px', position: 'relative', zIndex: 2 }}>
        {phase === 'idle' && (
          <div style={{
            paddingTop: 48, textAlign: 'center',
            color: 'rgba(255,255,255,0.45)',
            animation: 'hlfadeUp 0.5s cubic-bezier(0.22, 1, 0.36, 1)',
          }}>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 22,
              fontStyle: 'italic', fontWeight: 300, color: 'rgba(255,255,255,0.7)',
              letterSpacing: -0.5,
            }}>Empieza a escribir</div>
            <div style={{
              marginTop: 8, fontSize: 13, lineHeight: 1.5, maxWidth: 240,
              margin: '8px auto 0',
            }}>El nombre de la canción, del artista o un fragmento de la letra.</div>
          </div>
        )}

        {phase === 'searching' && (
          <div style={{ padding: '20px 4px 0', animation: 'hlfadeUp 0.4s cubic-bezier(0.22, 1, 0.36, 1)' }}>
            <div style={{
              fontFamily: 'var(--hl-font-mono)', fontSize: 10, letterSpacing: 1.6,
              color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase',
              marginBottom: 14, paddingLeft: 4,
            }}>Buscando "<span style={{ color: 'var(--hl-accent-light)' }}>{query}</span>"</div>
            <PhaseList active={activePhase} done={donePhases} sublabels={sublabels} />
          </div>
        )}

        {phase === 'results' && results.map((r, i) => (
          <ResultCard key={r.slug} song={r} isFirst={i === 0} index={i}
            loading={loadingSongId === r.slug}
            onClick={() => handleSelect(r)} />
        ))}

        {phase === 'empty' && (
          <div style={{
            paddingTop: 40, textAlign: 'center',
            animation: 'hlfadeUp 0.4s cubic-bezier(0.22, 1, 0.36, 1)',
          }}>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 22,
              fontStyle: 'italic', fontWeight: 300, color: 'rgba(255,255,255,0.7)',
              letterSpacing: -0.5,
            }}>Sin resultados</div>
            <div style={{
              marginTop: 8, fontSize: 13, color: 'rgba(255,255,255,0.45)',
              lineHeight: 1.5, maxWidth: 240, margin: '8px auto 0',
            }}>No encontramos coincidencias para "<span style={{ color: 'var(--hl-accent-light)' }}>{query}</span>". Prueba con otro nombre o un fragmento de la letra.</div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SearchScreen });
