/**
 * ZutaLW Trigger Logic
 */
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;

    window.zutalw_custom_alert = function(message) {
        window.isPopupOpen = true; 
        var $alertBox = $('#zutalw-custom-alert');
        
        if ($alertBox.length === 0) {
            var htmlAlert = `
            <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(htmlAlert);

            $(document).on('click', '#zutalw-custom-alert-close', function(e) {
                e.stopPropagation();
                $('#zutalw-custom-alert').fadeOut(200);
                setTimeout(function() {
                    window.isPopupOpen = false;
                    window.isGameLocked = false; // 🔥 THÊM DÒNG NÀY
                    window.s_rotated = false;
                    window.winnerFound = false;
                    window.canplay = false;
                    if (typeof window.zutalw_reset_wheel_visuals === 'function') {
                        window.zutalw_reset_wheel_visuals();
                    }
                    console.log("[ZutaLW Debug] System reset for next spin.");
                   
                }, 300);
            });
        } else {
            $alertBox.find('p').text(message);
        }
        $('#zutalw-custom-alert').css('display', 'flex').hide().fadeIn(200);
    };

    // --- CÁC HÀM loadScript, initIdentity, v.v. GIỮ NGUYÊN NHƯ FILE CŨ CỦA BẠN ---
    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);
        });
    }

    function initIdentityAndProcess() {
        var s = (typeof zutalw_Lazy_Assets !== 'undefined') ? zutalw_Lazy_Assets.scripts : {};
        loadScript(s.fingerprint).then(function() {
            if (window.FingerprintJS) {
                window.FingerprintJS.load().then(fp => fp.get()).then(result => {
                    finalizeIdentity(result.visitorId);
                }).catch(() => useFallbackIdentity());
            } else { useFallbackIdentity(); }
        });
    }

    function useFallbackIdentity() {
        var storedId = localStorage.getItem('zutalw_device_id') || '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;

        if (localStorage.getItem('zutalw_saved_customer')) {
            window.zutalw_form_submitted = true;
            console.log("[ZutaLW Debug] Welcome back! VIP Unlocked.");
        }
        initProcess();
    }

    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 && (parseInt(res.data.spins_left) || 0) > 0) {
                    $('#zutalw-spins-left').text(res.data.spins_left);
                    setTimeout(function() { $('#zutalw-gift-trigger').css('display', 'flex').hide().fadeIn(); }, config.popup_delay || 500);
                }
            }
        });
    }

    initIdentityAndProcess();

    function launchGame(targetId) {
        $('#zutalw-gift-trigger').fadeOut();
        $('#zutalw-popup-wrapper').fadeIn();
        if (isGameLoaded || isLoading) return;
        isLoading = true; $('#zutalw-loading').show();
        var s = zutalw_Lazy_Assets.scripts;
        window._idcampain = targetId; window.zutalw_active_campaign_id = targetId;
        Promise.all([loadScript(s.p5), loadScript(s.matter)])
            .then(() => 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(() => Promise.all([loadScript(s.sketch), loadScript(s.custom)]))
            .then(() => { isGameLoaded = true; isLoading = false; $('#zutalw-loading').hide(); if (typeof p5 !== 'undefined') new p5(); });
    }

    $(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;
        if (parseInt(config.tradein_enabled) === 1) {
            window.zutalw_current_pool_level = 2;
            window.zutalw_form_submitted = !!localStorage.getItem('zutalw_saved_customer');
        } else { window.zutalw_current_pool_level = 1; }
        launchGame(targetId);
    });

    $(document).on('click', 'a[href^="#zutalw_lucky_spin"]', function(e) {
        e.preventDefault();
        var match = $(this).attr('href').match(/#zutalw_lucky_spin=(\d+)/);
        var targetId = match ? parseInt(match[1]) : (config.target_campaign_id || 1);
        launchGame(targetId);
    });

    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(() => { window.isPopupOpen = false; }, 300);
        
    });

    // BRIDGE CHO SKETCH.JS
    window.get_popup = function(giftLabel, type = '', campaignId = 0) {
        var isTradeIn = (type === 'trade_in') ? 1 : 0;
        $.ajax({
            url: config.ajax_url, type: 'POST',
            data: { action: 'zutalw_popup', security: config.nonce, name_gif: giftLabel, is_trade_in: isTradeIn, campaign_id: campaignId },
            beforeSend: function() { $('#zutalw-loading').show(); },
            success: function(res) {
                $('#zutalw-loading').hide();
                let $formHtml = $(res);
                let savedData = localStorage.getItem('zutalw_saved_customer');
                if (savedData) {
                    let user = JSON.parse(savedData);
                    $formHtml.find('.fullname').val(user.fullname);
                    $formHtml.find('.phone').val(user.phone);
                    $formHtml.find('.email').val(user.email);
                }
                $('#zutalw-popup-notify').html($formHtml).fadeIn();
                window.isPopupOpen = true;
            },
            error: function() { $('#zutalw-loading').hide(); window.zutalw_custom_alert('Error loading form.'); }
        });
    };
});