'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { locales, defaultLocale } from '../lib/i18n';

export default function RootPage() {
    const router = useRouter();

    useEffect(() => {
        // Get user's preferred language from the browser
        const userLang = navigator.language;

        // Find a matching supported language
        let targetLang = defaultLocale;
        const matchedFullLang = locales.find((lang) => lang === userLang);
        if (matchedFullLang) {
            targetLang = matchedFullLang;
        } else {
            const baseLang = userLang.split('-')[0];
            const matchedBaseLang = locales.find((lang) => lang.startsWith(baseLang));
            if (matchedBaseLang) {
                targetLang = matchedBaseLang;
            }
        }

        // Redirect to the appropriate language-specific page
        router.replace(`/${targetLang}`);
    }, [router]);

    return (
        <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
            backgroundColor: '#111827',
            color: 'white',
            fontFamily: 'sans-serif'
        }}>
            <p>Redirecting to your preferred language...</p>
        </div>
    );
}
