// ─── load.js : 全屏 Loading Overlay ─────────────────────────────────────────
// practice.html 載入此檔後會自動彈出全屏 loading。
// 全部資源 load 完後移除 overlay，並呼叫 onAssetsReady() 啟動遊戲。
(function () {
    var ASSETS = [
        // Images........
        { id: "emvlogo",           src: "./assets/images/emvlogo_banner_with_slogan.png" },
        // Sound........
        { id: "button_mouseover",  src: "./assets/sounds/button_mouseover.mp3" },
        { id: "sound_button_click",src: "./assets/sounds/sound_button_click.mp3" },
        { id: "game_bgm2",         src: "./assets/sounds/game_bgm2.mp3" },
        { id: "slide",             src: "./assets/sounds/slide.mp3" },
        { id: "sound_up",          src: "./assets/sounds/sound_up.mp3" },
        { id: "safe_tuning",       src: "./assets/sounds/safe_tuning.mp3" },
        { id: "safe_open",         src: "./assets/sounds/safe_open.mp3" },
        { id: "safe_confirm",      src: "./assets/sounds/safe_confirm.mp3" },
        { id: "sfc_ambulance",     src: "./assets/sounds/sfc_ambulance.mp3" },
        { id: "sfc_hit",           src: "./assets/sounds/sfc_hit.mp3" },
        // Glb........
        { id: "map",           src: "./assets/3d_object/map.glb" }
    ];

    // 建立全屏 overlay
    var style = document.createElement("style");
    style.textContent = [
        "#loadOverlay{position:fixed;inset:0;background:#0a0f1e;z-index:99999;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:28px;font-family:'Segoe UI',Arial,sans-serif;color:#fff}",
        "#loadOverlay .lo-title{font-size:26px;font-weight:700;letter-spacing:3px;color:#c8daff}",
        "#loadOverlay .lo-pct{font-size:52px;font-weight:700;color:#6ab0ff;line-height:1}",
        "#loadOverlay .lo-pct span{font-size:22px;font-weight:400;color:#4a7acc}",
        "#loadOverlay .lo-track{width:420px;height:8px;background:#1a2540;border-radius:4px;overflow:hidden}",
        "#loadOverlay .lo-bar{height:100%;width:0%;background:linear-gradient(90deg,#2a5bd7,#6ab0ff);border-radius:4px;transition:width 0.2s ease}",
        "#loadOverlay .lo-status{font-size:14px;color:#3a5888;letter-spacing:1px;height:20px}"
    ].join("");
    document.head.appendChild(style);

    var overlay = document.createElement("div");
    overlay.id = "loadOverlay";
    overlay.innerHTML = [
        '<div class="lo-title" id="loTitle">載入中</div>',
        '<div class="lo-pct" id="loPct">0<span>%</span></div>',
        '<div class="lo-track"><div class="lo-bar" id="loBar"></div></div>',
        '<div class="lo-status" id="loStatus">載入資源檔...</div>'
    ].join("");

    // DOM ready 後插入 overlay 並開始載入
    document.addEventListener("DOMContentLoaded", function () {
        document.body.appendChild(overlay);

        var queue = new createjs.LoadQueue(true);
        createjs.Sound.alternateExtensions = ["ogg"];
        queue.installPlugin(createjs.Sound);
        queue.maxConnections = 10;

        queue.on("progress", function (e) {
            var pct = Math.round(e.progress * 100);
            document.getElementById("loBar").style.width = pct + "%";
            document.getElementById("loPct").innerHTML = pct + '<span>%</span>';
        });
        queue.on("fileload", function (e) {
            document.getElementById("loStatus").textContent = e.item.id;
        });
        queue.on("complete", function () {
            document.getElementById("loBar").style.width = "100%";
            document.getElementById("loPct").innerHTML = '100<span>%</span>';
            document.getElementById("loStatus").textContent = "載入 3D 模型...";
            
            // 從 ASSETS 篩選 .glb 檔案，並動態建立映射
            var glbAssets = ASSETS.filter(function(item) { return item.src && item.src.endsWith('.glb'); });
            var glbMap = {};
            glbAssets.forEach(function(item) {
                // 'hand_right' → 'rightHand', 'hand_left' → 'leftHand', 其他保持原名
                glbMap[item.id] = item.id.replace(/hand_(.+)/, '$1Hand');
            });
            
            Promise.all(glbAssets.map(function(item) {
                return new Promise(function(resolve, reject) {
                    var loader = new THREE.GLTFLoader();
                    loader.load(item.src, function(gltf) { resolve(gltf); }, undefined, function(err) { reject(err); });
                });
            }))
                .then(function(results) {
                    glbAssets.forEach(function(item, index) {
                        APL[glbMap[item.id]] = results[index].scene;
                        APL[glbMap[item.id]].orignalObject = results[index].scene.clone(); // 保留原始物件以便重置
                    });
                    document.getElementById("loStatus").textContent = "完成！開始遊戲...";
                    setTimeout(function () {
                        overlay.parentNode.removeChild(overlay);
                        if (typeof SceneGame === "function") SceneGame();
                    }, 50);
                })
                .catch(function(err) {
                    console.error("[APL] GLB 載入失敗:", err);
                    document.getElementById("loTitle").textContent = "載入 3D 模型失敗，請重新整理頁面。";
                    document.getElementById("loStatus").textContent = "[APL] GLB 載入失敗:"+err.srcElement.responseURL+" " + err;

                });
        });
        queue.on("error", function (e) {
            console.error("[load.js] 載入失敗:", e.item ? e.item.src : e);
            document.getElementById("loTitle").textContent = "載入 3D 模型失敗，請重新整理頁面。";
            document.getElementById("loStatus").textContent = "[load.js] 載入失敗:" + (e.item ? e.item.src : e);
        });

        queue.loadManifest(ASSETS);
    });
})();

// ─── APL ───────────────────────────────────────────────────────────────
// GLB 物件存放位置：APL.rightHand, APL.leftHand, APL.door1, APL.map
var APL = {};
