"use client";

import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  type ReactNode,
} from "react";
import { playSound, type SoundName } from "@/lib/sounds";
import { useLocalStorage } from "@/hooks/use-local-storage";

type SoundContextValue = {
  enabled: boolean;
  toggle: () => void;
  play: (name: SoundName) => void;
};

const SoundContext = createContext<SoundContextValue>({
  enabled: false,
  toggle: () => {},
  play: () => {},
});

const STORAGE_KEY = "entscheidomat-sound";

export function SoundProvider({ children }: { children: ReactNode }) {
  const [enabled, setEnabled] = useLocalStorage(STORAGE_KEY, true);

  const toggle = useCallback(() => {
    setEnabled((prev) => !prev);
  }, [setEnabled]);

  const play = useCallback(
    (name: SoundName) => {
      if (enabled) playSound(name);
    },
    [enabled],
  );

  const value = useMemo(
    () => ({ enabled, toggle, play }),
    [enabled, toggle, play],
  );

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

export function useSound() {
  return useContext(SoundContext);
}
