// LyricsModal.jsx — iOS-style bottom sheet for previewing lyrics with formato toggle.
//
// Backed by GET /acordes/:artista/:cancion?formato=letra|acordes|completo.
// User's last-used formato is persisted to localStorage so the toggle remembers.
// Cache hits are visualized via a brief "caché" pill so the user understands
// no new request was made.
//
// SECURITY NOTE: Real impl receives HTML from CifraClub scrape (with <b> chord
// markers). Sanitize with DOMPurify before injecting via dangerouslySetInnerHTML.
// Prototype renders sanitized plain text only.

const FORMATO_KEY = 'lavid:lastFormato';
const FORMATOS = [
  { id: 'letra',    label: 'Letra' },
  { id: 'completo', label: 'Letra + Acordes' },
  { id: 'acordes',  label: 'Solo acordes' },
];

function loadLastFormato() {
  try { return localStorage.getItem(FORMATO_KEY) || 'completo'; }
  catch { return 'completo'; }
}
function saveLastFormato(f) {
  try { localStorage.setItem(FORMATO_KEY, f); } catch {}
}

// Strip tags for prototype rendering. Real impl: DOMPurify with allowed list <b>.
function stripTags(html) {
  return (html || '').replace(/<[^>]+>/g, '').trim();
}

function LyricsModal({ song, isOpen, onClose, onEdit }) {
  const [formato, setFormato] = React.useState(loadLastFormato());
  const [acordes, setAcordes] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [fromCache, setFromCache] = React.useState(false);
  const [mountVisible, setMountVisible] = React.useState(false);

  React.useEffect(() => {
    if (isOpen) {
      requestAnimationFrame(() => requestAnimationFrame(() => setMountVisible(true)));
    } else {
      setMountVisible(false);
    }
  }, [isOpen]);

  React.useEffect(() => {
    if (!isOpen || !song) return;
    let stale = false;
    setLoading(true);
    const before = window.cifraClubAPI.getCacheStats?.();
    window.cifraClubAPI.obtenerAcordes(song.artist.slug, song.slug, formato)
      .then(d => {
        if (stale) return;
        const after = window.cifraClubAPI.getCacheStats?.();
        setFromCache(before && after && after.hits > before.hits);
        setAcordes(d);
        setLoading(false);
      });
    return () => { stale = true; };
  }, [isOpen, song?.slug, song?.artist?.slug, formato]);

  const handleFormatoChange = (id) => {
    setFormato(id);
    saveLastFormato(id);
  };

  if (!isOpen || !song) return null;

  const ease = 'cubic-bezier(0.22, 1, 0.36, 1)';

  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 50,
        background: mountVisible ? 'rgba(4,2,14,0.65)' : 'rgba(4,2,14,0)',
        backdropFilter: mountVisible ? 'blur(6px)' : 'blur(0)',
        WebkitBackdropFilter: mountVisible ? 'blur(6px)' : 'blur(0)',
        transition: `background 0.32s ${ease}, backdrop-filter 0.32s ${ease}`,
      }} />

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 51,
        height: '88%', borderTopLeftRadius: 28, borderTopRightRadius: 28,
        background: 'linear-gradient(180deg, #150A30 0%, #0A0520 100%)',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.6), 0 -1px 0 rgba(255,255,255,0.08) inset',
        display: 'flex', flexDirection: 'column',
        transform: mountVisible ? 'translateY(0)' : 'translateY(100%)',
        transition: `transform 0.42s ${ease}`,
        overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 10, paddingBottom: 4 }}>
          <div style={{ width: 38, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.18)' }} />
        </div>

        <div style={{
          padding: '12px 22px 14px',
          borderBottom: '1px solid rgba(255,255,255,0.06)',
          display: 'flex', alignItems: 'flex-start', gap: 12,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 22, fontWeight: 400,
              color: '#fff', letterSpacing: -0.5, lineHeight: 1.1, fontStyle: 'italic',
            }}>{song.name}</div>
            <div style={{
              marginTop: 4, display: 'flex', alignItems: 'center', gap: 8,
              fontSize: 12, color: 'rgba(255,255,255,0.55)', letterSpacing: -0.1,
            }}>
              <span>{song.artist.name}</span>
              {acordes?.key && (
                <>
                  <span style={{ color: 'rgba(255,255,255,0.25)' }}>·</span>
                  <span style={{
                    fontFamily: 'var(--hl-font-mono)', fontSize: 11,
                    color: 'var(--hl-accent-light)', letterSpacing: 0.4,
                  }}>Tono {acordes.key}</span>
                </>
              )}
              {fromCache && !loading && (
                <span style={{
                  marginLeft: 'auto',
                  fontSize: 9, padding: '3px 7px', borderRadius: 5,
                  background: 'rgba(52,211,153,0.18)', color: '#34D399',
                  fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.6,
                  textTransform: 'uppercase', fontWeight: 600,
                }}>caché</span>
              )}
            </div>
          </div>
          <button type="button" aria-label="Cerrar" onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 15,
            background: 'rgba(255,255,255,0.08)', border: 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', color: 'rgba(255,255,255,0.7)', flexShrink: 0,
          }}>
            <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
              <path d="M2 2l8 8M10 2l-8 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
            </svg>
          </button>
        </div>

        <div style={{ padding: '12px 16px 8px' }}>
          <div style={{
            display: 'flex', gap: 4, padding: 4,
            background: 'rgba(255,255,255,0.05)',
            borderRadius: 14, border: '1px solid rgba(255,255,255,0.06)',
          }}>
            {FORMATOS.map(f => (
              <button key={f.id} type="button"
                onClick={() => handleFormatoChange(f.id)}
                style={{
                  flex: 1, padding: '10px 8px', borderRadius: 10,
                  border: 'none', cursor: 'pointer',
                  background: f.id === formato
                    ? 'linear-gradient(135deg, #B45EFF, #4F1FCB)'
                    : 'transparent',
                  color: f.id === formato ? '#fff' : 'rgba(255,255,255,0.6)',
                  fontSize: 12, fontWeight: 600,
                  fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.1,
                  boxShadow: f.id === formato
                    ? '0 6px 18px rgba(168,85,247,0.4), inset 0 1px 0 rgba(255,255,255,0.25)'
                    : 'none',
                  transition: `all 0.22s ${ease}`,
                }}>
                {f.label}
              </button>
            ))}
          </div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '12px 22px 20px', position: 'relative' }}>
          {loading && !acordes && (
            <div style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              height: 240, gap: 14, color: 'rgba(255,255,255,0.5)',
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                border: '2px solid rgba(255,255,255,0.15)',
                borderTopColor: 'var(--hl-accent-light)',
                animation: 'hlspin 0.8s linear infinite',
              }} />
              <div style={{
                fontSize: 12, fontFamily: 'var(--hl-font-mono)',
                letterSpacing: 1.4, textTransform: 'uppercase',
              }}>Cargando…</div>
            </div>
          )}

          {acordes && (
            <div style={{ opacity: loading ? 0.55 : 1, transition: `opacity 0.22s ${ease}` }}>
              <div style={{
                fontSize: 9, color: 'rgba(255,255,255,0.45)',
                textTransform: 'uppercase', letterSpacing: 1.5,
                fontFamily: 'var(--hl-font-mono)', fontWeight: 500,
              }}>Fragmento</div>
              <div style={{
                marginTop: 6, fontSize: 16, lineHeight: 1.55,
                color: '#fff', fontStyle: 'italic',
                fontFamily: 'var(--hl-font-display)', letterSpacing: -0.2,
              }}>"{acordes.snippet}"</div>

              <div style={{ height: 1, background: 'rgba(255,255,255,0.08)', margin: '20px 0' }} />

              {formato === 'acordes' && (
                <>
                  <div style={{
                    fontSize: 9, color: 'rgba(255,255,255,0.45)',
                    textTransform: 'uppercase', letterSpacing: 1.5,
                    fontFamily: 'var(--hl-font-mono)', fontWeight: 500,
                  }}>Acordes utilizados</div>
                  <div style={{ marginTop: 12, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {acordes.chords_used.map(c => (
                      <span key={c} style={{
                        fontFamily: 'var(--hl-font-mono)', fontSize: 14, fontWeight: 600,
                        padding: '8px 12px', borderRadius: 10,
                        background: 'rgba(168,85,247,0.16)', color: 'var(--hl-accent-light)',
                        border: '1px solid rgba(192,132,252,0.3)', letterSpacing: 0.2,
                      }}>{c}</span>
                    ))}
                  </div>
                </>
              )}

              {(formato === 'letra' || formato === 'completo') && (
                <>
                  <div style={{
                    fontSize: 9, color: 'rgba(255,255,255,0.45)',
                    textTransform: 'uppercase', letterSpacing: 1.5,
                    fontFamily: 'var(--hl-font-mono)', fontWeight: 500,
                  }}>{formato === 'letra' ? 'Letra' : 'Letra con acordes'}</div>
                  <pre style={{
                    margin: '14px 0 0', fontSize: 14, lineHeight: 1.75,
                    color: 'rgba(255,255,255,0.88)',
                    fontFamily: 'var(--hl-font-mono)', letterSpacing: 0,
                    whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                  }}>{acordes.htmlPlain || stripTags(acordes.html)}</pre>

                  {formato === 'completo' && acordes.chords_used?.length > 0 && (
                    <div style={{ marginTop: 22 }}>
                      <div style={{
                        fontSize: 9, color: 'rgba(255,255,255,0.45)',
                        textTransform: 'uppercase', letterSpacing: 1.5,
                        fontFamily: 'var(--hl-font-mono)', fontWeight: 500,
                        marginBottom: 10,
                      }}>Acordes</div>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {acordes.chords_used.map(c => (
                          <span key={c} style={{
                            fontFamily: 'var(--hl-font-mono)', fontSize: 12, fontWeight: 600,
                            padding: '4px 8px', borderRadius: 6,
                            background: 'rgba(255,255,255,0.06)',
                            color: 'rgba(255,255,255,0.85)',
                          }}>{c}</span>
                        ))}
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>
          )}
        </div>

        {onEdit && (
          <div style={{
            padding: '12px 22px 18px',
            borderTop: '1px solid rgba(255,255,255,0.06)',
            background: 'linear-gradient(180deg, transparent, rgba(10,5,32,0.95))',
          }}>
            <button type="button" onClick={() => { onClose(); onEdit(); }} style={{
              width: '100%', height: 50, borderRadius: 14, border: 'none',
              background: 'linear-gradient(135deg, #B45EFF, #7C3AED 50%, #4F1FCB)',
              color: '#fff', fontSize: 15, fontWeight: 600,
              fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
              cursor: 'pointer',
              boxShadow: '0 10px 30px rgba(168,85,247,0.4), inset 0 1px 0 rgba(255,255,255,0.25)',
            }}>Editar en pantalla completa</button>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { LyricsModal });
