import React, { createContext, useContext, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/tauri';

interface SoundContextType {
  playSound: (sound: string) => void;
  setEnabled: (enabled: boolean) => void;
}

const SoundContext = createContext<SoundContextType | undefined>(undefined);

export function SoundProvider({ children }: { children: React.ReactNode }) {
  const [enabled, setEnabled] = React.useState(true);

  const playSound = useCallback(async (sound: string) => {
    if (!enabled) return;
    try {
      await invoke('play_sound', { sound });
    } catch (error) {
      console.error('Failed to play sound:', error);
    }
  }, [enabled]);

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

export function useSound() {
  const context = React.useContext(SoundContext);
  if (!context) {
    throw new Error('useSound must be used within SoundProvider');
  }
  return context;
}
