// Reusable bits — placeholders, icons, helpers

const Placeholder = ({ label }) => (
  <div className="placeholder">
    <span>{label || "image"}</span>
  </div>
);

const PlayIcon = () => (
  <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M7 5v14l12-7L7 5z" />
  </svg>
);
const PauseIcon = () => (
  <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <rect x="6" y="5" width="4" height="14" />
    <rect x="14" y="5" width="4" height="14" />
  </svg>
);

const ArrowRight = () => (
  <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
    <path d="M5 12h14M13 6l6 6-6 6" />
  </svg>
);
const ArrowLeft = () => (
  <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
    <path d="M19 12H5M11 18l-6-6 6-6" />
  </svg>
);

// "Custom" Suno-aware audio player.
// If a real audioSrc is provided, uses HTML5 audio.
// Otherwise simulates playback (visual only) and links out to Suno.
function SunoPlayer({ song }) {
  const [playing, setPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(0); // 0..1
  const [current, setCurrent] = React.useState(0); // seconds
  const audioRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const startTsRef = React.useRef(null);
  const baseRef = React.useRef(0);

  // Total seconds — parse "3:42" or default
  const total = React.useMemo(() => {
    if (!song.duration) return 222;
    const [m, s] = song.duration.split(":").map(Number);
    return m * 60 + (s || 0);
  }, [song.duration]);

  // simulated progress when no audio file
  React.useEffect(() => {
    if (!playing || song.audioSrc) return;
    const tick = (ts) => {
      if (startTsRef.current == null) startTsRef.current = ts;
      const elapsed = baseRef.current + (ts - startTsRef.current) / 1000;
      if (elapsed >= total) {
        setCurrent(total); setProgress(1);
        setPlaying(false);
        baseRef.current = 0;
        startTsRef.current = null;
        return;
      }
      setCurrent(elapsed);
      setProgress(elapsed / total);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(rafRef.current);
      if (startTsRef.current != null) {
        baseRef.current += (performance.now() - startTsRef.current) / 1000;
      }
      startTsRef.current = null;
    };
  }, [playing, total, song.audioSrc]);

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

  const toggle = () => {
    if (song.audioSrc && audioRef.current) {
      if (playing) audioRef.current.pause();
      else audioRef.current.play();
    }
    setPlaying((p) => !p);
  };

  const onSeek = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
    setProgress(ratio);
    setCurrent(ratio * total);
    baseRef.current = ratio * total;
    startTsRef.current = null;
    if (audioRef.current) audioRef.current.currentTime = ratio * total;
  };

  return (
    <div className="player" role="group" aria-label={`Аудио плейър за ${song.title}`}>
      {song.audioSrc && (
        <audio
          ref={audioRef}
          src={song.audioSrc}
          onTimeUpdate={(e) => {
            setCurrent(e.target.currentTime);
            setProgress(e.target.currentTime / (e.target.duration || total));
          }}
          onEnded={() => setPlaying(false)}
        />
      )}
      <button className="play-btn" onClick={toggle} aria-label={playing ? "Пауза" : "Пусни"}>
        {playing ? <PauseIcon /> : <PlayIcon />}
      </button>
      <div className="progress" onClick={onSeek}>
        <div className="progress-fill" style={{ width: `${progress * 100}%` }} />
        <div className="progress-knob" style={{ left: `${progress * 100}%` }} />
      </div>
      <div className="time">{fmt(current)} / {fmt(total)}</div>
      <a
        className="source"
        href={song.sunoUrl}
        target="_blank"
        rel="noopener noreferrer"
        title="Слушай в Suno"
      >Suno ↗</a>
    </div>
  );
}

Object.assign(window, { Placeholder, PlayIcon, PauseIcon, ArrowRight, ArrowLeft, SunoPlayer });
