'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import HomePage from '../../components/HomePage';

export default function DynamicPage() {
    const params = useParams();
    const router = useRouter();
    const [language, setLanguage] = useState('en');

    useEffect(() => {
        const slug = params.slug as string[];
        let detectedLanguage = 'en';

        // Check if the first segment is a language code
        if (slug && slug.length > 0) {
            const firstSegment = slug[0];
            if (['zh-CN', 'zh-TW'].includes(firstSegment)) {
                detectedLanguage = firstSegment;

                // If it's just the language root (e.g., /zh-CN), show the homepage
                if (slug.length === 1) {
                    setLanguage(detectedLanguage);
                    return;
                }

                // For other pages like /zh-CN/products, redirect to main site with language preference
                localStorage.setItem('preferred-language', detectedLanguage);
                const remainingPath = slug.slice(1).join('/');
                router.replace(`/${remainingPath}`);
                return;
            }
        }

        // Check localStorage for saved preference
        const savedLanguage = localStorage.getItem('preferred-language');
        if (savedLanguage && ['en', 'zh-CN', 'zh-TW'].includes(savedLanguage)) {
            detectedLanguage = savedLanguage;
        }

        setLanguage(detectedLanguage);
    }, [params, router]);

    return <HomePage initialLanguage={language} data-oid="mzpq2zv" />;
}
