/**
 * Context para gerenciar idioma/localização
 */

'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Locale, defaultLocale, supportedLocales, translations } from '@/lib/i18n/config';

interface LocaleContextType {
    locale: Locale;
    setLocale: (locale: Locale) => void;
    t: (key: string, params?: Record<string, string | number>) => string;
}

/** Exportado para testes (fallback em `jest.setup` quando não há provider). */
export const LocaleContext = createContext<LocaleContextType | undefined>(undefined);

export function LocaleProvider({ children }: { children: ReactNode }) {
    const [locale, setLocaleState] = useState<Locale>(defaultLocale);

    // Carregar preferência salva na inicialização
    useEffect(() => {
        if (typeof window !== 'undefined') {
            const savedLocale = localStorage.getItem('locale') as Locale;
            if (savedLocale && supportedLocales.includes(savedLocale)) {
                setLocaleState(savedLocale);
            }
        }
    }, []);

    const setLocale = (newLocale: Locale) => {
        setLocaleState(newLocale);
        if (typeof window !== 'undefined') {
            localStorage.setItem('locale', newLocale);
            // Atualizar atributo lang do HTML
            document.documentElement.lang = newLocale;
        }
    };

    const t = (key: string, params?: Record<string, string | number>): string => {
        let translation = translations[locale][key] || key;

        // Substituir parâmetros
        if (params) {
            Object.entries(params).forEach(([param, value]) => {
                translation = translation.replace(`{{${param}}}`, String(value));
            });
        }

        return translation;
    };

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

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