import theme from "@/core/utils/theme";
import useLanguage from "@/lib/app/hooks/useLanguage";
import useLoading from "@/lib/app/hooks/useLoading";
import useUser from "@/lib/app/hooks/useUser";
import NextNProgress from "nextjs-progressbar";
import {useEffect} from "react";
import {ToastContainer} from "react-toastify";
import useDirection from "@/lib/app/hooks/useDirection";
import "react-toastify/dist/ReactToastify.css";
import NetworkComponent from "@/core/components/NetworkComponent";
import GlobalHead from "@/core/components/GlobalHead";

function AppLayout({children, isBot}) {
    const {languageIsReady} = useLanguage();
    const {setLoadingPage} = useLoading();
    const {userChangedLanguage, token, isAuth} = useUser();
    const {directionApp} = useDirection();

    useEffect(() => {
        if (languageIsReady) {
            if (token) {
                if (isAuth) {
                    if (userChangedLanguage) {
                        setLoadingPage(true);
                        return;
                    }
                    setLoadingPage(false);
                    return;
                }
                setLoadingPage(true);
                return;
            }
            setLoadingPage(false);
            return;
        }
        setLoadingPage(true);
    }, [languageIsReady, token, isAuth, userChangedLanguage]);

    if (!isBot) {
        if (userChangedLanguage) return;
        if (!languageIsReady) return;
    }

    return (<>
        <GlobalHead/>
        <NextNProgress
            color={theme.palette.secondary.dark}
            options={{showSpinner: false}}
        />
        <ToastContainer position={directionApp === "ltr" ? "top-left" : "top-right"} rtl={directionApp === 'rtl'}/>
        <NetworkComponent/>
        {children}
    </>);
}

export default AppLayout;
