import { useEffect } from 'react';
import { usePage } from '@inertiajs/react';

export function useTranslation() {
    const { translations = {}, locale = 'en', isRtl = false } = usePage().props;

    // Control HTML layout direction (RTL/LTR)
    useEffect(() => {
        const isAdmin = window.location.pathname.startsWith('/cp');
        if (isAdmin) {
            document.documentElement.dir = 'ltr';
            document.documentElement.lang = 'en';
        } else {
            document.documentElement.dir = isRtl ? 'rtl' : 'ltr';
            document.documentElement.lang = locale;
        }
    }, [locale, isRtl]);

    // The Translation Function
    const t = (key, replacements = null) => {
        // 1. If in admin panel, ignore translations (keep English)
        if (typeof window !== 'undefined' && window.location.pathname.startsWith('/cp')) {
            return key; 
        }

        // 2. Find the translation in the JSON object, or fallback to the English key
        let translation = translations[key] !== undefined ? translations[key] : key;

        // 3. Replace dynamic variables (e.g., :name, :order)
        if (replacements && typeof replacements === 'object') {
            Object.keys(replacements).forEach(placeholder => {
                translation = String(translation).replace(`:${placeholder}`, replacements[placeholder]);
            });
        }

        return translation;
    };

    return { t, locale, isRtl };
}