import { create } from 'zustand';
import pt from './pt';
import en from './en';

type Lang = 'pt' | 'en';

const LANGS: Record<Lang, Record<string, string>> = { pt, en };

function detectLang(): Lang {
  const saved = localStorage.getItem('lang') as Lang | null;
  if (saved && LANGS[saved]) return saved;
  return navigator.language.startsWith('pt') ? 'pt' : 'en';
}

interface I18nState {
  lang: Lang;
  setLang: (lang: Lang) => void;
  t: (key: string) => string;
}

export const useI18n = create<I18nState>((set, get) => ({
  lang: detectLang(),
  setLang: (lang: Lang) => {
    localStorage.setItem('lang', lang);
    set({ lang });
  },
  t: (key: string) => {
    const { lang } = get();
    return LANGS[lang]?.[key] ?? LANGS.pt[key] ?? key;
  },
}));
