import { create } from "zustand";

const STORAGE_KEY = "mindavio-sound-settings";

interface SoundSettings {
  soundsEnabled:       boolean;  // master mute
  notificationSounds:  boolean;
  achievementSounds:   boolean;
  taskSounds:          boolean;
  volume:              number;   // 0–1
}

interface SoundStore extends SoundSettings {
  toggleMaster:              () => void;
  toggleNotificationSounds:  () => void;
  toggleAchievementSounds:   () => void;
  toggleTaskSounds:          () => void;
  setVolume:                 (v: number) => void;
}

function loadSettings(): SoundSettings {
  if (typeof window === "undefined") {
    return { soundsEnabled: true, notificationSounds: true, achievementSounds: true, taskSounds: true, volume: 0.8 };
  }
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (!stored) return { soundsEnabled: true, notificationSounds: true, achievementSounds: true, taskSounds: true, volume: 0.8 };
    return { soundsEnabled: true, notificationSounds: true, achievementSounds: true, taskSounds: true, volume: 0.8, ...JSON.parse(stored) };
  } catch {
    return { soundsEnabled: true, notificationSounds: true, achievementSounds: true, taskSounds: true, volume: 0.8 };
  }
}

function persist(state: SoundSettings) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify({
      soundsEnabled:      state.soundsEnabled,
      notificationSounds: state.notificationSounds,
      achievementSounds:  state.achievementSounds,
      taskSounds:         state.taskSounds,
      volume:             state.volume,
    }));
  } catch { /* ignore */ }
}

const initial = loadSettings();

export const useSoundStore = create<SoundStore>((set) => ({
  ...initial,

  toggleMaster: () => set((s) => {
    const next = { ...s, soundsEnabled: !s.soundsEnabled };
    persist(next);
    return next;
  }),

  toggleNotificationSounds: () => set((s) => {
    const next = { ...s, notificationSounds: !s.notificationSounds };
    persist(next);
    return next;
  }),

  toggleAchievementSounds: () => set((s) => {
    const next = { ...s, achievementSounds: !s.achievementSounds };
    persist(next);
    return next;
  }),

  toggleTaskSounds: () => set((s) => {
    const next = { ...s, taskSounds: !s.taskSounds };
    persist(next);
    return next;
  }),

  setVolume: (v) => set((s) => {
    const next = { ...s, volume: Math.max(0, Math.min(1, v)) };
    persist(next);
    return next;
  }),
}));
