import { usePage } from '@inertiajs/react';
import { Fragment, useEffect, type PropsWithChildren } from 'react';

type PagePropsWithLocale = {
    locale: string;
};

/**
 * Remounts children when the active locale changes so layouts and memoized
 * UI pick up the new `i18n` payload without a manual hard refresh.
 * Must render inside an Inertia page/layout (uses `usePage`).
 */
export function LocaleRoot({ children }: PropsWithChildren) {
    const { locale } = usePage<PagePropsWithLocale>().props;

    useEffect(() => {
        document.documentElement.lang = locale;
    }, [locale]);

    return <Fragment key={locale}>{children}</Fragment>;
}
