import { useCallback, useState } from "react";

interface UseNotificationSoundOptions {
  enabled?: boolean;
  volume?: number;
  soundUrl?: string;
}

export const useNotificationSound = ({
  enabled = true,
  volume = 0.5,
  soundUrl = "/notification.mp3",
}: UseNotificationSoundOptions = {}) => {
  const [isPlaying, setIsPlaying] = useState(false);

  const playSound = useCallback(async () => {
    if (!enabled || isPlaying) {
      return;
    }

    try {
      setIsPlaying(true);

      const audio = new Audio();
      audio.preload = "auto";
      audio.src = soundUrl;
      audio.volume = Math.max(0, Math.min(1, volume));

      // Add event listeners
      audio.addEventListener("ended", () => {
        setIsPlaying(false);
      });

      audio.addEventListener("error", () => {
        setIsPlaying(false);
      });

      // Wait for audio to be ready
      if (audio.readyState >= 2) {
        await audio.play();
      } else {
        audio.addEventListener("canplay", async () => {
          try {
            await audio.play();
          } catch {
            setIsPlaying(false);
          }
        });
      }
    } catch {
      setIsPlaying(false);
    }
  }, [enabled, isPlaying, soundUrl, volume]);

  const stopSound = useCallback(() => {
    setIsPlaying(false);
  }, []);

  return {
    playSound,
    stopSound,
    isPlaying,
  };
};
