import React, { useEffect, useRef, useState } from "react";
import styles from './styles.module.scss';

import download from '@assets/topArea/download.webp';
import close from '@assets/topArea/close.webp';
import { useLocation } from "react-router";
import { ROUTE_PATH } from "@constants/routes";
import { checkIsStandalone } from "@utils/helpers";

const TopDownload = ({ data }) => {
    const [show, setShow] = useState(true);
    const [inGame, setInGame] = useState(false);
    const [imgHeight, setImgHeight] = useState(0);
    const isStandalone = checkIsStandalone();//是否下载
    const { pathname } = useLocation();

    const handleClick = () => {
        global["showShortcutGuide"] && global["showShortcutGuide"]();
        // adjust 点击顶部pwa下载按钮
        global.tracker.trackEvent("click_download");
    };

    const handleClickClose = (e) => {
        e.stopPropagation();
        setShow(false);
    };

    useEffect(() => {
        setInGame(pathname.startsWith(ROUTE_PATH.GAME));
    }, [pathname]);

    const downloadRef = useRef(null);

    // 获取图片高度的函数
    const updateImgHeight = () => {
        if (downloadRef.current) {
            setImgHeight(downloadRef.current.offsetHeight);
        }
    };

    useEffect(() => {
        if (!show) return;

        const handleLoad = () => {
            updateImgHeight();
        };
        
        let imgElement = downloadRef.current;
        
        if (imgElement) {
            // 如果图片已经加载完成
            if (imgElement.complete) {
                handleLoad();
            } else {
                imgElement.addEventListener('load', handleLoad);
            }
        }

        // 添加窗口resize监听
        window.addEventListener('resize', updateImgHeight);
        
        return () => {
            if (imgElement) {
                imgElement.removeEventListener('load', handleLoad);
            }
            window.removeEventListener('resize', updateImgHeight);
        };
    }, [show]); // 当show状态改变时重新获取

    if (!show || inGame || isStandalone) return <></>;
    return (
        <div className={styles.container} onClick={handleClick}>
            <img src={download} alt="" className={styles.download} ref={downloadRef} />
            <div 
                className={styles.close} 
                style={{ 
                    backgroundImage: `url(${close})`,
                    height: `${imgHeight}px`,
                    width: `${imgHeight}px`
                }} 
                onClick={handleClickClose}
            ></div>
        </div >
    );
};
export default TopDownload;