/**
 * useTranslation Hook
 * 提供翻译功能和语言切换
 */

import { useState, useEffect } from 'react';
import { getCurrentLocale, setCurrentLocale, defaultLocale, type Locale } from '@/lib/i18n';
import { getTranslations, type TranslationKeys } from '@/locales';

export function useTranslation() {
  // 使用 defaultLocale 作为初始值，避免 hydration mismatch
  const [locale, setLocale] = useState<Locale>(defaultLocale);
  const [t, setT] = useState<TranslationKeys>(getTranslations(defaultLocale));

  useEffect(() => {
    const syncLocale = (nextLocale?: Locale) => {
      const currentLocale = nextLocale ?? getCurrentLocale();
      setLocale(currentLocale);
      setT(getTranslations(currentLocale));
    };

    syncLocale();

    const handleLocaleChange = (event: Event) => {
      const customEvent = event as CustomEvent<Locale>;
      syncLocale(customEvent.detail);
    };

    const handleStorage = (event: StorageEvent) => {
      if (event.key === 'locale') {
        syncLocale((event.newValue as Locale) || undefined);
      }
    };

    window.addEventListener('ffoa-locale-change', handleLocaleChange as EventListener);
    window.addEventListener('storage', handleStorage);

    return () => {
      window.removeEventListener('ffoa-locale-change', handleLocaleChange as EventListener);
      window.removeEventListener('storage', handleStorage);
    };
  }, []);

  // 同步 <html lang>，让浏览器原生输入（date / number 等）按当前 locale 渲染
  useEffect(() => {
    if (typeof document !== 'undefined') {
      document.documentElement.lang = locale === 'en' ? 'en' : 'zh-CN';
    }
  }, [locale]);

  const changeLocale = (newLocale: Locale) => {
    setCurrentLocale(newLocale);
    setLocale(newLocale);
    setT(getTranslations(newLocale));
  };

  return {
    t,
    locale,
    changeLocale,
  };
}

// 简化版本 - 用于简单翻译
export function useT() {
  const { t } = useTranslation();
  return t;
}
