import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import { translations, type Lang, type Translations } from '../i18n';

const KIT_STORAGE_KEY = 'if_untan_lang';

function readKitLang(): Lang {
  const saved = localStorage.getItem(KIT_STORAGE_KEY);
  if (saved === 'en') return 'en';
  const browser = (navigator.language || 'id').toLowerCase();
  return browser.startsWith('en') ? 'en' : 'id';
}

interface LanguageContextType {
  lang: Lang;
  t: Translations;
  toggleLang: () => void;
}

const LanguageContext = createContext<LanguageContextType | null>(null);

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [lang, setLang] = useState<Lang>(readKitLang);

  // Sync dengan kit's language toggle (tombol ID/EN di navbar)
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent<{ lang: string }>).detail;
      if (detail?.lang === 'en' || detail?.lang === 'id') {
        setLang(detail.lang as Lang);
      }
    };
    document.addEventListener('languageChanged', handler);
    return () => document.removeEventListener('languageChanged', handler);
  }, []);

  const toggleLang = () => setLang((prev) => (prev === 'id' ? 'en' : 'id'));

  return (
    <LanguageContext.Provider value={{ lang, t: translations[lang], toggleLang }}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLang() {
  const ctx = useContext(LanguageContext);
  if (!ctx) throw new Error('useLang must be used within LanguageProvider');
  return ctx;
}
