import styles from './styles.module.scss'
import {useEffect, useRef, useState} from "react";
import {useThemeProvider} from "@contexts/themeContext";
import {useDispatch, useSelector} from "react-redux";
import {
    getBBConf,
    getUserBBToken,
    getUserID,
    getUserInfo, getUserLang, getUserNick,
    getUserNickAndLang,
    getUserThemeAndLang
} from "@features/mainSlice";
import {APP_THEME} from "@constants/app";
import {useLocation, useNavigate} from "react-router-dom";
import {ROUTE_PATH} from "@constants/routes";
import {reqGameInfo} from "@features/api";
import {getUrlParam} from "@utils/helpers";
import {useWindowSize} from "react-use";
const i18n=global.i18n;
const objInfo={
    bt:null,
    timer:null,
    isTopHeader:false,
    isMobile:false,
}
const checkStartPath=(pathname)=>{
    // let path=pathname.startsWith(ROUTE_PATH.RACING)?"/horse-racing-55":"/";
    let path=pathname;
    if (path.startsWith(ROUTE_PATH.SPORTS)) {
        path=path.replace(ROUTE_PATH.SPORTS,"");
    }
    else if (path.startsWith(ROUTE_PATH.RACING)){
        path=path.replace(ROUTE_PATH.RACING,"");
    }
    if (path==="")path=pathname.startsWith(ROUTE_PATH.RACING)?"/horse-racing-55":"/";
    let bt_path=getUrlParam("bt-path");
    if (bt_path!=null&&bt_path!==""){
        path=bt_path;
    }
    return path;
}
const WSport=({resetSport})=>{
    const {isMobile,showMHeader}=useThemeProvider();
    const bbConf=useSelector(getBBConf);
    const {theme}=useThemeProvider();
    const user=useSelector(getUserInfo);
    const userID=useSelector(getUserID);
    const language=i18n.language;
    const navigate=useNavigate();
    const dispatch=useDispatch();
    const {pathname,hash} = useLocation();
    // const tempSPath=pathname.startsWith(ROUTE_PATH.RACING)?"/horse-racing-55":"/";
    const tempSPath=checkStartPath(pathname);
    const [sportPath,setSportPath]=useState(tempSPath);
    const btToken=useSelector(getUserBBToken);
    const userLang=useSelector(getUserLang);
    const userNick=useSelector(getUserNick);
    const {width} = useWindowSize();
    const [stickyTop,setStickyTop]=useState(-1);
    const [betSlipOffsetBottom,setBetSlipOffsetBottom]=useState(-1);
    //监听install
    let installBanner = document.querySelector('#installBanner');
    const handleResize = (entries) => {
        for (let entry of entries) {
            if (entry.target === installBanner) {
                checkStickyTop();
            }
        }
    };
    const observer = new ResizeObserver(handleResize);
    const refreshToken=async ()=>{
        return new Promise((resolve, reject) => {
            dispatch(reqGameInfo()).then(({payload})=>{
                let data=payload.data;
                if (data!=null){
                    let bb=data.bb;
                    if (bb!=null){
                        resolve(bb.token);
                    }
                    else reject('');
                }
                else reject('');
            });
        });
    }
    const initBetby=()=>{
        if (bbConf==null)return null;
        let brand_id=bbConf.id;
        let bbtheme=bbConf.theme;
        let themeIndex=0;
        if (theme===APP_THEME.LIGHT)themeIndex=1;
        let themeName=bbtheme[themeIndex];
        // let token=null;
        // if (bbConf.token!=null)token=bbConf.token;
        // if (user!=null&&user.bb!=null&&user.bb.token!=null)token=user.bb.token;
        // token=null;
        let token=btToken;
        // let betSlipOffsetBottom=isMobile()?70:0;
        // let stickyTop=isMobile()?55:60;
        let betSlipOffsetBottom=checkBetSlipOffsetBottom();
        let stickyTop=checkStickyTop();
        var bt = new window.BTRenderer().initialize({
            brand_id: brand_id,
            token: token,
            onTokenExpired: ()=>refreshToken(),
            themeName: themeName,
            // themeName: "bc-game-dark-tile",
            lang: language,
            target: document.getElementById('betby'),
            betSlipOffsetBottom: betSlipOffsetBottom,
            betSlipOffsetRight: 0,
            betSlipOffsetTop: 130,
            betslipZIndex: 100,
            stickyTop: stickyTop,
            url:sportPath,
            onRouteChange: function() {},
            onLogin: function() {
                navigate(ROUTE_PATH.SIGN_IN);
            },
            onRegister: function() {
                navigate(ROUTE_PATH.SIGN_UP);
            },
            onRecharge:function (){
                navigate(ROUTE_PATH.PAY);
            },
            onSessionRefresh: function() {
                // resetBT();
                if (resetSport)resetSport();
            },
            onBetSlipStateChange: function() {}
        })
        return bt;
    }
    const clearBT=()=>{
        if (objInfo.bt){
            objInfo.bt.kill();
            objInfo.bt=null;
        }
    }
    const clearTimer=()=>{
        if (objInfo.timer!=null){
            clearTimeout(objInfo.timer);
            objInfo.timer=null;
        }
    }
    const checkStickyTop=()=>{
        let sTop=55;
        if (objInfo.isMobile){
            if (objInfo.isTopHeader)sTop=126;
            let installBanner = document.querySelector('#installBanner');
            if (installBanner!=null){
                let extH=installBanner.clientHeight;
                sTop+=extH;
            }
        }
        else
        {
            sTop=60;
        }
        setStickyTop(sTop)
        return sTop;
    }
    const checkBetSlipOffsetBottom=()=>{
        let sBottom=0;
        if (objInfo.isMobile){
            sBottom=70;
        }
        setBetSlipOffsetBottom(sBottom);
        return sBottom;
    }
    useEffect(()=>{
        if (pathname.startsWith(ROUTE_PATH.SPORTS)){
            let sub=pathname.replace(ROUTE_PATH.SPORTS,"");
            if (sub==="")sub="/";
            setSportPath(sub);
            if (objInfo.bt){
                objInfo.bt.updateOptions({
                    url:sub
                })
            }
        }
        else if (pathname.startsWith(ROUTE_PATH.RACING))
        {
            let sub=pathname.replace(ROUTE_PATH.RACING,"");
            if (sub==="")sub="/horse-racing-55";
            setSportPath(sub);
            if (objInfo.bt){
                objInfo.bt.updateOptions({
                    url:sub
                })
            }
        }
    },[pathname])
    useEffect(()=>{
        if (hash===""){
            clearTimer();
            objInfo.timer=setTimeout(()=>{
                if (objInfo.bt){
                    objInfo.bt.updateOptions({
                        url:sportPath
                    })
                }
            },20);
        }
    },[hash])
    useEffect(()=>{
        if (objInfo.bt){
            if (bbConf==null)return null;
            let bbtheme=bbConf.theme;
            let themeIndex=0;
            if (theme===APP_THEME.LIGHT)themeIndex=1;
            let themeName=bbtheme[themeIndex];
            objInfo.bt.updateOptions({
                themeName:themeName
            })
        }
    },[theme])
    // useEffect(()=>{
    //     if (objInfo.bt){
    //         objInfo.bt.updateOptions({
    //             lang: language,
    //         })
    //     }
    // },[language])
    const resetBT=()=>{
        objInfo.isTopHeader=showMHeader;
        objInfo.isMobile=isMobile();
        clearBT();
        objInfo.bt=initBetby();
    }
    useEffect(()=>{
        resetBT();
        if (installBanner)observer.observe(installBanner);
        return ()=>{
            clearBT();
            clearTimer();
            if (installBanner)observer.unobserve(installBanner);
        }
    },[userID,userLang,userNick])

    useEffect(()=>{
        objInfo.isTopHeader=showMHeader;
        objInfo.isMobile=isMobile();
        checkStickyTop();
        checkBetSlipOffsetBottom();
    },[showMHeader,width])
    useEffect(() => {
        if (stickyTop===-1)return;
        if (objInfo.bt){
            objInfo.bt.updateOptions({
                stickyTop: stickyTop,
            })
        }
    }, [stickyTop]);
    useEffect(()=>{
        if (betSlipOffsetBottom===-1)return;
        if (objInfo.bt){
            objInfo.bt.updateOptions({
                betSlipOffsetBottom: betSlipOffsetBottom,
            })
        }
    },[betSlipOffsetBottom])
    //,theme,language
    return (
        <div id="betby" className={`${styles.container} ${isMobile()?styles.container_m:''}`}></div>
    )
}
export default WSport;