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

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 core.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;
}
