import { create } from 'zustand';
import { translations, type LangKey } from '@/lib/translations';

const LANG_STORAGE_KEY = 'scamchecker_lang';

function getStoredLang(): LangKey {
  if (typeof window === 'undefined') return 'en';
  try {
    const stored = localStorage.getItem(LANG_STORAGE_KEY);
    if (stored === 'bn' || stored === 'en') return stored;
  } catch {
    // ignore
  }
  return 'en';
}

interface LangState {
  lang: LangKey;
  setLang: (lang: LangKey) => void;
  toggleLang: () => void;
  t: (key: string) => string;
}

export const useLangStore = create<LangState>((set, get) => ({
  lang: 'en', // default; will hydrate from localStorage on client

  setLang: (lang: LangKey) => {
    try {
      localStorage.setItem(LANG_STORAGE_KEY, lang);
    } catch {
      // ignore
    }
    set({ lang });
  },

  toggleLang: () => {
    const newLang = get().lang === 'en' ? 'bn' : 'en';
    get().setLang(newLang);
  },

  t: (key: string): string => {
    const lang = get().lang;
    return translations[lang]?.[key] || translations['en']?.[key] || key;
  },
}));

/**
 * Hydrate the language store from localStorage.
 * Call this once on the client side (e.g., in a useEffect in the root layout).
 */
export function hydrateLangStore() {
  const stored = getStoredLang();
  if (stored !== useLangStore.getState().lang) {
    useLangStore.setState({ lang: stored });
  }
}
