import { create } from 'zustand';

export type Locale = 'en' | 'de';

const STORAGE_KEY = 'cup26:locale';

function readLocale(): Locale {
  try {
    const v = localStorage.getItem(STORAGE_KEY);
    if (v === 'en' || v === 'de') return v;
  } catch { /* SSR / tests / private mode */ }
  try {
    if (navigator.language?.toLowerCase().startsWith('de')) return 'de';
  } catch { /* no navigator */ }
  return 'en';
}

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

export const useLocaleStore = create<LocaleState>((set) => ({
  locale: readLocale(),
  setLocale: (locale) => {
    try { localStorage.setItem(STORAGE_KEY, locale); } catch { /* private mode */ }
    if (typeof document !== 'undefined') document.documentElement.lang = locale;
    set({ locale });
  },
}));

// keep <html lang> in sync from the start
if (typeof document !== 'undefined') document.documentElement.lang = readLocale();
