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

export type SupportedLocale = 'en' | 'zh';

interface LocaleState {
  locale: SupportedLocale;
  setLocale: (locale: SupportedLocale) => void;
}

export const useLocaleStore = create<LocaleState>()(
  persist(
    (set) => ({
      locale: 'en',
      setLocale: (locale) => {
        import('@/i18n/config').then(({ default: i18n }) => {
          i18n.changeLanguage(locale);
        });
        if (typeof document !== 'undefined') {
          document.documentElement.lang = locale;
        }
        set({ locale });
      },
    }),
    { name: 'it0-locale' },
  ),
);

// Sync i18next with persisted locale on app load.
// Called once from providers.tsx after i18n/config is initialized.
export function syncLocaleOnLoad() {
  const { locale } = useLocaleStore.getState();
  if (locale && typeof document !== 'undefined') {
    import('@/i18n/config').then(({ default: i18n }) => {
      i18n.changeLanguage(locale);
    });
    document.documentElement.lang = locale;
  }
}
