"use client";

import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";

type SoundContextValue = {
  isMuted: boolean;
  toggleMuted: () => void;
  playSound: (src: string) => void;
};

const SOUND_MUTED_STORAGE_KEY = "mohfarawati-sound-muted";

const SoundContext = createContext<SoundContextValue | null>(null);

export function SoundProvider({ children }: { children: ReactNode }) {
  const [isMuted, setIsMuted] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);

    const storedValue = window.localStorage.getItem(SOUND_MUTED_STORAGE_KEY);

    if (storedValue === "true") {
      setIsMuted(true);
    }
  }, []);

  useEffect(() => {
    if (!mounted) {
      return;
    }

    window.localStorage.setItem(SOUND_MUTED_STORAGE_KEY, String(isMuted));
  }, [isMuted, mounted]);

  const value = useMemo<SoundContextValue>(
    () => ({
      isMuted,
      toggleMuted: () => {
        setIsMuted((currentValue) => !currentValue);
      },
      playSound: (src: string) => {
        if (!mounted || isMuted) {
          return;
        }

        const audio = new Audio(src);
        audio.preload = "auto";
        void audio.play().catch(() => {});
      },
    }),
    [isMuted, mounted],
  );

  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;
}

export function useSound() {
  const context = useContext(SoundContext);

  if (!context) {
    throw new Error("useSound must be used within SoundProvider");
  }

  return context;
}
