// History.jsx — Per-user history of recently opened songs.
//
// Reads from window.cifraClubAPI.getHistory() (localStorage today, Postgres
// `user_history` in production). Each row is { id, song, accessedAt }.
// Tap → onSelect(song): no /canciones request needed, /acordes is cache-hit.

function relativeTime(ts) {
  const diff = Date.now() - ts;
  const min = Math.floor(diff / 60000);
  if (min < 1)   return 'Ahora';
  if (min < 60)  return `Hace ${min} min`;
  const h = Math.floor(min / 60);
  if (h < 24)    return `Hace ${h} h`;
  const d = Math.floor(h / 24);
  if (d < 7)     return `Hace ${d} d`;
  return new Date(ts).toLocaleDateString('es-ES', { day: 'numeric', month: 'short' });
}

function HistoryScreen({ onBack, onSelect }) {
  const [entries, setEntries] = React.useState(() => window.cifraClubAPI?.getHistory?.() || []);
  const [filter, setFilter] = React.useState('');
  const [confirmClear, setConfirmClear] = React.useState(false);

  const filtered = React.useMemo(() => {
    const q = filter.trim().toLowerCase();
    if (!q) return entries;
    return entries.filter(e =>
      e.song.name.toLowerCase().includes(q) ||
      e.song.artist.name.toLowerCase().includes(q)
    );
  }, [entries, filter]);

  const handleClear = () => {
    if (!confirmClear) { setConfirmClear(true); setTimeout(() => setConfirmClear(false), 3000); return; }
    window.cifraClubAPI.clearHistory();
    setEntries([]);
    setConfirmClear(false);
  };

  return (
    <div style={{
      height: '100%', position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(180deg, #0E0726 0%, #08051A 50%, #04020E 100%)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        position: 'absolute', top: -130, left: -100, width: 360, height: 360,
        borderRadius: '50%', filter: 'blur(110px)', 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: 16 }}>
          <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,
          }}>Tu <span style={{ fontStyle: 'italic', fontWeight: 400 }}>historial</span></div>
        </div>

        {entries.length > 0 && (
          <div style={{
            height: 46, borderRadius: 14, position: 'relative',
            background: 'rgba(255,255,255,0.04)',
            border: '1px solid rgba(255,255,255,0.06)',
            display: 'flex', alignItems: 'center', padding: '0 14px', gap: 8,
          }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <circle cx="7" cy="7" r="5" stroke="rgba(255,255,255,0.4)" strokeWidth="1.6"/>
              <path d="M11 11l3 3" stroke="rgba(255,255,255,0.4)" strokeWidth="1.6" strokeLinecap="round"/>
            </svg>
            <input value={filter} onChange={e => setFilter(e.target.value)}
              placeholder="Filtrar tu historial"
              style={{
                flex: 1, background: 'transparent', border: 'none', outline: 'none',
                color: '#fff', fontSize: 14, fontFamily: 'var(--hl-font-ui)',
                fontWeight: 500, letterSpacing: -0.2,
              }} />
          </div>
        )}

        {entries.length > 0 && (
          <div style={{
            marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontSize: 10, color: 'rgba(255,255,255,0.45)',
            fontFamily: 'var(--hl-font-mono)', letterSpacing: 1.4, textTransform: 'uppercase',
          }}>
            <span>{filtered.length} de {entries.length}</span>
            <button type="button" onClick={handleClear} style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              color: confirmClear ? '#FB7185' : 'rgba(255,255,255,0.45)',
              fontSize: 10, fontFamily: 'var(--hl-font-mono)',
              letterSpacing: 1.4, textTransform: 'uppercase', fontWeight: 600,
              padding: 0, transition: 'color 0.2s ease',
            }}>{confirmClear ? '¿Confirmas?' : 'Limpiar'}</button>
          </div>
        )}
      </div>

      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: 'calc(12px) 16px calc(28px + var(--safe-bottom, 16px))', position: 'relative', zIndex: 2 }}>
        {entries.length === 0 ? (
          <div style={{
            paddingTop: 60, textAlign: 'center',
            animation: 'hlfadeUp 0.4s cubic-bezier(0.22, 1, 0.36, 1)',
          }}>
            <div style={{
              width: 64, height: 64, borderRadius: '50%',
              margin: '0 auto 18px',
              background: 'rgba(255,255,255,0.04)',
              border: '1px solid rgba(255,255,255,0.08)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                stroke="rgba(255,255,255,0.4)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="9"/>
                <polyline points="12 7 12 12 15 14"/>
              </svg>
            </div>
            <div style={{
              fontFamily: 'var(--hl-font-display)', fontSize: 22,
              fontStyle: 'italic', fontWeight: 300, color: 'rgba(255,255,255,0.7)',
              letterSpacing: -0.5,
            }}>Sin historial todavía</div>
            <div style={{
              marginTop: 8, fontSize: 13, color: 'rgba(255,255,255,0.45)',
              lineHeight: 1.5, maxWidth: 240, margin: '8px auto 0',
            }}>Las canciones que abras aparecerán aquí para acceso instantáneo.</div>
          </div>
        ) : filtered.length === 0 ? (
          <div style={{
            paddingTop: 60, textAlign: 'center',
            color: 'rgba(255,255,255,0.45)', fontSize: 13,
          }}>
            Sin coincidencias en tu historial.
          </div>
        ) : (
          filtered.map((e, i) => (
            <button key={e.id} onClick={() => onSelect && onSelect(e.song)} style={{
              width: '100%', textAlign: 'left',
              border: '1px solid rgba(255,255,255,0.06)',
              background: 'rgba(255,255,255,0.04)',
              backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
              borderRadius: 16, padding: 12,
              display: 'flex', gap: 12, marginBottom: 8,
              cursor: 'pointer',
              animation: 'hlfadeUp 0.4s cubic-bezier(0.22, 1, 0.36, 1) backwards',
              animationDelay: `${0.04 + i * 0.04}s`,
            }}>
              <div style={{
                width: 48, height: 48, borderRadius: 10, flexShrink: 0,
                background: e.song.cover?.startsWith('http')
                  ? `url(${e.song.cover}) center/cover` : e.song.cover,
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.25), 0 4px 14px rgba(0,0,0,0.3)',
              }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  color: '#fff', fontSize: 14, fontWeight: 600,
                  fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.3,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                }}>{e.song.name}</div>
                <div style={{
                  color: 'rgba(255,255,255,0.55)', fontSize: 12, marginTop: 2,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                }}>{e.song.artist.name}</div>
                <div style={{
                  marginTop: 4, fontSize: 10, color: 'rgba(255,255,255,0.4)',
                  fontFamily: 'var(--hl-font-mono)', letterSpacing: 0.4,
                  textTransform: 'uppercase',
                }}>{relativeTime(e.accessedAt)}</div>
              </div>
              <div style={{
                display: 'flex', alignItems: 'center',
                color: 'rgba(192,132,252,0.6)',
              }}>
                <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>
            </button>
          ))
        )}
      </div>
    </div>
  );
}

Object.assign(window, { HistoryScreen });
