"use client";

import { useEffect, useRef, useState } from "react";
import { Music, Volume2, VolumeX } from "lucide-react";
import type { StoryMusic } from "@/lib/types";

/**
 * The track attached to a photo, played over it.
 *
 * Starts muted, because a feed that makes noise on its own is unpleasant —
 * whether it starts muted at all is the admin's choice. Tapping the badge
 * unmutes, and only one post plays at a time.
 */
export function PostMusic({
  music,
  startMuted,
}: {
  music: StoryMusic;
  /** From admin settings: whether music begins muted. */
  startMuted: boolean;
}) {
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [muted, setMuted] = useState(startMuted);
  const [playing, setPlaying] = useState(false);

  // Only one post makes noise at a time.
  useEffect(() => {
    const stopOthers = (e: Event) => {
      if (e.target !== audioRef.current) {
        audioRef.current?.pause();
        setPlaying(false);
      }
    };
    document.addEventListener("play", stopOthers, true);
    return () => document.removeEventListener("play", stopOthers, true);
  }, []);

  function toggle() {
    const audio = audioRef.current;
    if (!audio) return;

    if (muted || !playing) {
      audio.muted = false;
      setMuted(false);
      audio.play().then(() => setPlaying(true)).catch(() => {});
    } else {
      audio.pause();
      setPlaying(false);
      setMuted(true);
    }
  }

  return (
    <button onClick={toggle} className="pm-badge" title={music.trackName}>
      <audio
        ref={audioRef}
        src={music.previewUrl}
        loop
        muted={muted}
        preload="none"
      />

      {music.artworkUrl ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={music.artworkUrl} alt="" className={playing ? "spin" : ""} />
      ) : (
        <Music size={13} />
      )}

      <span className="min-w-0">
        <b>{music.trackName}</b>
        <em>{music.artistName}</em>
      </span>

      {muted || !playing ? <VolumeX size={15} /> : <Volume2 size={15} />}
    </button>
  );
}
