'use client';

import { NextIntlClientProvider } from 'next-intl';
import { createContext, useContext, useState, ReactNode } from 'react';
import zhMessages from '@/locales/zh';
import enMessages from '@/locales/en';

type Locale = 'zh' | 'en';

const messages: Record<Locale, any> = {
  zh: zhMessages,
  en: enMessages,
};

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

const LocaleContext = createContext<LocaleContextType | undefined>(undefined);

export function useLocale() {
  const context = useContext(LocaleContext);
  if (!context) {
    throw new Error('useLocale must be used within IntlProvider');
  }
  return context;
}

interface IntlProviderProps {
  children: ReactNode;
}

export function IntlProvider({ children }: IntlProviderProps) {
  const [locale, setLocale] = useState<Locale>('zh');

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      <NextIntlClientProvider
        locale={locale}
        messages={messages[locale]}
        timeZone="Asia/Shanghai"
      >
        {children}
      </NextIntlClientProvider>
    </LocaleContext.Provider>
  );
}
