// audio.jsx — Player de audio con waveform sintético

const { useState, useEffect, useRef, useMemo } = React;

// Genera un patrón de waveform pseudoaleatorio determinístico por seed
function genWaveform(seed, count = 64) {
  let s = seed;
  const rng = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
  const out = [];
  for (let i = 0; i < count; i++) {
    const env = Math.sin((i / count) * Math.PI) * 0.7 + 0.3;
    const noise = rng() * 0.6 + 0.4;
    out.push(Math.min(1, env * noise + rng() * 0.15));
  }
  return out;
}

function Waveform({ seed = 17, progress = 0, animated = false, onSeek, height = 88, count = 64 }) {
  const bars = useMemo(() => genWaveform(seed, count), [seed, count]);
  const [tick, setTick] = useState(0);
  useEffect(() => {
    if (!animated) return;
    let raf;
    const loop = () => { setTick(t => t + 1); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [animated]);

  return (
    <div className="wave-bars" style={{ height }} onClick={(e) => {
      if (!onSeek) return;
      const rect = e.currentTarget.getBoundingClientRect();
      onSeek((e.clientX - rect.left) / rect.width);
    }}>
      {bars.map((b, i) => {
        const played = i / bars.length < progress;
        const playingHere = animated && Math.abs(i / bars.length - progress) < 0.04;
        const wob = animated ? Math.sin((tick / 8) + i * 0.5) * 0.08 : 0;
        const h = Math.max(6, (b + wob) * height * 0.85);
        return (
          <div
            key={i}
            className={`wave-bar ${played ? 'played' : ''} ${playingHere ? 'playing' : ''}`}
            style={{ height: `${h}px` }}
          />
        );
      })}
    </div>
  );
}

function fmtTime(s) {
  const m = Math.floor(s / 60);
  const sec = Math.floor(s % 60).toString().padStart(2, '0');
  return `${m}:${sec}`;
}

function HeroPlayer() {
  const [playing, setPlaying] = useState(true);
  const [progress, setProgress] = useState(0.32);
  const dur = 154;
  useEffect(() => {
    if (!playing) return;
    const iv = setInterval(() => setProgress(p => (p + 0.003) % 1), 60);
    return () => clearInterval(iv);
  }, [playing]);

  return (
    <div className="wave-card">
      <div className="wave-head">
        <div className="wave-track-info">
          <div className="wave-cover" />
          <div>
            <div className="wave-title">Pa' la Pancha · cumbia</div>
            <div className="wave-sub">SUENA-001 · 40 años</div>
          </div>
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-3)' }}>
          EN VIVO
        </div>
      </div>
      <Waveform seed={17} progress={progress} animated={playing} onSeek={setProgress} />
      <div className="wave-controls">
        <button className="play-btn" onClick={() => setPlaying(p => !p)} aria-label="play">
          {playing ? <Icon.Pause /> : <Icon.Play />}
        </button>
        <span>{fmtTime(progress * dur)}</span>
        <div style={{ flex: 1, height: 2, background: 'var(--line)', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ width: `${progress * 100}%`, height: '100%', background: 'var(--accent)' }} />
        </div>
        <span>{fmtTime(dur)}</span>
      </div>
    </div>
  );
}

function ExampleCard({ ex, isPlaying, onToggle }) {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    if (!isPlaying) return;
    const iv = setInterval(() => setProgress(p => (p + 0.005) % 1), 80);
    return () => clearInterval(iv);
  }, [isPlaying]);
  useEffect(() => { if (!isPlaying) setProgress(0); }, [isPlaying]);

  return (
    <div className={`ex-card ${isPlaying ? 'playing' : ''}`}>
      <div className="ex-cover" style={{ background: ex.gradient }}>
        <div className="play-overlay">
          <button className="play-btn" onClick={onToggle} aria-label="play">
            {isPlaying ? <Icon.Pause /> : <Icon.Play />}
          </button>
        </div>
      </div>
      <div className="ex-genre">{ex.genre}</div>
      <div className="ex-title">{ex.title}</div>
      <div className="ex-meta">{ex.tag} · {ex.duration}</div>
      <Waveform seed={ex.seed} progress={isPlaying ? progress : 0} animated={isPlaying} height={28} count={48} />
    </div>
  );
}

Object.assign(window, { HeroPlayer, ExampleCard, Waveform });
