'use client';

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

export interface SpeechPrefs {
  /**
   * BCP-47 tag the user explicitly picked (via `<LanguagePicker>` or
   * programmatically). `null` means "no override" — `useResolvedLanguage`
   * then falls through to the app i18n locale / `navigator.language`.
   * Storing the picker default as `null` is what lets a host's i18n
   * locale take effect when the user never touched the picker.
   */
  language: string | null;
  deviceId: string | null;
  engineId: string | null;
  earcons: boolean;
}

const DEFAULTS: SpeechPrefs = {
  language: null,
  deviceId: null,
  engineId: null,
  earcons: false,
};

interface PrefsStore extends SpeechPrefs {
  setLanguage: (v: string | null) => void;
  setDeviceId: (v: string | null) => void;
  setEngineId: (v: string | null) => void;
  setEarcons: (v: boolean) => void;
  reset: () => void;
}

export const useSpeechPrefs = create<PrefsStore>()(
  persist(
    (set) => ({
      ...DEFAULTS,
      setLanguage: (language) => set({ language }),
      setDeviceId: (deviceId) => set({ deviceId }),
      setEngineId: (engineId) => set({ engineId }),
      setEarcons: (earcons) => set({ earcons }),
      reset: () => set({ ...DEFAULTS }),
    }),
    {
      name: 'djangocfg-stt:prefs',
      storage: createJSONStorage(() =>
        typeof window === 'undefined'
          ? (undefined as unknown as Storage)
          : window.localStorage,
      ),
    },
  ),
);
