// =======================================================
//  SKETCH.JS - WP.org Compliant & Multi-Campaign Version
//  FIXED: Dynamic Segments Parsing, Anti-Fraud Identity, & Physics Engine
// =======================================================

const {
    Engine, Render, Runner,
    Composites, Common, MouseConstraint,
    Mouse, Composite, Bodies, Constraint,
    Events, World, Vertices, Body, Renderer
} = Matter;

const Vector = Matter.Vector;

if (Common && typeof Common.setDecomp === 'function' && typeof decomp !== 'undefined') {
    Common.setDecomp(decomp);
}

// Core variables
let bodies;
let acrshapes = [], particles = [], boundaries = [], buts = [];
let initsound = false;
const PARTICLE_SPEED = 0.01;

let canplay = false; 

let w_arc = 450, h_arc = 450; 
let context;
let radius = 0;
let angle = 0;
let speed = 0.06;

let centerX = 300;
let centerY = 300;

let rp = 2;
let rbc = w_arc / 2;

// Win coordinates
let x_win0 = 0, y_win0 = 0;

let winnerFound = false; 

// ===================== GUARD & CONFIG =====================
if (typeof window.ZutalwConfig === 'undefined') {
    if (typeof window.zutalw_Lazy_Assets !== 'undefined' && window.zutalw_Lazy_Assets.config_data) {
         window.ZutalwConfig = window.zutalw_Lazy_Assets.config_data;
    }
}

if (typeof window.ZutalwConfig === 'undefined' || !window.ZutalwConfig.ajax_url) {
    console.error("zutalw Critical Error: 'ZutalwConfig' or 'ajax_url' is missing.");
}

let _plugin_dir = '';
if (window.ZutalwConfig && window.ZutalwConfig.assets_url) {
    _plugin_dir = window.ZutalwConfig.assets_url;
}
if (_plugin_dir && _plugin_dir.slice(-1) !== '/') _plugin_dir += '/';

let config = window.ZutalwConfig && window.ZutalwConfig.getConfig ? window.ZutalwConfig.getConfig : [];
if (typeof config === 'string') {
    try { config = JSON.parse(config); } catch (e) { config = []; }
}

// sounds variables
let ding, touch, win, error, startsound, winsound;
let initial = false;
window.s_rotated = false; 
let valid = 1; 
let _getgift = "";
window.winnerFound = false;
window.canplay = false;

let load = document.getElementsByClassName("zutalw-popup-processing")[0];
let group = Body.nextGroup ? Body.nextGroup(true) : null;
let mode_admin = false;

// default colors
let colodd = "#eff4fb", colevent = "#0564b1", colwin = "#033b70",
    coltextwin = "#ffffff", coltextodd = "#000000", coltexteven = "#ffffff";
let colbut = "#007CBD", coltextbut = "#ffffff", sizetextbut = 16,
    textbut = "SPIN", colbutpress = "#03acf9", coltextpress = "#ffffff";

let _count = 0, _maxc = 3;

// ===================== SOUND SETUP =====================
let _startsound = _plugin_dir + "sound/spinning.mp3";
let _winsound = _plugin_dir + "sound/success.mp3";

if (Array.isArray(config) && config.length > 0 && config[0]) {
    _startsound = config[0].startsound || _startsound;
    _winsound = config[0].winsound || _winsound;
}

function makeSoundStub() {
    return { isPlaying: () => false, play: () => {}, stop: () => {}, setVolume: () => {}, getVolume: () => 1, jump: () => {} };
}

function preload() {
    try {
        if (typeof loadSound === 'function') {
            startsound = loadSound(_startsound, () => {}, (err) => { startsound = makeSoundStub(); });
            winsound = loadSound(_winsound, () => {}, (err) => { winsound = makeSoundStub(); });
        } else { startsound = makeSoundStub(); winsound = makeSoundStub(); }
    } catch (e) { startsound = makeSoundStub(); winsound = makeSoundStub(); }
}

// ===================== CAMPAIGN DETECT =====================
let _idcampain = (window.ZutalwConfig && window.ZutalwConfig.target_campaign_id) ? window.ZutalwConfig.target_campaign_id : 1;
let _license = 0;

let e_game = document.getElementById("area-game");
if (e_game) {
    if (e_game.dataset.id && e_game.dataset.id > 0) _idcampain = e_game.dataset.id;
    _license = e_game.dataset.license || 0;
}

// ===================== MATTER ENGINE =====================
let engine = Engine.create();
let world = engine.world;
let xa = 250, ya = 250, distan = Math.PI/4, loadconfig = false;
let dataconfig = null; 

// ===================== P5 SETUP =====================
function setup() {
    window.setup = setup;
    let container = document.getElementById("area-game");

    if (container) {
        let w = container.offsetWidth || w_default();
        let h = container.offsetHeight || h_default();
        
        canvas = createCanvas(w, h);
        canvas.parent('area-game');
        clear();

        // [FIX] Prefer Localized Config over AJAX if available
        if (!loadconfig) {
            if (config && config.length > 1) {
                console.log("zutalw Debug: Loaded config directly from inline data");
                restart_game(config);
            } else {
                getdatascore(function(data) {
                    console.log("zutalw Debug: Config loaded via fallback AJAX");
                    restart_game(data);
                });
            }
            loadconfig = true;
        }
        
        if (typeof Runner !== 'undefined' && Runner.run) {
            Runner.run(engine);
        }
    }
}

function w_default() {
    let w_device = window.innerWidth > 0 ? window.innerWidth : screen.width;
    return (w_device < 768) ? 300 : 500;
}
function h_default() {
    let w_device = window.innerWidth > 0 ? window.innerWidth : screen.width;
    return (w_device < 768) ? 300 : 500;
}

// ===================== AJAX GET CONFIG =====================
function getdatascore(callback) {
    let http = new XMLHttpRequest();
    let baseAjax = window.ZutalwConfig ? window.ZutalwConfig.ajax_url : null;
    if (!baseAjax) return;

    let url = baseAjax + "?action=zutalw_getdataConfig";
    let params = new URLSearchParams();
    params.append('idcampain', _idcampain);
    params.append('license', _license);
    
    let poolLevel = window.zutalw_current_pool_level || 1;
    params.append('pool_level', poolLevel);

    if (load) load.style.display = "block";
    
    http.open("POST", url, true);
    http.setRequestHeader("Accept", "application/json");
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    
    http.onreadystatechange = function () {
        if (http.readyState === 4) {
            if (http.status === 200) {
                try {
                    let arr = JSON.parse(this.responseText);
                    let finalData = arr;
                    
                    // 🔥 FIX: Bóc tách lớp vỏ bọc JSON do PHP trả về qua AJAX
                    if (arr && arr.length > 0 && typeof arr[0].dataconfig === 'string') {
                        finalData = JSON.parse(arr[0].dataconfig);
                        
                        // Chép biến VIP/Trade-in vào trong mảng dữ liệu thực tế để JS đọc được
                        if (finalData.length > 0 && arr[0].tradein_enabled !== undefined) {
                            finalData[0].tradein_enabled = arr[0].tradein_enabled;
                        }
                    }

                    dataconfig = finalData; 
                    callback(finalData);
                } catch (e) { 
                    console.error('zutalw Error: Invalid JSON Config', e); 
                }
            }
            if (load) load.style.display = "none";
        }
    };
    http.send(params.toString());
}
// ===================== RESTART GAME (FIXED SYNTAX & COLOR) =====================
function restart_game(data) {
    // Dừng âm thanh và reset volume context
    try {
        if (winsound) winsound.stop();
        if (startsound) {
            startsound.stop();
            startsound.setVolume(1.0);
        }
        // Thêm dòng này để đánh thức Audio Context của P5
        if (typeof userStartAudio === 'function') userStartAudio();
    } catch(e) {}

    if (!data || !data.length) return;

    // Deep copy để đảm bảo không bị dính màu cũ
    dataconfig = JSON.parse(JSON.stringify(data)); 
    let response = dataconfig; 

    window.s_rotated = false;
    window.winnerFound = false;
    window.canplay = false;
    speed = 0; 

    if (acrshapes.length > 0) {
        acrshapes.forEach(a => { if(a && a.body) World.remove(world, a.body); });
    }
    acrshapes = []; boundaries = []; buts = [];

    // 🔥 THÊM 2 DÒNG NÀY VÀO ĐÂY ĐỂ HẾT LỖI currentH
    let currentW = w_default();
    let currentH = h_default();

    centerX = currentW / 2;
    centerY = currentH / 2;
    
    let effectiveRadius = (w_arc / 2) * Math.cos(PI / 8); 
    x_win0 = centerX + effectiveRadius; 
    y_win0 = centerY; 
    // ---------------------------------------------

    colodd = response[0].colodd || "#eff4fb";
    colevent = response[0].colevent || "#0564b1";
    colwin = response[0].colwin || "#033b70";

    let totalSlices = response.length - 1;
    distan = (2 * Math.PI) / totalSlices;
    let start = 0;

    for (let i = 0; i < totalSlices; i++) {
        let stop = start + distan;
        let angleBase = start + (distan / 2);
        let xm0 = centerX + Math.cos(angleBase) * (w_arc / 2) * Math.cos(distan / 2);
        let ym0 = centerY + Math.sin(angleBase) * (w_arc / 2) * Math.cos(distan / 2);

        let item = response[i + 1];
        let background = item.bg_color || ((i % 2 === 0) ? colodd : colevent);
        let txtcol = item.text_color || ((i % 2 === 0) ? coltextodd : coltexteven);

        acrshapes.push(new Arcshape(
            xm0, ym0, 10, w_arc, h_arc, start, stop,
            background, '', item.label, i, txtcol, item.image_url, 40, 25, 16
        ));
        start = stop;
    }

    // Sau khi có currentH và currentW, phần này sẽ không còn lỗi nữa
    let params = { isStatic: true };
    boundaries.push(new Boundary(0, currentH / 2, 0.1, currentH, params));
    boundaries.push(new Boundary(currentW, currentH / 2, 0.1, currentH, params));
    boundaries.push(new Boundary(currentW / 2, 0, currentW, 0.1, params));
    boundaries.push(new Boundary(currentW / 2, currentH, currentW, 0.1, params));

    if (valid > 0) {
        buts.push(new Particle(xa, ya, 60, "", "", "", colbut));
    }
    initial = true;
}

// =======================================================
// AJAX SPIN SUBMIT (FIXED DEVICE ID)
// =======================================================

function mousePressed() {
    if (window.isGameLocked === true) return;
    if (window.isPopupOpen === true) return;

    for (let bt of buts) {
        if (bt && typeof bt.clicked === 'function' && bt.clicked() && !window.s_rotated && valid > 0) {
            
                if (window.isCheckingServer) return;

            // --- VIP POOL LOCK LOGIC ---
            let trade_enabled = 0;
            if (dataconfig && dataconfig[0] && dataconfig[0].tradein_enabled !== undefined) {
                trade_enabled = parseInt(dataconfig[0].tradein_enabled);
            } else if (window.ZutalwConfig && window.ZutalwConfig.tradein_enabled !== undefined) {
                trade_enabled = parseInt(window.ZutalwConfig.tradein_enabled);
            }

            // If VIP mode is ON and user hasn't submitted the form -> Block and show form
            if (trade_enabled === 1 && window.zutalw_form_submitted !== true) {
                console.log("[ZutaLW Debug] Wheel is locked. Prompting user for Lead Form.");
                if (typeof window.get_popup === 'function') {
                    window.get_popup('Unlock VIP Pool', 'trade_in', _idcampain);
                }
                return; // Halt execution, do not spin
            }
            // ---------------------------

            const runServerCheck = (recaptchaToken = '') => {
                window.isCheckingServer = true;
                document.body.style.cursor = 'wait';
                
                let ajaxUrl = window.ZutalwConfig ? window.ZutalwConfig.ajax_url : null;
                if (!ajaxUrl) {
                     window.isCheckingServer = false;
                     return;
                }

                // [FIX] Bulletproof way to get Device ID (Anti-fraud)
                let final_device_id = window.zutalw_visitor_id 
                                      || localStorage.getItem('zutalw_fingerprint') 
                                      || window.ZutalwConfig.device_id 
                                      || 'missing_id';

                let data = {
                    action: 'zutalw_get_spin_result', 
                    security: window.ZutalwConfig.nonce,
                    device_id: final_device_id,
                    idcampain: _idcampain,
                    pool_level: window.zutalw_current_pool_level || 1,
                    recaptcha_token: recaptchaToken,
                    license: _license 
                };

                jQuery.ajax({
                    url: ajaxUrl, 
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        window.isCheckingServer = false;
                        document.body.style.cursor = 'default';

                        if (response.success) {
                            console.log("zutalw Debug: Spin Result -> Target Segment:", response.data.segment_id);
                            
                            if (typeof response.data.spins_left !== 'undefined') {
                                window.zutalw_current_spins = response.data.spins_left;
                                jQuery('#zutalw-spins-left').text(response.data.spins_left);
                            }

                            start_physics_spin(response.data.segment_id);

                        } else {
                            console.warn("zutalw Debug: Server Denied - ", response.data ? response.data.message : 'Unknown error');
                            let msg = (response.data && response.data.message) ? response.data.message : "Error processing spin.";
                            
                            // Check for custom notice function first
                            if (typeof zutalw_show_notice === 'function') {
                                zutalw_show_notice(msg);
                            } 
                            // Use the custom popup alert from our trigger.js
                            else if (typeof window.zutalw_custom_alert === 'function') {
                                window.zutalw_custom_alert(msg);
                            } 
                            // Final fallback just in case
                            else {
                                alert(msg);
                            }
                            
                            // Reset wheel state so it doesn't get locked out forever on a failed request
                            window.s_rotated = false;
                            window.canplay = false;
                            if (typeof window.zutalw_reset_wheel_visuals === 'function') {
                                window.zutalw_reset_wheel_visuals();
                            }
                        }
                    },
                    error: function(err) {
                        window.isCheckingServer = false;
                        document.body.style.cursor = 'default';
                        console.error("zutalw Error: Could not connect to server", err);
                    }
                });
            };

            const siteKey = window.ZutalwConfig.recaptcha_site_key;
            if (siteKey && typeof grecaptcha !== 'undefined') {
                grecaptcha.ready(function() {
                    grecaptcha.execute(siteKey, {action: 'spin_wheel'}).then(function(token) {
                        runServerCheck(token);
                    }, function(error) {
                        runServerCheck('');
                    });
                });
            } else {
                runServerCheck('');
            }
            return; 
        }
    }
}

// =======================================================
// DYNAMIC PHYSICS CALCULATION
// =======================================================
function start_physics_spin(targetIndex) {
    if (!dataconfig) return; 
    
    // Đảm bảo dừng hẳn âm thanh cũ và reset volume
    try { 
        if (winsound) winsound.stop();
        if (startsound) {
            startsound.stop();
            startsound.setVolume(1.0); // Ép volume lên 1
        }
    } catch (e) { }

    window.s_rotated = true;
    window.canplay = true;   
    _count++;

    // Bật nhạc quay
    try {
        if (startsound) {
            startsound.play();
        }
    } catch (e) { }

    const friction = 0.0001; 
    const totalSegments = acrshapes.length || 8;
    const segmentAngle = (2 * Math.PI) / totalSegments; 

    let idx = parseInt(targetIndex);
    
    // Validate target bounds
    if(idx < 0 || idx >= totalSegments) idx = 0; 

    const minRounds = 5; 
    const baseDistance = minRounds * 2 * Math.PI;

    // [FIX] Physics angle calculation adapted for dynamic slice count
    let currentTargetAngle = (segmentAngle / 2) + (idx * segmentAngle);
    let noise = (Math.random() * (segmentAngle * 0.8)) - (segmentAngle * 0.4); 
    
    let targetRotation = (2 * Math.PI) - currentTargetAngle + noise;
    let totalDistance = baseDistance + targetRotation;

    let calculatedSpeed = Math.sqrt(2 * friction * totalDistance);

    speed = calculatedSpeed;
    console.log(`zutalw Physics: Segment ${idx}, T_Dist ${totalDistance.toFixed(2)}, Speed ${speed.toFixed(5)}`);
}

// ===================== DRAW LOOP (FIXED STOP LOGIC) =====================
function draw() {
    window.draw = draw;
    if (!document.getElementById("area-game")) return false;
    clear();
    
    // 1. XỬ LÝ MA SÁT
    if (window.canplay === true && speed > 0) {
        speed -= 0.0001; 

        // Fade out âm thanh quay
        if (startsound && startsound.isPlaying()) {
            if (speed > 0.02) {
                startsound.setVolume(1.0);
            } else {
                let vol = map(speed, 0.0003, 0.02, 0, 1.0);
                startsound.setVolume(vol);
            }
        }
    }

    // 2. CHỐT DỪNG VẬT LÝ
    if (speed <= 0.0003 && speed !== 0 && window.canplay === true) {
        speed = 0;
        try { if (startsound) startsound.stop(); } catch (e) {}
    }

    // 3. HIỂN THỊ
    acrshapes.forEach(a => {
        if (a && typeof a.update === 'function') a.update();
        if (a && typeof a.show === 'function') a.show();
    });

    // 4. LOGIC THẮNG CUỘC (SỬA LẠI ĐỂ CHẠY ÂM THANH CHUẨN)
    if (speed === 0 && !window.winnerFound && initial && window.canplay && acrshapes.length > 0) {
        window.winnerFound = true; 
        
        let minDistance = 999999;
        let winningSlice = null;

        acrshapes.forEach(a => {
            let d = Math.sqrt(Math.pow(a.x - x_win0, 2) + Math.pow(a.y - y_win0, 2));
            if (d < minDistance) {
                minDistance = d;
                winningSlice = a;
            }
        });

        if (winningSlice) {
            // 1. Dừng nhạc quay ngay lập tức
            if (startsound) startsound.stop();

            // 2. Phát nhạc thắng với cơ chế an toàn
            setTimeout(() => {
                try {
                    if (winsound) {
                        winsound.setVolume(1.0);
                        winsound.play();
                        console.log("[ZutaLW Sound] Winning sound triggered after delay.");
                    }
                } catch(e) { console.error("Sound Error:", e); }
            }, 50); // Trễ 50ms để thoát khỏi loop vật lý

            // 3. Kích hoạt hiệu ứng thắng (đổi màu ô) và hiện Popup
            if (typeof winningSlice.triggerWin === 'function') {
                winningSlice.triggerWin();
            }
            
            window.canplay = false;
        }
    }

    boundaries.forEach(b => { if (b && typeof b.show === 'function') b.show(); });
    buts.forEach(bt => { if (bt && typeof bt.show === 'function') bt.show(); });

    try { Engine.update(engine); } catch (e) {}
}
// ===================== SAFE SOUND LOADING =====================
function loadsound() {
    try {
        if (typeof p5 !== 'undefined' && p5 && typeof p5.SoundFile === 'function') {
            try { ding  = new p5.SoundFile(_plugin_dir + "sound/ding.mp3"); } catch (e) { ding = makeSoundStub(); }
            try { touch = new p5.SoundFile(_plugin_dir + "sound/touch1.mp3"); } catch (e) { touch = makeSoundStub(); }
            try { win = new p5.SoundFile(_plugin_dir + "sound/win1.mp3"); } catch (e) { win = makeSoundStub(); }
            try { error = new p5.SoundFile(_plugin_dir + "sound/error.mp3"); } catch (e) { error = makeSoundStub(); }
        } else { ding = touch = win = error = makeSoundStub(); }
    } catch (e) { ding = touch = win = error = makeSoundStub(); }
}

document.body.addEventListener("mouseover", function () { if (!initsound) { loadsound(); initsound = true; } }, { once: true });
document.body.addEventListener("touchstart", function () { if (!initsound) { loadsound(); initsound = true; } }, { once: true });

window.getdatascore = getdatascore;
window.restart_game = restart_game;

// Hàm để các file JS khác gọi khi đóng Popup trúng thưởng
window.zutalw_reset_wheel_visuals = function() {
    window.s_rotated = false;
    window.winnerFound = false;
    window.canplay = false;
    speed = 0;

    // Reset trạng thái từng ô về ban đầu
    if (acrshapes && acrshapes.length > 0) {
        acrshapes.forEach(a => {
            a.win = false;
            // Trả lại màu gốc (đã được lưu trong constructor của Arcshape mới)
            if (typeof a.initialBackground !== 'undefined') {
                a.currentBackground = a.initialBackground;
            }
        });
    }
    console.log("[ZutaLW Debug] Wheel visuals and states have been reset.");
};