jQuery(document).ready(function($) {
    var isGameLoaded = false;
    var isLoading = false;
    var fireworkInterval = null; 

    function getGlobalConfig() {
        return (typeof ZutalwConfig !== 'undefined') ? ZutalwConfig : null;
    }

    var config = getGlobalConfig();
    if (!config) return;

    // ==================================================
    // 0. HÀM TẠO POPUP THÔNG BÁO CUSTOM (REPLACES BROWSER ALERT)
    // ==================================================
    window.zutalw_custom_alert = function(message) {
        window.isPopupOpen = true; // 🔥 ĐÓNG BĂNG VÒNG QUAY NGAY LẬP TỨC

        var $alertBox = $('#zutalw-custom-alert');
        if ($alertBox.length === 0) {
            var html = `
            <div id="zutalw-custom-alert" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:999999; align-items:center; justify-content:center;">
                <div style="background:#fff; border-radius:8px; width:90%; max-width:350px; text-align:center; box-shadow:0 4px 12px rgba(0,0,0,0.15); font-family:sans-serif; overflow:hidden;">
                    <div style="padding:15px; border-bottom:1px solid #eee;">
                        <h3 style="margin:0; color:#333; font-size:16px; font-weight:bold;">NOTIFICATION</h3>
                    </div>
                    <div style="padding:25px 20px;">
                        <p style="color:#555; font-size:15px; margin:0 0 25px;">${message}</p>
                        <button id="zutalw-custom-alert-close" style="background:#0d6efd; color:#fff; border:none; padding:10px 30px; border-radius:4px; cursor:pointer; font-size:15px; font-weight:bold; width:100%; max-width:120px;">Close</button>
                    </div>
                </div>
            </div>`;
            $('body').append(html);

            // Bắt sự kiện mousedown để chặn nhấp nháy click xuyên thấu
            $(document).on('mousedown touchstart click', '#zutalw-custom-alert-close', function(e) {
                e.stopPropagation();
                $('#zutalw-custom-alert').fadeOut(200);
                
                // 🔥 ĐỢI 300ms SAU KHI TẮT THÔNG BÁO MỚI MỞ KHÓA VÒNG QUAY
                setTimeout(function() {
                    window.isPopupOpen = false;
                }, 300);
            });
        } else {
            $alertBox.find('p').text(message);
        }
        $('#zutalw-custom-alert').css('display', 'flex').hide().fadeIn(200);
    };

    // ==================================================
    // 1. HÀM TẢI SCRIPT
    // ==================================================
    function loadScript(url) {
        return new Promise(function(resolve) {
            if (!url) return resolve();
            if (document.querySelector('script[src="' + url + '"]')) return resolve();
            var script = document.createElement('script');
            script.src = url;
            script.onload = resolve;
            script.onerror = function() {
                console.warn('[ZutaLW Debug] Failed to load:', url);
                resolve();
            };
            document.head.appendChild(script);
        });
    }

    // ==================================================
    // 2. KHỞI TẠO ĐỊNH DANH 
    // ==================================================
    function initIdentityAndProcess() {
        var s = (typeof zutalw_Lazy_Assets !== 'undefined') ? zutalw_Lazy_Assets.scripts : {};
        var fpUrl = s.fingerprint;

        loadScript(fpUrl).then(function() {
            if (window.FingerprintJS) {
                window.FingerprintJS.load().then(function(fp) {
                    return fp.get();
                }).then(function(result) {
                    console.log('[ZutaLW Debug] Fingerprint ID generated:', result.visitorId);
                    finalizeIdentity(result.visitorId);
                }).catch(function(err) {
                    useFallbackIdentity();
                });
            } else {
                useFallbackIdentity();
            }
        });
    }

    function useFallbackIdentity() {
        var storedId = localStorage.getItem('zutalw_device_id');
        if (!storedId) {
            storedId = 'guest_' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('zutalw_device_id', storedId);
        }
        finalizeIdentity(storedId);
    }

    function finalizeIdentity(deviceId) {
        window.zutalw_visitor_id = deviceId;
        config.device_id = deviceId;
        if (typeof ZutalwConfig !== 'undefined') {
            ZutalwConfig.device_id = deviceId;
        }
        initProcess();
    }

    // ==================================================
    // 3. KIỂM TRA LƯỢT QUAY TỪ SERVER (AUTO-LOAD)
    // ==================================================
    function initProcess() {
        var campId = config.target_campaign_id || 0;
        window.zutalw_active_campaign_id = campId;

        if (campId === 0) return;

        $.ajax({
            url: config.ajax_url,
            type: 'POST',
            data: {
                action: 'zutalw_check_limit',
                security: config.nonce,
                device_id: window.zutalw_visitor_id,
                idcampain: campId
            },
            success: function(res) {
                if (res.success) {
                    var spins = parseInt(res.data.spins_left) || 0;
                    window.zutalw_current_spins = spins;

                    if (spins > 0) {
                        $('#zutalw-spins-left').text(spins);
                        setTimeout(function() {
                            $('#zutalw-gift-trigger').css('display', 'flex').hide().fadeIn();
                            startFireworks();
                        }, parseInt(config.popup_delay) || 500);
                    } else {
                        console.log('[ZutaLW Debug] Auto-load skipped: User has no spins left.');
                    }
                }
            }
        });
    }

    initIdentityAndProcess();

    // ==================================================
    // 4. HÀM CHUNG: NẠP ENGINE 3 TẦNG VÀ HIỂN THỊ GAME
    // ==================================================
    function launchGame(targetId) {
        $('#zutalw-gift-trigger').fadeOut();
        $('#zutalw-popup-wrapper').fadeIn();

        if (isGameLoaded || isLoading) return;
        isLoading = true;
        $('#zutalw-loading').show();

        var s = (typeof zutalw_Lazy_Assets !== 'undefined') ? zutalw_Lazy_Assets.scripts : {};
        
        $('#area-game').attr('data-id', targetId);
        window._idcampain = targetId;
        window.zutalw_active_campaign_id = targetId; // Synchronize global campaign ID

        Promise.all([
            loadScript(s.p5),
            loadScript(s.matter)
        ]).then(function() {
            return Promise.all([
                loadScript(s.p5_dom),
                loadScript(s.p5_sound),
                loadScript(s.decomp),
                loadScript(s.pathseg),
                loadScript(s.arcshape), 
                loadScript(s.particle),
                loadScript(s.boundary)
            ]);
        }).then(function() {
            return Promise.all([
                loadScript(s.sketch),
                loadScript(s.custom)
            ]);
        }).then(function() {
            isGameLoaded = true;
            isLoading = false;
            $('#zutalw-loading').hide();
            console.log('[ZutaLW Debug] Full Engine & Classes loaded.');
            if (typeof p5 !== 'undefined') new p5();
        });
    }

    // ==================================================
    // 5A. CLICK TRIGGER -> LOAD POOL 2 DIRECTLY IF VIP MODE IS ON
    // ==================================================
    $(document).on('click', '.zutalw-card-btn, #zutalw-gift-trigger', function(e) {
        if ($(e.target).hasClass('zutalw-card-close')) return;
        e.preventDefault();
        var targetId = window.zutalw_active_campaign_id || 1;
        
        let trade_enabled = (config && config.tradein_enabled !== undefined) ? parseInt(config.tradein_enabled) : 0;

        if (trade_enabled === 1) {
            console.log("[ZutaLW Debug] VIP Mode: Loading Pool 2 directly.");
            window.zutalw_current_pool_level = 2; // Force load VIP Pool immediately
            window.zutalw_form_submitted = false; // Lock the spin button
        } else {
            window.zutalw_current_pool_level = 1;
        }

        $('#zutalw-gift-trigger').fadeOut();
        launchGame(targetId);
    });

    // ==================================================
    // 5B. XỬ LÝ CLICK TỪ LINK ẢNH (Vd: <a href="#zutalw_lucky_spin=2">)
    // ==================================================
    $(document).on('click', 'a[href^="#zutalw_lucky_spin"]', function(e) {
        e.preventDefault();
        
        var href = $(this).attr('href');
        var match = href.match(/#zutalw_lucky_spin=(\d+)/);
        var targetId = match ? parseInt(match[1]) : (config.target_campaign_id || 1);

        $('#zutalw-loading').show();

        $.ajax({
            url: config.ajax_url,
            type: 'POST',
            data: {
                action: 'zutalw_check_limit',
                security: config.nonce,
                device_id: window.zutalw_visitor_id || localStorage.getItem('zutalw_device_id'),
                idcampain: targetId
            },
            success: function(res) {
                $('#zutalw-loading').hide();
                if (res.success) {
                    var spins = parseInt(res.data.spins_left) || 0;
                    if (spins > 0) {
                        $('#zutalw-spins-left').text(spins);
                        launchGame(targetId); 
                    } else {
                        // Gọi Custom Popup thay vì Alert mặc định
                        var msg = "You have used all your free spins for this campaign!";
                        window.zutalw_custom_alert(msg);
                    }
                }
            },
            error: function() {
                $('#zutalw-loading').hide();
            }
        });
    });

    // ==================================================
    // 6. EFFECTS & CLOSE BUTTONS
    // ==================================================
    function startFireworks() { fireworkInterval = setInterval(createFirework, 600); }
    function stopFireworks() { clearInterval(fireworkInterval); $('.zutalw-firework').remove(); }
    function createFirework() {
        var $c = $('#zutalw-gift-trigger'); if ($c.is(':hidden')) return;
        var $f = $('<div class="zutalw-firework"></div>').css({'top':Math.random()*40+30+'%','left':Math.random()*40+30+'%'});
        $c.append($f); setTimeout(()=>$f.remove(), 1000);
    }

    $(document).on('mousedown touchstart click', '.zutalw-close-game, .zutalw-congrats-close, .zutalw-card-close, .btn-close', function(e) {
        e.stopPropagation();
        $(this).closest('[id$="-overlay"], [id$="-wrapper"], [id$="-trigger"], .zutalw-popup-form').fadeOut();
        stopFireworks();
        setTimeout(function() { 
            window.isPopupOpen = false; 
        }, 300);
    });
});

// ==================================================
// 7. POPUP WINNER FORM VÀ FIREWORKS TRÚNG GIẢI
// ==================================================
(function($) {
    let confettiAnimationId;

    window.get_popup = function(giftLabel, type = '', campaignId = 0) {
        var isTradeIn = (type === 'trade_in' || window.zutalw_is_trade_in_flow === true) ? 1 : 0;
        var cfg = typeof ZutalwConfig !== 'undefined' ? ZutalwConfig : { ajax_url: '/wp-admin/admin-ajax.php', nonce: '' };

        $.ajax({
            url: cfg.ajax_url,
            type: 'POST',
            data: {
                action: 'zutalw_popup',
                security: cfg.nonce,
                name_gif: giftLabel,
                is_trade_in: isTradeIn,
                campaign_id: campaignId // BỔ SUNG DÒNG NÀY ĐỂ BÁO CHO SERVER BIẾT CHIẾN DỊCH NÀO
            },
            beforeSend: function() { $('#zutalw-loading').show(); },
            success: function(res) {
                $('#zutalw-loading').hide();
                $('#zutalw-popup-notify').html(res).fadeIn();
                window.isPopupOpen = true;
            },
            error: function() {
                $('#zutalw-loading').hide();
                if (typeof window.zutalw_custom_alert === 'function') {
                    window.zutalw_custom_alert('Could not load form. Please refresh.');
                }
            }
        });
    };

    window.zutalw_fireworks_win = function(giftLabel) {
        $('#zutalw-won-gift-name').text(giftLabel);
        $('#zutalw-popup-wrapper').hide();
        $('#zutalw-congrats-overlay').css('display', 'flex');
        startZutaFireworks();
    };

    $(document).on('click', '#zutalw-btn-claim-gift', function() {
        $('#zutalw-congrats-overlay').hide();
        window.get_popup($('#zutalw-won-gift-name').text(), 'claim', window.zutalw_active_campaign_id);
    });

    $(document).on('click', '#zutalw-btn-trade-in', function() {
        $('#zutalw-congrats-overlay').hide();
        window.get_popup($('#zutalw-won-gift-name').text(), 'trade_in', window.zutalw_active_campaign_id);
    });

    function startZutaFireworks() {
        const canvas = document.getElementById("zutalw-fireworks-canvas");
        if (!canvas) return;
        const ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth; canvas.height = window.innerHeight;
        let particles = [];
        function draw() {
            ctx.clearRect(0,0,canvas.width,canvas.height);
            particles.forEach((p, i) => {
                p.y += 3; p.x += p.dx;
                ctx.fillStyle = p.color; ctx.fillRect(p.x, p.y, p.r, p.r);
                if (p.y > canvas.height) particles.splice(i, 1);
            });
            if (particles.length < 100) particles.push({x:Math.random()*canvas.width, y:0, r:Math.random()*5+2, dx:Math.random()*2-1, color:'#'+(Math.random()*0xFFFFFF<<0).toString(16)});
            confettiAnimationId = requestAnimationFrame(draw);
        }
        draw();
    }
    // Handle form submission and Pool switching
    $(document).on('click', '#zutalw-submit-winner-btn', function(e) {
        e.preventDefault();
        
        let cfg = typeof ZutalwConfig !== 'undefined' ? ZutalwConfig : { ajax_url: '/wp-admin/admin-ajax.php', nonce: '' };
        let isTradeIn = parseInt($('input[name="is_trade_in_hidden"]').val()) || 0;
        
        let formData = {
            action: 'zutalw_InsCustomer',
            security: cfg.nonce,
            fullname: $('.zutalw-popup-form .fullname').val(),
            phone: $('.zutalw-popup-form .phone').val(),
            email: $('.zutalw-popup-form .email').val(),
            getgift: $('input[name="getgift_hidden"]').val(),
            is_trade_in: isTradeIn,
            campaign_id: window.zutalw_active_campaign_id || 1,
            device_id: window.zutalw_visitor_id || localStorage.getItem('zutalw_device_id'),
            page_url: window.location.href
        };

        if (!formData.fullname || !formData.phone) {
            if (typeof window.zutalw_custom_alert === 'function') window.zutalw_custom_alert('Please fill in your name and phone!');
            else alert('Please fill in your name and phone!');
            return;
        }

        $('#zutalw-loading').show();

        $.ajax({
            url: cfg.ajax_url,
            type: 'POST',
            data: formData,
            success: function(res) {
                $('#zutalw-loading').hide();
                
                if (res.success) {
                    $('#zutalw-popup-notify').fadeOut();
                    
                    // 🔥 ÉP MỞ KHÓA: Nếu Form có cờ TradeIn HOẶC đang ở giao diện Pool 2
                    // Chỉ cần submit thành công là chắc chắn Mở Khóa!
                    if (isTradeIn === 1 || window.zutalw_current_pool_level === 2) {
                        window.zutalw_form_submitted = true; 
                        console.log("[ZutaLW Debug] VIP Form submitted successfully. Wheel is UNLOCKED!");
                    }

                    // Đẩy thẳng tin nhắn của Backend vào Custom Alert
                    if (typeof window.zutalw_custom_alert === 'function') {
                        window.zutalw_custom_alert(res.data.message);
                    } else {
                        alert(res.data.message);
                        window.isPopupOpen = false; // Phục hồi nếu không có Custom Alert
                    }

                } else {
                    if (typeof window.zutalw_custom_alert === 'function') window.zutalw_custom_alert(res.data.message);
                    else alert(res.data.message);
                }
            },
            error: function() {
                $('#zutalw-loading').hide();
                alert('Connection error!');
            }
        });
    });
})(jQuery);
