'use client';

import { useAppSelector } from "@/redux/store"
import { isLoggedIn , mountCheckIfValid } from "@/redux/features/auth-slice";
import { useDispatch } from "react-redux"
import { AppDispatch } from '@/redux/store';
import { useEffect } from "react";
import { useRouter } from 'next/navigation'
import { ReactNode } from 'react' 
import FullScreenLoader from "@/components/common/fullScreenLoader";

//? HOC for no auth pages ( only accept no auth user )
export default function LocaleLayout({children} : { children : ReactNode }) {

    const dispatch = useDispatch<AppDispatch>();
    const isValid = useAppSelector((state) => state.authReducer.value.isValid)
    const checkIfValidMounted = useAppSelector((state) => state.authReducer.value.checkIfValidMounted)

    const authRedirectPage = useAppSelector((state) => state.settingsReducer.value.authRedirectPage)
    
    const router = useRouter()

    // Get redux states
    useEffect(() => { // init isLoggedIn
        if(checkIfValidMounted) return
        dispatch(mountCheckIfValid())
        async function a()
        {
            await dispatch(isLoggedIn({LoggedInCallback}))
        }
        a()
    }, [])

    // if logged in this will fire
    function LoggedInCallback()
    {
        return router.push(authRedirectPage)
    }

    return (
        <>
            {
                !isValid ?
                    <>
                        {children}
                    </>
                :
                <FullScreenLoader />
            }
        </>
    );
}
