import { invoke } from '@tauri-apps/api/core'; import { create } from 'zustand'; export type AmbientSound = 'none' | 'rain' | 'cafe' | 'white_noise'; interface AudioStatus { available: boolean; playing: boolean; sound: AmbientSound | null; volume: number; } interface AudioStore { available: boolean; playing: boolean; sound: AmbientSound; volume: number; fetchStatus: () => Promise; setSound: (sound: AmbientSound) => Promise; setVolume: (volume: number) => Promise; } function normalizeSound(sound: AudioStatus['sound'], playing: boolean): AmbientSound { if (!playing || sound === null) { return 'none'; } return sound; } export const useAudioStore = create((set, get) => ({ available: true, playing: false, sound: 'none', volume: 0.5, fetchStatus: async () => { try { const status = await invoke('get_audio_status'); set({ available: status.available, playing: status.playing, sound: normalizeSound(status.sound, status.playing), volume: status.volume, }); } catch (error) { console.error('get_audio_status error:', error); set({ available: false, playing: false, sound: 'none' }); } }, setSound: async (sound) => { try { if (sound === 'none') { await invoke('stop_ambient'); await get().fetchStatus(); return; } await invoke('play_ambient', { sound }); await get().fetchStatus(); } catch (error) { console.error('play_ambient error:', error); await get().fetchStatus(); } }, setVolume: async (volume) => { const nextVolume = Math.min(1, Math.max(0, volume)); set({ volume: nextVolume }); try { await invoke('set_ambient_volume', { volume: nextVolume }); await get().fetchStatus(); } catch (error) { console.error('set_ambient_volume error:', error); await get().fetchStatus(); } }, }));