'use client';

import { createContext, useContext, useState, ReactNode } from 'react';
import { Locale, detectLocale } from '@/lib/i18n';

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

const LocaleContext = createContext<LocaleContextType>({ locale: 'en', setLocale: () => {} });

export function LocaleProvider({ children }: { children: ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>(() => {
    if (typeof window === 'undefined') return 'en';
    const saved = localStorage.getItem('moon-locale') as Locale | null;
    return saved || detectLocale();
  });

  const setLocale = (l: Locale) => {
    setLocaleState(l);
    localStorage.setItem('moon-locale', l);
  };

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      {children}
    </LocaleContext.Provider>
  );
}

export function useLocale() {
  return useContext(LocaleContext);
}
