
// GA
import ReactGA from 'react-ga4';

// utils
import React, { lazy, Suspense, useCallback, useState } from 'react';

// styles
import ThemeStyles from '@styles/theme';
import './style.scss';

// libs styles
import 'react-toastify/dist/ReactToastify.min.css';
import 'react-grid-layout/css/styles.css';
import 'swiper/css';
import 'swiper/css/effect-fade';
import 'swiper/css/pagination';

// fonts
import '@fonts/icomoon/icomoon.woff';
// import '@fonts/swisscbt/SWISSC-BT.ttf'

// contexts
import { SidebarProvider, useSidebar } from '@contexts/sidebarContext';
import { WithdrawMissionProvider } from '@contexts/withdrawMissionContext';
import { ThemeProvider } from 'styled-components';

// hooks
import { useThemeProvider } from '@contexts/themeContext';
import { useEffect, useRef } from 'react';
import { useWindowSize } from 'react-use';
import useAuthRoute from '@hooks/useAuthRoute';

// utils
import { StyleSheetManager } from 'styled-components';
import { ThemeProvider as MuiThemeProvider, createTheme } from '@mui/material/styles';
import {
    checkIsStandalone,
    checkTimestampIsNextDay,
    getBrazilTimeStamp,
    getUrlParam,
    localStorageGet,
    localStorageRemove,
    localStorageSet,
    preventDefault,
    updateShareUrl
} from '@utils/helpers';
import rtlPlugin from 'stylis-plugin-rtl';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
// components
import { BrowserRouter, HashRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import Layout from "@layout/Layout";
import {
    getBFP,
    getFetchStatus,
    getHallServerUrl, getKickState, getOpenPay, getPromoteInstall, getPopWheel,
    getUserID,
    getUserInfo,
    isLogined,
    updateCurrGame, updateOpenPay, getIsGuest, getPopBindPhone, getPopFirst,
    getUserRegisted,
    getFreeWithdraw,
    getIsBindPhone,
    getUserVip, getPopPwaBonus
} from '@features/mainSlice';
import { useDispatch, useSelector } from "react-redux";
import { REQ_STATUS } from "@api/config";
import {
    reqAgentCheck, reqBankruptcyGift, reqCheckinCheck,
    reqCustomService, reqFavoGet, reqFirstPayConfig, reqFirstPayGift, reqFreeWithdraw, reqFreeWithdrawMission, reqGameActivity, reqGameInfo,
    reqGetRoutes,
    reqHolidaysActInfo,
    reqHolidaysGiftInfo,
    reqMailCheck, reqProtectCheck,
    reqRechargeConfig,
    reqRedpackCheck, reqRedpackConfig,
    reqTurnplateIndex,
    reqWithdrawBaseInfo
} from "@features/api";
import LoadingScreen from "@components/LoadingScreen";
import DropCoins from "@components/DropCoins";
import { getFirstPayGift, getFirstPayMulti, getPayFinishFlag, reqPayConfig, resetPayFinishFlag } from "@features/paySlice";
import { connectHall, disconnectHall, hallSendState } from "@features/actions/hallClient";
import { toast } from "react-toastify";
import { useBlocker } from "react-router";
import FontFaceObserver from 'fontfaceobserver';
import { getTurnplate } from "@features/turnplateSlice";
import {
    LOCAL_ACTIVITY_C,
    LOCAL_BIND_TIPS_TS,
    LOCAL_CHECKIN_GAME_TS,
    LOCAL_CHECKIN_LAUNCH_TS,
    LOCAL_DOWNLOAD_PROMPT_TS,
    LOCAL_HOLIDAYS_GAME_TS,
    LOCAL_HOLIDAYS_LAUNCH_TS,
    LOCAL_PDD_TIPS_TS,
    LOCAL_SIGN,
    LOCAL_USER_NEW,
    LOCAL_VISTOR_ID,
    LOCAL_WHEEL_INVITE_CODE,
    LOCAL_WITHDRAW_TIP_TS,
    LOCAL_HOLIDAYS_ACT_GAME_TS
} from "@constants/localkey";

import LoadingFull from "@components/Loading/LoadingFull";
import { ClickAwayListener } from "@mui/base/ClickAwayListener";
import useGlobalClick from "@hooks/useGlobalClick";
import SoundHelp from "@utils/SoundManger";
import { ROUTE_PATH } from "@constants/routes";
import { onChangeUser, onChangeUserID } from "@features/actions/mainAction";
import {checkBrowserNotSupport, isInAppBrowser, isShowInstallBox, isTWA, openUrlUseChrome} from "@utils/UAUtils";
import WInstallBox from "@widgets/WInstallBox";
import WMaintainBox from "@widgets/WMaintainBox";
import WAreaSelect from "@widgets/WAreaSelect";
import WDownBox from "@widgets/WInstallBox/WDownBox";
import WShortcutGuide from "@widgets/WInstallBox/WShortcutGuide";
import store from 'app/store';
import usePaymentActions from '@hooks/usePaymentActions';
import { getIsCanCheckIn } from '@features/checkInSlice';
import WBrowserNotSupport from "@widgets/WBrowserNotSupport";
const objInfo = {
    gameID: 0
};
const App = () => {
    const dispatch = useDispatch();
    const fetchStatus = useSelector(getFetchStatus);
    const userInfo = useSelector(getUserInfo);
    const userID = useSelector(getUserID);
    const registed = useSelector(getUserRegisted);
    const turnplate = useSelector(getTurnplate);
    const isBindPhone = useSelector(getIsBindPhone);
    const freeWithdraw = useSelector(getFreeWithdraw);
    const isCanCheckIn = useSelector(getIsCanCheckIn);
    const payFinishFlag = useSelector(getPayFinishFlag);
    const turnplateRef = useRef(turnplate);
    const isBindPhoneRef = useRef(isBindPhone);
    const freeWithdrawRef = useRef(freeWithdraw);
    const isCanCheckInRef = useRef(isCanCheckIn);
    useEffect(() => { turnplateRef.current = turnplate; }, [turnplate]);
    useEffect(() => { isBindPhoneRef.current = isBindPhone; }, [isBindPhone]);
    useEffect(() => { freeWithdrawRef.current = freeWithdraw; }, [freeWithdraw]);
    useEffect(() => { isCanCheckInRef.current = isCanCheckIn; }, [isCanCheckIn]);

    const appRef = useRef(null);
    const { theme, direction, setIsShowWheel, preLocation, gameID } = useThemeProvider();
    const { pathname, search, hash } = useLocation();
    const gaKey = process.env.REACT_APP_PUBLIC_GA;
    gaKey && ReactGA.initialize(gaKey);
    const navigate = useNavigate();
    // auto RTL support for Material-UI components and styled-components

    const plugins = direction === 'rtl' ? [rtlPlugin] : [];
    const hallServerUrl = useSelector(getHallServerUrl);
    useGlobalClick();
    // const {preLocation,gameID}=usePreviousRoute();
    const serverKick = useSelector(getKickState);
    const promoteInstall = useSelector(getPromoteInstall);
    const popWheel = useSelector(getPopWheel);
    const openPay = useSelector(getOpenPay);
    const guest = useSelector(getIsGuest);
    const vip = useSelector(getUserVip);
    const popBindPhone = useSelector(getPopBindPhone);
    const [isMaintain, setIsMaintain] = useState(false);
    //是否唤起选择area
    const [isSelectArea, setIsSelectArea] = useState(false);
    const { checkFirstPayGift } = usePaymentActions();
    const popPwaBonus=useSelector(getPopPwaBonus);

    const muiTheme = createTheme({
        direction: direction,
    });

    const cacheRtl = createCache({
        key: 'css-rtl',
        stylisPlugins: plugins,
    });
    const startReqRoutes = () => {
        //先请求指纹id
        dispatch(getBFP()).then((result) => {
            dispatch(reqGetRoutes());
        });
    };
    const loadFont = () => {
        // let swisscbt=new FontFaceObserver("SWISSC-BT");
        // swisscbt.load().then(() => {
        //
        // })
        let timeout = 3000;
        // new FontFaceObserver("SWISSC-BT").load(null,timeout).catch(e=>{
        //     // console.log(e);
        // });
        // new FontFaceObserver("Roboto").load(null,timeout).catch(e=>{
        //     // console.log(e);
        // });
        // new FontFaceObserver("Roboto-1").load(null,timeout).catch(e=>{
        //     // console.log(e);
        // });
    };

    // useEffect(() => {
    //     // console.error("reload user", window.location.pathname);
    //     // 页面加载时，如果 URL 不是根路径，则强制重置
    //     // if (window.location.pathname !== "/") {
    //     window.history.replaceState(null, "", "/"); // 静默替换 URL
    //     navigate("/"); // 跳转到首页（可选）
    //     // }
    // }, []);
    //检查邀请码
    const checkInviteCode = () => {
        let name = "act";
        let code = getUrlParam(name);
        if (code != null) {
            localStorageSet(LOCAL_WHEEL_INVITE_CODE, code);
        }
        else {
            localStorageSet(LOCAL_WHEEL_INVITE_CODE, "");
        }
        let cname = "c";
        let ccode = getUrlParam(cname);
        if (ccode != null) {
            localStorageSet(LOCAL_ACTIVITY_C, ccode);
        }
        // else{
        //     localStorageSet(LOCAL_ACTIVITY_C,"");
        // }
        let bfp = getUrlParam("bfp");
        if (bfp != null && bfp !== "") {
            localStorageSet(LOCAL_VISTOR_ID, bfp);
            global.BFP = bfp;
        }
        global.checkUrlvars();
    };
    const checkAdjustParams = () => {
        // let params = {
        //     pxid: getUrlParam("pxid"),
        //     fbclid: getUrlParam("fbclid"),
        //     ad_id: getUrlParam("ad_id"),
        //     adset_id: getUrlParam("adset_id"),
        //     campaign_id: getUrlParam("campaign_id"),
        //     pixel: getUrlParam("pixel")
        // };

        // // 登录后检查c参数 如果用户已绑定了c 跟url参数中的不一致 则重新导航到

        // console.log(`>>>>>>>> adjust params:${JSON.stringify(params)}`);

    };
    const reProgressierInstallBanner = () => {
        if (window.NewProgressierInstallBanner != null) return;
        let ProgressierInstallBanner = window.ProgressierInstallBanner;
        window.NewProgressierInstallBanner = ProgressierInstallBanner;
        window.ProgressierInstallBanner = function (e, t) {
            this.remove = async function () {

            };
            this.render = async function () {

            };
            this.make = function () {

            };
            this.init = async function () {

            };
        };
    };
    const reqInitData = async () => {
        //未初始化
        if (userID === -1) return;
        //fb浏览器暂停继续
        if (checkBrowserNotSupport())return;
        //onChangeUser
        dispatch(onChangeUser(userInfo));
        if (userID > 0) {
            dispatch(connectHall(hallServerUrl));
            // localStorageSet(LOCAL_WHEEL_INVITE_CODE, "");
            // localStorageSet(LOCAL_ACTIVITY_C,"");
            //Mail红点屏蔽
            await Promise.all([
                dispatch(reqCheckinCheck()),
                dispatch(reqBankruptcyGift()),
                dispatch(reqRechargeConfig()),
                dispatch(reqFirstPayGift()).unwrap(),
                dispatch(reqMailCheck()).unwrap(),
                dispatch(reqFavoGet()).unwrap(),
                dispatch(reqTurnplateIndex()).unwrap(),
                dispatch(reqFreeWithdraw()).unwrap(),
                dispatch(reqFreeWithdrawMission()).unwrap(),
                dispatch(reqHolidaysGiftInfo()).unwrap(),
                dispatch(reqHolidaysActInfo()).unwrap(),
            ]);
            // console.error("reqTurnplateIndex after", turnplate);
            // const latestTurnplate = store.getState().turnplate.turnplate;
            // console.error("强制获取最新状态:", latestTurnplate);
            launchPopupflows();
            //setPopupFlow();
            //checkOpenBindPrompt();
        }
        else {
            checkNewUserPrompt();
            dispatch(disconnectHall());
        }
        //pay
        // reqPayConfig(dispatch,userInfo);
        // dispatch(reqFirstPayConfig(userID))
        //customer
        // dispatch(reqCustomService());
        //turnplate
        // dispatch(reqTurnplateIndex());
        //redpack
        // dispatch(reqRedpackCheck());
        // dispatch(reqRedpackConfig());
        //agent
        // dispatch(reqAgentCheck());
        //activity
        // dispatch(reqGameActivity());
    };
    const appInitData = () => {
        // scroll to top on route change
        //检查是否维护
        if (checkMaintain()) return;
        if (checkAreaSelect()) return;
        checkInviteCode();
        checkAdjustParams();
        // checkOpenInChrome();
        loadFont();
        //请求routes
        startReqRoutes();
        appRef.current && appRef.current.scrollTo(0, 0);
        preventDefault();
        reProgressierInstallBanner();
        SoundHelp.loadAllAudioFile();
        // preventTouchMove();
    };
    const checkFirstPayPopup = () => {
        if (!checkFirstPayGift()) return false;
        if (vip > 0) return false;
        const { pathname, hash } = window.location;
        if (pathname === "/") {
            if (hash == null || hash === "") {
                global.showFirstPay();
                return true;
            }
        }
    };
    const checkFreeWithdraw = () => {
        const freeWithdraw = freeWithdrawRef.current;
        if (freeWithdraw != null && freeWithdraw.state === 2) {
            global.showFirstCashoutTips();
            return true;
        }
        return false;
    };
    const checkPddWheel = () => {
        // console.error("checkPddWheel", turnplate);
        //手动取最新数据
        // const latestTurnplate = store.getState().turnplate.turnplate;
        // if (latestTurnplate == null || latestTurnplate.times <= 0) return;
        // const latestTurnplate = turnplateRef.current;
        // if (latestTurnplate == null || latestTurnplate.times <= 0) return;
        if (!checkTimestampIsNextDay(LOCAL_PDD_TIPS_TS)) return false;
        localStorageSet(LOCAL_PDD_TIPS_TS, Date.now());
        setIsShowWheel(true);

        // global.showPddWheel();
        return true;
    };
    const checkLaunchHolidaysGift = () => {
        // let paying = localStorageGet("payHolidaysGift", false);
        // if (paying && JSON.parse(paying)) {
        //     localStorageRemove("payHolidaysGift");
        // } else {
        //     if (!checkTimestampIsNextDay(LOCAL_HOLIDAYS_LAUNCH_TS)) return false;
        //     localStorageSet(LOCAL_HOLIDAYS_LAUNCH_TS, Date.now());
        // }

        global.showHolidaysGift();
        return true;
    };

    const checkGameBackHolidaysGift = () => {
        // let paying = localStorageGet("payHolidaysGift", false);
        // if (paying && JSON.parse(paying)) {
        //     localStorageRemove("payHolidaysGift");
        // } else {
        //     if (!checkTimestampIsNextDay(LOCAL_HOLIDAYS_GAME_TS)) return false;
        //     localStorageSet(LOCAL_HOLIDAYS_GAME_TS, Date.now());
        // }
        global.showHolidaysGift();
        return true;
    };

    const checkLaunchHolidaysAct = () => {
        let paying = localStorageGet("payHolidaysAct", false);
        if (paying && JSON.parse(paying)) {
            localStorageRemove("payHolidaysAct");
        } else {
            if (!checkTimestampIsNextDay(LOCAL_HOLIDAYS_ACT_GAME_TS)) return false;
            localStorageSet(LOCAL_HOLIDAYS_ACT_GAME_TS, Date.now());
        }

        global.showHolidaysAct();
        return true;
    };

    const checkGameBackHolidaysAct = () => {
        global.showHolidaysAct();
        return true;
    };

    const checkOpenCheckin = () => {
        if (userID > 0) {
            if (pathname === "/") {
                if (hash == null || hash === "") {
                    // let key = "checkin_open_time";
                    // let now = Date.now();
                    // let lst = Number(localStorageGet(key, 0));
                    // let delta = now - lst;
                    // if (delta < 86400000) {
                    //     return false;
                    // }
                    dispatch(reqCheckinCheck((isCanCheckIn) => {
                        let is_check_first = true;
                        if (hash == null || hash === "") {
                            if (isCanCheckIn === 1) {
                                // navigate(ROUTE_PATH.CHECK_IN, { replace: true });
                                global.showCheckIn();
                                // localStorageSet(key, Date.now());
                                // is_check_first = false;
                            } else {
                                global.openNextPopup();
                            }
                        }
                    }));
                    return true;
                }
            }
        }
        return false;
    };

    const onCheckCheckInPopup = (key) => {
        if (vip <= 0) return false;
        if (!checkTimestampIsNextDay(key)) return false;
        localStorageSet(key, Date.now());
        global.showCheckIn();
        return true;
    };

    const checkLaunchCheckin = () => {
        return onCheckCheckInPopup(LOCAL_CHECKIN_LAUNCH_TS);
    };
    const checkGameBackCheckin = () => {
        return onCheckCheckInPopup(LOCAL_CHECKIN_GAME_TS);
    };
    const checkHomeWithdrawTips = () => {
        if (!checkTimestampIsNextDay(LOCAL_WITHDRAW_TIP_TS)) return false;
        const freeWithdraw = freeWithdrawRef.current;
        //console.error("freeWithdraw:", freeWithdraw);
        if (freeWithdraw != null && (freeWithdraw.state === 2 || freeWithdraw.state === 3)) {
            global.showHomeWithdrawTip(true);
            localStorageSet(LOCAL_WITHDRAW_TIP_TS, Date.now());
            return true;
        }
        return false;
    };
    const onCloseHallWheel = () => {
        //checkOpenCheckin();
        // startPopupflows();
    };
    const checkOpenInstallBox = () => {
        if (promoteInstall > 0) {
            if (global.installed === 1) return;
            global.installed = 1;
            let time = promoteInstall * 1000;
            // time=1000;
            setTimeout(async () => {
                if (!isShowInstallBox()) return;
                let gameID = Number(objInfo.gameID);
                if (gameID > 0) return;
                global.showInstallBox();
            }, time);
        }
    };
    const checkOpenInChrome = () => {
        let time = 200;
        setTimeout(async () => {
            if (!isShowInstallBox()) return;
            if (isInAppBrowser()) {
                openUrlUseChrome();
            }
        }, time);
    };
    //检查打开绑定提示
    const checkOpenBindPrompt = () => {
        if (vip > 0) return;
        if (guest !== 1) return;
        if (popBindPhone !== 1) return;
        if (global.ispopBindPhone === 1) return;
        if (pathname.startsWith(ROUTE_PATH.GAME)) return;
        if (isBindPhoneRef.current) return;
        //if (!checkTimestampIsNextDay(LOCAL_BIND_TIPS_TS)) return;

        let flag = localStorageGet(LOCAL_BIND_TIPS_TS, "");
        if (flag !== '') return;

        localStorageSet(LOCAL_BIND_TIPS_TS, Date.now());
        global.showBindPhone();
        global.ispopBindPhone = 1;
        return true;
    };
    //检查维护
    const checkMaintain = () => {
        // let sdate=new Date(2024, 7, 27, 3, 0, 0);
        // let edate=new Date(2024, 7, 27, 7, 0, 0);
        // let stime=sdate.getTime();
        // let etime=edate.getTime();
        //巴西时间
        let stime = getBrazilTimeStamp("2024-08-29 01:00:00");
        // let stime=getBrazilTimeStamp("2024-08-26 16:34:00");
        let etime = getBrazilTimeStamp("2024-08-29 01:10:00");
        let now = Date.now();
        let isopen = false;
        if (now >= stime && now <= etime) {
            isopen = true;
            setIsMaintain(isopen);
        }
        return isopen;
    };
    //检查选择地区
    const checkAreaSelect = () => {
        let isopen = false;
        let areaID = global.getLocalAreaID();
        if (areaID <= 0) {
            global.setLocalAreaID(1);
            // isopen=true;
            // setIsSelectArea(isopen);
            // global.showAreaSelect(false);
        }
        return isopen;
    };
    const checkNewUserPrompt = () => {
        // if (userInfo.Registed === 1) return false;
        // global.showNewUserPrompt();
        // return true;
        if (global.newUserPrompted) return;
        global.newUserPrompted = true;
        global.showNewUserPrompt();
    };
    //检查是否弹downloadprompt
    const checkDownloadPrompt=()=>{
        if (checkIsStandalone()||isTWA()) return false;
        // if (!checkTimestampIsNextDay(LOCAL_DOWNLOAD_PROMPT_TS)) return false;
        // localStorageSet(LOCAL_DOWNLOAD_PROMPT_TS, Date.now());
        global?.downloadPrompt.show();
        return true;
    }
    //检查是否领取pwa
    const checkPopPwaBonus =()=>{
        if (userID<=0)return false;
        if (!(checkIsStandalone() || isTWA())) return false;
        let isActive=Boolean(Number(popPwaBonus));
        if (isActive){
            global.popPwaBonus&&global.popPwaBonus.show();
        }
        return isActive;
    }
    //弹窗顺序
    const launchPopupflows = () => {
        if (window.location.pathname !== ROUTE_PATH.HOME) return;
        if (global.isNewUser) return;

        global.clearPopupFlow();
        // global.addPopupFlow(checkNewUserPrompt);
        //pwa bonus
        global.addPopupFlow(checkPopPwaBonus);
        global.addPopupFlow(checkOpenBindPrompt);
        global.addPopupFlow(checkLaunchCheckin);
        global.addPopupFlow(checkFirstPayPopup);
        global.addPopupFlow(checkLaunchHolidaysGift);
        global.addPopupFlow(checkLaunchHolidaysAct);
        // global.addPopupFlow(checkPddWheel);
        //提示下载
        global.addPopupFlow(checkDownloadPrompt);
        global.openNextPopup();
    };
    ///
    const gameBackPopupflows = () => {
        let hash = window.location.hash;
        if (!!hash && hash.length > 0) return;

        if (global.ignorePopup) {
            global.ignorePopup = false;
            return;
        }

        global.clearPopupFlow();
        global.addPopupFlow(checkPopPwaBonus);
        global.addPopupFlow(checkFreeWithdraw);
        global.addPopupFlow(checkHomeWithdrawTips);
        global.addPopupFlow(checkFirstPayPopup);
        global.addPopupFlow(checkGameBackHolidaysGift);
        // global.addPopupFlow(checkGameBackHolidaysAct);
        global.addPopupFlow(checkOpenBindPrompt);
        global.addPopupFlow(checkGameBackCheckin);
        // global.addPopupFlow(checkPddWheel);
        global.addPopupFlow(checkDownloadPrompt);
        global.openNextPopup();
    };
    const onGameBack = async () => {
        global.onGameBack();
        if (userID > 0) {
            await Promise.all([
                dispatch(reqFreeWithdrawMission()).unwrap(),
                dispatch(reqFirstPayGift()).unwrap(),
                dispatch(reqGameInfo()).unwrap(),
                dispatch(reqFreeWithdraw()).unwrap(),
            ]);

            gameBackPopupflows();
        }
    };
    //app Effect
    //初始化
    useEffect(() => {
        appInitData();
        updateShareUrl();
        return () => {

        };
    }, []);
    //用户信息改变
    useEffect(() => {
        reqInitData();
    }, [userID]);
    //转盘
    // useEffect(() => {
    // console.error("turnplate", Date.now());
    // if (turnplate) {
    //     let times = turnplate.times;
    //     if (times > 0) {
    //         if (pathname === "/") {
    //             if (hash == null || hash === "") {
    //                 if (popWheel) {
    //                     setIsShowWheel(true);
    //                     return;
    //                 }
    //             }
    //         }
    //     }
    // }
    // if (userID > -1) {
    //     startPopupflows();
    // }
    // }, [turnplate]);
    //监听上一次的路由
    useEffect(() => {
        if (preLocation) {
            let pathname = preLocation.pathname;
            if (pathname && window.location.pathname == ROUTE_PATH.HOME) {
                if (pathname.startsWith(ROUTE_PATH.GAME)) {
                    //更新金币
                    onGameBack();
                }
            }
        }
        //检查是否维护
        checkMaintain();
    }, [preLocation]);
    //监听gameID
    useEffect(() => {
        dispatch(updateCurrGame(gameID));
        dispatch(hallSendState());
        objInfo.gameID = gameID;
    }, [gameID]);
    //监听被服务器踢掉
    useEffect(() => {
        if (serverKick === 1) {
            if (pathname.startsWith(ROUTE_PATH.GAME)) {
                navigate(ROUTE_PATH.HOME, { replace: true });
            }
        }
    }, [serverKick]);
    //监听安装提示
    useEffect(() => {
        checkOpenInstallBox();
    }, [promoteInstall]);
    //监听打开pay
    useEffect(() => {
        if (openPay === 1) {
            navigate(ROUTE_PATH.PAY, { replace: true });
            dispatch(updateOpenPay(0));
        }
    }, [openPay]);
    useEffect(() => {
        if (payFinishFlag === 1) {
            navigate(ROUTE_PATH.HOME, { replace: true });
            dispatch(resetPayFinishFlag());
        }
    }, [payFinishFlag])


    const homePopupTimer = useRef(null);
    const clearHomePopupTimer = () => {
        if (homePopupTimer.current != null) {
            clearTimeout(homePopupTimer.current);
            homePopupTimer.current = null;
        }
    };

    const backHomePopup = () => {
        if (userID <= 0) return;
        if (pathname != ROUTE_PATH.HOME) return;
        if (hash != null && hash.length > 0) return;
        if (gameID != 0) return;

        if (global.ignorePopup) {
            global.ignorePopup = false;
            return;
        }
        // 开始弹窗逻辑
        // console.error(`>>>>>>>>> pathname: ${preLocation.pathname} hash: ${preLocation.hash}`)
        launchPopupflows();
    };

    useEffect(() => {
        backHomePopup();
    }, [pathname, hash]);
    //app Effect

    const renderLayout = () => {
        //fb 内打开引导去默认浏览器
        if (checkBrowserNotSupport()){
            return (
                <>
                    {
                        fetchStatus === REQ_STATUS.IDLE ? <WBrowserNotSupport/> : (<LoadingFull />)
                    }
                </>
            )
        }
        if (isMaintain) return (
            <WMaintainBox open={true}></WMaintainBox>
        );
        if (isSelectArea) return (<></>);
        return (
            <>
                {
                    fetchStatus === REQ_STATUS.IDLE ? <Layout onCloseHallWheel={onCloseHallWheel} /> : (<LoadingFull />)
                }
            </>
        );
    };
    const renderPreload = () => {
        //维护
        if (isMaintain) return (<></>);
        if (isSelectArea) return (<></>);
        return (
            <>
                {/* {<WInstallBox/>} */}
                {<WDownBox />}
                {<WShortcutGuide />}
            </>
        );
    };
    const renderAreaSelect = () => {
        return (
            <WAreaSelect />
        );
    };

    return (
        <CacheProvider value={cacheRtl}>
            <MuiThemeProvider theme={muiTheme}>
                <ThemeProvider theme={{ theme: theme }}>
                    <SidebarProvider>
                        <WithdrawMissionProvider>
                            <ThemeStyles />
                            <ToastContainer theme={theme} autoClose={2500}
                                position={direction === 'ltr' ? 'top-right' : 'top-left'} style={{
                                    width: '100%',
                                    maxWidth: "510px",
                                    right: "auto",
                                    left: "auto"
                                }}
                                limit={1}
                            />
                            <StyleSheetManager stylisPlugins={plugins}>
                                {
                                    renderLayout()
                                }
                            </StyleSheetManager>
                            {
                                renderPreload()
                            }
                        </WithdrawMissionProvider>
                    </SidebarProvider>
                </ThemeProvider>
            </MuiThemeProvider>
        </CacheProvider>
    );
};

export default App;
