import styles from './styles.module.scss';


// hooks
import { useRef, useState, useEffect } from 'react';

import symbol from '@assets/symbol-defs.svg';
import icon1 from '@assets/sidebar/activity-switch-icon.webp';
import pdd from '@assets/sidebar/pdd.webp';
import firstRecharge from '@assets/sidebar/firstRecharge.webp';
import withdraw from '@assets/sidebar/withdraw.webp';
import bindPhone from '@assets/sidebar/bindPhone.webp';
import signIn from '@assets/sidebar/signIn.webp';
import rescue from '@assets/sidebar/rescue.webp';
import customer from '@assets/sidebar/customer.webp';
import download_ios from '@assets/sidebar/download.webp';
import download_android from '@assets/sidebar/download_android.webp';
import { checkIsStandalone, isAndroid } from '@utils/helpers';
import { useNavigate } from 'react-router';
import { ROUTE_PATH } from '@constants/routes';
import { getIsBindPhone, getIsGuest, getServiceLink } from '@features/mainSlice';
import { useSelector } from 'react-redux';
import { getFirstPayGift } from '@features/paySlice';



const Sidebar2 = () => {
    const [show, setShow] = useState(true);
    const [open, setOpen] = useState(false);
    const [showMore, setShowMore] = useState(true);
    const navigate = useNavigate();

    const isBind = useSelector(getIsBindPhone);
    const firstGiftInfo = useSelector(getFirstPayGift);
    const isStandalone = checkIsStandalone();//是否下载

    const serviceLink = useSelector(getServiceLink);


    useEffect(() => {
        let pathname = window.location.pathname;
        let hash = window.location.hash;
        if (pathname == "/" && hash == "") {
            if (!show) setShow(true);
        } else {
            if (show) setShow(false);
        }
    }, [window.location.pathname, window.location.hash]);

    useEffect(() => {
        const homeSidebar = {
            show: () => { setOpen(true) }
        }
        global.homeSidebar = homeSidebar;
    }, [])

    // 在任意位置添加这个测试组件
    function ScrollTest() {
        return (
            <div style={{
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                width: '200px',
                height: '200px',
                background: 'white',
                border: '2px solid red',
                zIndex: 10000,
                overflowY: 'auto',
                touchAction: 'pan-y'
            }}>
                {Array(20).fill(0).map((_, i) => (
                    <div key={i} style={{ padding: '10px', borderBottom: '1px solid #ccc' }}>
                        测试行 {i} - 如果能看到这个，就能滚动
                    </div>
                ))}
            </div>
        );
    }

    let data = [
        { closeBar: false, link: serviceLink, target: "", status: true, img: customer },
        { closeBar: false, link: "", target: "showCheckIn", status: true, img: signIn },
        { closeBar: false, link: "", target: "showProtectReward", status: true, img: rescue },
        { closeBar: false, link: "", target: "showBindPhone", status: !isBind, img: bindPhone },
        { closeBar: false, link: "", target: "showFirstPay", status: !!!firstGiftInfo?.has_purchased, img: firstRecharge },
        { closeBar: true, link: ROUTE_PATH.SHARE, target: "", status: true, img: pdd },
        { closeBar: true, link: "", target: "showShortcutGuide", status: !isStandalone, img: isAndroid() ? download_android : download_ios },


    ];

    const renderMobile = () => {

        return (
            <>
                <div className={open ? styles.mask : ""} onClick={() => setOpen(false)} />

                <div className={`${open ? styles.open : styles.close} ${styles.sidebar}`}>
                    <div className={styles.sidebarTrigger}>
                        <button className={styles.burger}
                            onClick={handleClick}
                            aria-label="Open sidebar">

                            <svg className={`${styles.svg1}`} width={61} height={152}>
                                <use xlinkHref={`${symbol}#SideBar_icon`} />
                            </svg>
                            <img src={icon1} alt="" className={open ? styles.openIcon : ""} />

                        </button>

                        {
                            showMore ? (
                                <div className={styles.more} onClick={handleClickMore} >
                                    <svg className={`${styles.svg2}`} width={24.031} height={22.063}>
                                        <use xlinkHref={`${symbol}#SideBar_icon2`} />
                                    </svg>
                                </div>
                            ) : ""
                        }
                    </div>


                    <div className={styles.content} ref={contentRef} onScroll={handleScroll}>
                        {/* {Array(100).fill(0).map((_, index) => (
                            <p key={index}>内容项 {index}</p>
                        ))} */}
                        {
                            data.map((item, index) => {
                                if (!item.status) return <></>;

                                return (
                                    <div className={styles.item} key={index} onClick={() => handleClickItem(item)}>
                                        <img src={item.img} alt="" />
                                    </div>
                                );
                            })
                        }
                    </div>



                </div >

            </>

        );
    };



    const handleClick = (e) => {
        setOpen(!open);
    };
    const handleClickMore = (e) => {
        const content = contentRef.current;
        if (!content) return;

        const start = content.scrollTop;
        const end = content.scrollHeight - content.clientHeight;
        const duration = 200;
        const startTime = Date.now();

        const scrollInterval = setInterval(() => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);
            const easedProgress = 1 - Math.pow(1 - progress, 2);

            content.scrollTop = start + (end - start) * easedProgress;

            if (progress >= 1) {
                clearInterval(scrollInterval);
            }
        }, 16); // 约60帧/秒（1000ms/60 ≈ 16ms）
    };
    const handleClickItem = (item) => {
        let { link, target, closeBar } = item;
        if (closeBar || link) setOpen(false);
        if (link) {
            if (link.startsWith("http")) {
                window.open(link);
                return;
            }
            setTimeout(() => {
                navigate(link);
            }, 100);
        } else if (target) {
            global[target] && global[target]();
        }
    };


    const contentRef = useRef(null);

    const handleScroll = (e) => {
        const { scrollTop, scrollHeight, clientHeight } = e.target;
        // console.log("当前滚动位置:", scrollTop);
        // console.log("总高度:", scrollHeight);
        // console.log("可视高度:", clientHeight);

        // 判断是否滚动到底部
        const isBottom = scrollHeight - scrollTop <= clientHeight + 1;
        if (isBottom) {
            setShowMore(false);
            // console.error("已滚动到底部");
        } else {
            setShowMore(true);
            // console.error("未滚动到底部");
        }
    };

    useEffect(() => {
        if (open) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
        }
    }, [open]);

    const checkOverflow = () => {
        if (!contentRef.current) return false;

        const element = contentRef.current;
        // 垂直方向是否溢出
        const hasVerticalOverflow = element.scrollHeight > element.clientHeight;
        // 水平方向是否溢出
        const hasHorizontalOverflow = element.scrollWidth > element.clientWidth;

        return hasVerticalOverflow || hasHorizontalOverflow;
    };

    // 使用示例
    useEffect(() => {
        if (contentRef.current) {
            const isOverflowing = checkOverflow();
            // console.error('内容是否溢出:', isOverflowing);
            setShowMore(isOverflowing);
        }
    }, [open]); // 当data变化时检查


    if (!show) return <></>;

    return (
        <>
            {
                renderMobile()
            }
        </>
    );
};

export default Sidebar2;
