import { create } from 'zustand';
import { soundEffects } from '@/lib/sound-effects/engine';

const ENABLED_KEY = 'llink:soundEffects-enabled';
const DEFAULT_ENABLED = true;

function loadEnabled(): boolean {
  try {
    const v = localStorage.getItem(ENABLED_KEY);
    return v === null ? DEFAULT_ENABLED : v === 'true';
  } catch {
    return DEFAULT_ENABLED;
  }
}

interface SoundEffectsState {
  enabled: boolean;
  setEnabled: (enabled: boolean) => void;
}

export const useSoundEffectsStore = create<SoundEffectsState>((set) => {
  const initialEnabled = loadEnabled();

  // Sync engine with persisted state on first load. Master volume is a fixed
  // tuning constant in the engine — no UI control.
  soundEffects.setOptions({ enabled: initialEnabled });

  return {
    enabled: initialEnabled,
    setEnabled: (enabled) => {
      set({ enabled });
      soundEffects.setOptions({ enabled });
      try {
        localStorage.setItem(ENABLED_KEY, String(enabled));
      } catch {
        // storage unavailable
      }
    },
  };
});
