if (typeof global === 'undefined') {
    window.global = window;
}
  
import React, { useEffect, useRef } from "react";
import { usePage, router } from "@inertiajs/react";
import Header from "@user/Header";
import Footer from "@user/Footer";

const UserLayout = ({ children }) => {
    const { url } = usePage();
    const isFirstRender = useRef(true);

    // Close menu on navigation
    useEffect(() => {
        const body = document.body;
        const menuToggle = document.querySelector('.site-menu-toggle');
        const siteNavbar = document.querySelector('.js-site-navbar');
        
        if (body.classList.contains('menu-open')) {
            body.classList.remove('menu-open');
            if (menuToggle) menuToggle.classList.remove('open');
            if (siteNavbar) siteNavbar.style.display = 'none';
        }

        // Scroll to top on navigation (skip first render)
        if (!isFirstRender.current) {
            window.scrollTo(0, 0);
        }
        isFirstRender.current = false;
    }, [url]);

    // Reinitialize plugins on navigation
    useEffect(() => {
        const timer = setTimeout(() => {
            if (typeof window !== 'undefined' && typeof window.initializeMainPlugins === 'function') {
                window.initializeMainPlugins();
            }
        }, 150);

        return () => clearTimeout(timer);
    }, [url]);

    // Show preloader on navigation start
    useEffect(() => {
        const handleNavigationStart = () => {
            const preloader = document.getElementById('preloder');
            if (preloader) {
                preloader.style.display = 'flex';
            }
        };

        const removeStart = router.on('start', handleNavigationStart);

        return () => {
            removeStart();
        };
    }, []);

    return (
        <div translate="yes">
            <Header />
            {children}
            <Footer />
        </div>
    );
};

export default UserLayout;
