import { create } from "zustand";
import { persist } from "zustand/middleware";
import { DEFAULT_SOUND_ID, type SoundId } from "@/lib/notifications/sounds";

/**
 * Per-device notification preferences. Stored in localStorage (NOT server-side):
 * browser notification permission, sound choice, and volume are all bound to the
 * specific device/browser, so they should never be shared across a café's devices.
 */
export interface NotifPrefs {
  /** Play a sound when a new notification arrives. */
  soundEnabled: boolean;
  soundId: SoundId;
  /** 0..1 */
  volume: number;
  /** Show a native OS/Windows popup when the dashboard tab is in the background. */
  desktopEnabled: boolean;
  /** Show the unread count on the browser tab (title + favicon badge). */
  tabBadgeEnabled: boolean;
  /** Show an in-app toast when a new notification arrives. */
  toastEnabled: boolean;
}

interface NotifPrefsState extends NotifPrefs {
  /** True once Zustand has finished rehydrating from localStorage. */
  _hasHydrated: boolean;
  setPrefs: (partial: Partial<NotifPrefs>) => void;
  _setHasHydrated: (v: boolean) => void;
}

export const DEFAULT_NOTIF_PREFS: NotifPrefs = {
  soundEnabled: true,
  soundId: DEFAULT_SOUND_ID,
  volume: 0.7,
  desktopEnabled: false, // opt-in: requires an explicit permission grant
  tabBadgeEnabled: true,
  toastEnabled: true,
};

export const useNotifPrefs = create<NotifPrefsState>()(
  persist(
    (set) => ({
      ...DEFAULT_NOTIF_PREFS,
      _hasHydrated: false,
      setPrefs: (partial) => set(partial),
      _setHasHydrated: (v) => set({ _hasHydrated: v }),
    }),
    {
      name: "meezi_notif_prefs",
      partialize: (s): NotifPrefs => ({
        soundEnabled: s.soundEnabled,
        soundId: s.soundId,
        volume: s.volume,
        desktopEnabled: s.desktopEnabled,
        tabBadgeEnabled: s.tabBadgeEnabled,
        toastEnabled: s.toastEnabled,
      }),
      onRehydrateStorage: () => (state) => {
        state?._setHasHydrated(true);
      },
    }
  )
);
