/* ============================================================
   PLAYER — full + mini variants (real audio playback)
   ============================================================ */

const TRACKS = [
  { n: 1,  title: "Toulouse",                     time: "3:24", audio: "assets/audio/album/Toulouse, Never let me go.mp3" },
  { n: 2,  title: "Easy, Easy",                   time: "3:18", audio: "assets/audio/album/Easy, Easy.mp3" },
  { n: 3,  title: "Seventeen and Wild",           time: "3:41", audio: "assets/audio/album/Seventeen and Wild.mp3" },
  { n: 4,  title: "Out of the Noise",             time: "3:52", audio: "assets/audio/album/Out of the Noise.mp3" },
  { n: 5,  title: "Your Kiss on \"Take On Me\"",  feat: "feat. Mateo Reed", time: "3:29", audio: "assets/audio/album/Your Kiss on _Take on me_.mp3" },
  { n: 6,  title: "Golden Flame",                 time: "3:47", audio: "assets/audio/album/Golden Flame.mp3" },
  { n: 7,  title: "Come Back Soon",               feat: "feat. Mateo Reed", time: "3:33", audio: "assets/audio/album/Come Back Soon.mp3" },
  { n: 8,  title: "Hands Find the Way",           time: "3:58", audio: "assets/audio/album/Hands Find The Way.mp3" },
  { n: 9,  title: "You Don't See Me",             time: "3:44", audio: "assets/audio/album/You Don't See Me.mp3" },
  { n: 10, title: "Grand Hôtel d'Orléans",        feat: "feat. Mateo Reed", time: "3:51", audio: "assets/audio/album/Grand Hôtel d'Orléans.mp3" },
  { n: 11, title: "Winter is Coming",             time: "3:39", audio: "assets/audio/album/Winter is Coming.mp3" },
  { n: 12, title: "You'll Never Know",            time: "4:02", audio: "assets/audio/album/You'll Never Know.mp3" },
  { n: 13, title: "Fragile Heartbeats",           feat: "feat. Mateo Reed", time: "3:55", audio: "assets/audio/album/Fragile Heartbeats.mp3" },
  { n: 14, title: "Not Artificial",               time: "3:48", audio: "assets/audio/album/Not Artificial.mp3" },
];

const SELECTION = [
  { ...TRACKS[0], album: "My Blue Hours", year: "2026" },
  { ...TRACKS[1], album: "My Blue Hours", year: "2026" },
  { ...TRACKS[5], album: "My Blue Hours", year: "2026" },
  { ...TRACKS[9], album: "My Blue Hours", year: "2026" },
  { ...TRACKS[13], album: "My Blue Hours", year: "2026" },
];

function timeToSec(t) { const [m, s] = t.split(":").map(Number); return m * 60 + s; }
function secToTime(s) {
  s = Math.max(0, Math.floor(s));
  const m = Math.floor(s / 60);
  const r = s % 60;
  return `${m}:${r.toString().padStart(2, "0")}`;
}

function useThemeColors() {
  const [colors, setColors] = React.useState({ wave: "rgba(255,255,255,0.18)", accent: "#d96b3e" });
  React.useEffect(() => {
    const apply = () => {
      const cs = getComputedStyle(document.documentElement);
      setColors({
        wave: cs.getPropertyValue("--line-strong").trim() || "rgba(255,255,255,0.18)",
        accent: cs.getPropertyValue("--copper").trim() || "#d96b3e",
      });
    };
    apply();
    const obs = new MutationObserver(apply);
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
    return () => obs.disconnect();
  }, []);
  return colors;
}

function useAudioPlayer(tracks) {
  const audioRef = React.useRef(null);
  const rafRef = React.useRef(0);
  const [trackIdx, setTrackIdx] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);
  const [elapsed, setElapsed] = React.useState(0);
  const [duration, setDuration] = React.useState(0);

  React.useEffect(() => {
    if (!audioRef.current) audioRef.current = new Audio();
    return () => { if (audioRef.current) { audioRef.current.pause(); audioRef.current.src = ""; } };
  }, []);

  React.useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    const track = tracks[trackIdx];
    if (!track || !track.audio) return;
    audio.src = track.audio;
    audio.load();
    setElapsed(0);
    setDuration(timeToSec(track.time));
    if (playing) audio.play().catch(() => {});
  }, [trackIdx]);

  React.useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    if (playing) {
      audio.play().catch(() => {});
      const tick = () => {
        setElapsed(audio.currentTime);
        if (audio.duration && !isNaN(audio.duration)) setDuration(audio.duration);
        rafRef.current = requestAnimationFrame(tick);
      };
      rafRef.current = requestAnimationFrame(tick);
    } else {
      audio.pause();
      cancelAnimationFrame(rafRef.current);
    }
    return () => cancelAnimationFrame(rafRef.current);
  }, [playing]);

  React.useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    const onEnded = () => {
      const next = (trackIdx + 1) % tracks.length;
      setTrackIdx(next);
      setPlaying(true);
    };
    const onLoaded = () => {
      if (audio.duration && !isNaN(audio.duration)) setDuration(audio.duration);
    };
    audio.addEventListener("ended", onEnded);
    audio.addEventListener("loadedmetadata", onLoaded);
    return () => { audio.removeEventListener("ended", onEnded); audio.removeEventListener("loadedmetadata", onLoaded); };
  }, [trackIdx, tracks.length]);

  const current = tracks[trackIdx];
  const total = duration || timeToSec(current.time);
  const progress = total > 0 ? Math.min(1, elapsed / total) : 0;

  const selectTrack = (i) => { if (i === trackIdx) { setPlaying(p => !p); } else { setTrackIdx(i); setPlaying(true); } };
  const prev = () => { setTrackIdx((trackIdx - 1 + tracks.length) % tracks.length); };
  const next = () => { setTrackIdx((trackIdx + 1) % tracks.length); };
  const togglePlay = () => setPlaying(p => !p);

  return { trackIdx, playing, elapsed, total, progress, current, selectTrack, prev, next, togglePlay };
}

function Waveform({ playing, progress, color, accent, density = 120 }) {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(0);
  const seedRef = React.useRef(Array.from({ length: density }, () => 0.3 + Math.random() * 0.7));

  React.useEffect(() => {
    const cvs = canvasRef.current;
    if (!cvs) return;
    const dpr = window.devicePixelRatio || 1;
    const resize = () => {
      const r = cvs.getBoundingClientRect();
      cvs.width = r.width * dpr;
      cvs.height = r.height * dpr;
    };
    resize();
    window.addEventListener("resize", resize);

    let t = 0;
    const draw = () => {
      const ctx = cvs.getContext("2d");
      const W = cvs.width, H = cvs.height;
      ctx.clearRect(0, 0, W, H);
      const bars = seedRef.current;
      const N = bars.length;
      const barW = W / N * 0.7;
      const gap = W / N * 0.3;
      const cutoff = N * progress;
      for (let i = 0; i < N; i++) {
        const base = bars[i];
        const wobble = playing ? Math.sin((t + i * 0.4) * 0.06) * 0.18 + Math.cos((t + i * 0.7) * 0.13) * 0.12 : 0;
        const amp = Math.min(0.98, Math.max(0.05, base + wobble));
        const h = amp * H * 0.78;
        const x = i * (barW + gap);
        const y = (H - h) / 2;
        ctx.fillStyle = i < cutoff ? accent : color;
        ctx.fillRect(x, y, barW, h);
      }
      t += 1;
      rafRef.current = requestAnimationFrame(draw);
    };
    draw();
    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener("resize", resize);
    };
  }, [playing, progress, color, accent]);

  return <canvas ref={canvasRef} />;
}

/* -------------------- FULL PLAYER (album page) -------------------- */
function Player({ coverSrc, tracks = TRACKS, albumTitle = "My Blue Hours" }) {
  const { trackIdx, playing, elapsed, total, progress, current, selectTrack, prev, next, togglePlay } = useAudioPlayer(tracks);
  const { wave, accent } = useThemeColors();

  return (
    <div className="player">
      <div className="player-left">
        <div className="player-cover" onClick={togglePlay}>
          <img src={coverSrc} alt={albumTitle} />
          <div className="play-overlay"><div className="play-circle">{playing ? "‖" : "▶"}</div></div>
        </div>
        <div>
          <div className="now-playing-label">Now playing — piste {current.n || (trackIdx + 1)} / {tracks.length}</div>
          <div className="now-playing-title">{current.title}</div>
          <div className="now-playing-album">{albumTitle} · Sofia Brainwood</div>
        </div>
        <div className="transport">
          <button className="transport-btn" onClick={prev} aria-label="Précédent">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M6 6h2v12H6zM20 6L9 12l11 6z"/></svg>
          </button>
          <button className="transport-btn primary" onClick={togglePlay} aria-label="Play / Pause">
            {playing
              ? <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>
              : <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M7 5l12 7-12 7z"/></svg>}
          </button>
          <button className="transport-btn" onClick={next} aria-label="Suivant">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M16 6h2v12h-2zM4 18l11-6L4 6z"/></svg>
          </button>
        </div>
      </div>
      <div className="player-right">
        <div className="waveform"><Waveform playing={playing} progress={progress} color={wave} accent={accent} /></div>
        <div className="waveform-meta">
          <span>{secToTime(elapsed)}</span>
          <span>− {secToTime(total - elapsed)}</span>
        </div>
        <div className="tracklist">
          {tracks.map((t, i) => (
            <div key={i} className={"track" + (i === trackIdx ? " active" : "")} onClick={() => selectTrack(i)}>
              <div className="track-num">{i === trackIdx && playing ? <span className="pulse">▶</span> : String(t.n || (i + 1)).padStart(2, "0")}</div>
              <div className="track-title">{t.title}{t.feat && <span className="feat">{t.feat}</span>}</div>
              <div className="track-time">{t.time}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* -------------------- MINI PLAYER (homepage selection) -------------------- */
function MiniPlayer({ tracks = SELECTION }) {
  const { trackIdx, playing, elapsed, total, progress, current, selectTrack, togglePlay } = useAudioPlayer(tracks);
  const { wave, accent } = useThemeColors();

  return (
    <div className="mini-player">
      <div className="mini-player-head">
        <div>
          <div className="block-eyebrow" style={{margin:0}}>Sélection</div>
          <div className="mini-player-title">À écouter maintenant</div>
        </div>
        <button className="mini-player-fab" onClick={togglePlay} aria-label="Play / Pause">
          {playing
            ? <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>
            : <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M7 5l12 7-12 7z"/></svg>}
        </button>
      </div>

      <div className="mini-now">
        <div className="mini-now-info">
          <div className="now-playing-title" style={{fontSize:22}}>{current.title}</div>
          <div className="now-playing-album">{current.album} · {current.year}</div>
        </div>
        <div className="mini-now-time">
          <span>{secToTime(elapsed)}</span>
          <span style={{opacity:0.5}}> / </span>
          <span>{current.time}</span>
        </div>
      </div>

      <div className="mini-wave"><Waveform playing={playing} progress={progress} color={wave} accent={accent} density={60} /></div>

      <div className="mini-tracklist">
        {tracks.map((t, i) => (
          <button
            key={i}
            className={"mini-track" + (i === trackIdx ? " active" : "")}
            onClick={() => selectTrack(i)}
          >
            <span className="mini-track-num">{i === trackIdx && playing ? "▶" : String(i + 1).padStart(2, "0")}</span>
            <span className="mini-track-title">{t.title}</span>
            <span className="mini-track-album">{t.album}</span>
            <span className="mini-track-time">{t.time}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Player, MiniPlayer, TRACKS, SELECTION });
