"use client";

/**
 * Background music, off by default (task 2.5, PRD §9.1).
 *
 * "Muted by default" is not politeness here, it is the only thing that works: every current
 * mobile browser blocks audio that starts without a gesture, so a track set to autoplay
 * would be silently refused and the guest would never know a toggle existed. Sound starts
 * when the guest asks for it, and only then.
 *
 * Renders nothing at all when the couple has not supplied a track, which is the state the
 * seed data ships in — an audio control that plays silence is worse than no control.
 */
import { useRef, useState } from "react";

import type { Dictionary } from "@/lib/i18n";

export function MusicToggle({
  src,
  dict,
}: {
  src: string | null;
  dict: Dictionary;
}) {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [playing, setPlaying] = useState(false);

  if (!src) return null;

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

    if (playing) {
      audio.pause();
      setPlaying(false);
      return;
    }

    try {
      await audio.play();
      setPlaying(true);
    } catch {
      // Refused by the browser, or the file is missing. Staying on `false` keeps the
      // button honest about what is actually happening.
      setPlaying(false);
    }
  }

  return (
    <>
      {/* preload="none" so a track nobody plays costs nothing on a metered connection. */}
      <audio ref={audioRef} src={src} loop preload="none" />
      <button
        type="button"
        onClick={toggle}
        aria-pressed={playing}
        aria-label={playing ? dict.mute : dict.unmute}
        className="fixed bottom-5 right-5 z-40 flex size-12 items-center justify-center rounded-full border border-stone-300 bg-white/90 text-lg shadow-sm backdrop-blur"
      >
        <span aria-hidden="true">{playing ? "⏸" : "♫"}</span>
      </button>
    </>
  );
}
