// JetKTV 2025 Mobile & Web Client-Side Script

let currentPlayingTitle = "";
let isCurrentlyPaused = false;

// 取得目前播放狀態 (每秒執行)
function getStatus() {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let status = xmlhttp.responseText;
            let parts = status.split("|");
            if (parts.length < 5) return;

            let nowplay = parts[0];   // 目前播放
            let playtime = parts[1];  // 播放時間
            let mode = parts[2];      // 目前模式: 1:導唱 2:伴唱 3:立體聲
            let key = parseInt(parts[3], 10) || 0;       // 目前升降Key
            let volume = parseInt(parts[4], 10) || 0;    // 音樂音量

            // 1. 歌曲標題 & 跑馬燈
            if (!nowplay || nowplay.trim() === "") {
                nowplay = "目前沒有播放的歌曲";
                $('.equalizer-bar').addClass('paused');
            } else {
                if (!isCurrentlyPaused) {
                    $('.equalizer-bar').removeClass('paused');
                }
            }

            if (nowplay !== currentPlayingTitle) {
                currentPlayingTitle = nowplay;
                setMarqueeText(nowplay);
            }

            // 2. 播放時間
            $("#playTime").html("⏱️ " + (playtime || "00:00"));

            // 3. 伴唱模式圖示
            $("#playMode").html("<img src='/images/icon_mode" + mode + ".png' alt='Mode " + mode + "'>");

            // 4. 調性 Key
            let $keyEl = $('#key');
            $keyEl.removeClass('keyup_bg keydown_bg key_bg');
            if (key > 0) {
                $keyEl.addClass('keyup_bg').text("♯ +" + key);
            } else if (key < 0) {
                $keyEl.addClass('keydown_bg').text("♭ " + key);
            } else {
                $keyEl.addClass('key_bg').text("♮ 原調");
            }

            // 5. 音量 Volume
            let volumeHtml = "";
            if (volume <= 0) {
                volumeHtml = "<span style='color:#f87171;'>🔇 靜音</span>";
            } else {
                volumeHtml = "<span>🔊 " + volume + "%</span>";
            }
            $("#volume").html(volumeHtml);
        }
    };
    xmlhttp.open("GET", "dofunc?f=status", true);
    xmlhttp.send();
}

// 取得待播清單 (每 4-5 秒更新)
function getPlaylist(menuContent) {
    if (menuContent) {
        if (menuContent.startsWith("go")) {
            getMenu("main");
            return false;
        }
    }

    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let playlistHtml = xmlhttp.responseText;
            if (playlistHtml !== $('#playList').html()) {
                $("#playList").html(playlistHtml);
                updatePlaylistBadge();
            }
        }
    };
    xmlhttp.open("GET", "dofunc?f=playlist", true);
    xmlhttp.send();
}

// 更新待播清單上的未播數量徽章
function updatePlaylistBadge() {
    let rowCount = $("#playList tr.songlist").length;
    let $badge = $("#playlist-badge");
    if (rowCount > 0) {
        $badge.text(rowCount).show();
    } else {
        $badge.hide();
    }
}

// 取得選單內容
function getMenu(menu) {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let menuContent = xmlhttp.responseText;
            if (menuContent !== "OK") {
                if (menuContent !== $('#menu').html()) {
                    $("#menu").html(menuContent);
                    $("#tab-menu, #menu").animate({ scrollTop: 0 }, 150);
                }
            } else {
                showToast("🎵 已加入待播清單！");
            }

            if (menuContent === "goHome") {
                switchMobileTab("menu");
                getMenu("main");
            }
            if (menuContent === "goList") {
                switchMobileTab("playlist");
            }

            getPlaylist(menuContent);
        }
    };
    xmlhttp.open("GET", "dofunc?f=menu_" + encodeURIComponent(menu), true);
    xmlhttp.send();
}

// 回上一層選單
function menuBack() {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let result = xmlhttp.responseText;
            getMenu(result);
        }
    };
    xmlhttp.open("GET", "dofunc?f=back", true);
    xmlhttp.send();
}

// 執行後端功能 (播放、音量、調性、音效等)
function doFunc(func) {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let resp = xmlhttp.responseText;
            
            // 處理暫停/續播狀態反饋
            if (func === "pause") {
                if (resp === "pause") {
                    isCurrentlyPaused = true;
                    $("#btnPause, #btnPauseCtrl").html("<span class='ctrl-icon'>▶︎</span><span class='ctrl-label'>播放</span>");
                    $('.equalizer-bar').addClass('paused');
                    showToast("⏸︎ 播放已暫停");
                } else {
                    isCurrentlyPaused = false;
                    $("#btnPause, #btnPauseCtrl").html("<span class='ctrl-icon'>⏸︎</span><span class='ctrl-label'>暫停</span>");
                    $('.equalizer-bar').removeClass('paused');
                    showToast("▶︎ 繼續播放");
                }
            } else if (func === "cut") {
                showToast("⏭️ 已切換至下一首歌曲");
            } else if (func === "replay") {
                showToast("🔁 重新播放本曲");
            } else if (func === "stop") {
                showToast("⏹️ 已停止自播");
            } else if (func === "keyup") {
                showToast("♯ 升 1 半音");
            } else if (func === "keydown") {
                showToast("♭ 降 1 半音");
            } else if (func === "keyreset") {
                showToast("♮ 已恢復原調");
            } else if (func === "mode") {
                showToast("🎤 切換導唱 / 伴唱模式");
            } else if (func === "zoom") {
                showToast("📺 切換螢幕顯示比例 (4:3 / 16:9)");
            } else if (func === "volup") {
                showToast("🔊 提高音量");
            } else if (func === "voldown") {
                showToast("🔉 降低音量");
            } else if (func === "volmute") {
                showToast("🔇 切換靜音");
            } else if (func.startsWith("effect_")) {
                showToast("🎉 播放現場歡呼音效");
            }

            getStatus();
            getPlaylist();
        }
    };
    xmlhttp.open("GET", "dofunc?f=" + encodeURIComponent(func), true);
    xmlhttp.send();
}

// 跑馬燈文字設置
function setMarqueeText(text) {
    const container = document.querySelector('#nowPlay');
    const content = document.querySelector('.marquee-content');
    if (!container || !content) return;

    content.textContent = text;
    content.classList.remove('marquee-animate');

    requestAnimationFrame(() => {
        if (content.scrollWidth > container.clientWidth - 40) {
            content.classList.add('marquee-animate');
        }
    });
}

// 搜尋歌曲
function searchSong(mode) {
    let searchStr = $("#searchText").val().trim();
    if (searchStr) {
        doSearch(searchStr, mode);
        showToast("🔍 搜尋：「" + searchStr + "」");
    }
}

// 執行搜尋請求
function doSearch(searchStr, mode) {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let result = xmlhttp.responseText;
            $("#menu").html(result);
            if (mode === "mobi") {
                switchMobileTab("menu");
            }
        }
    };
    xmlhttp.open("GET", "dofunc?f=search_" + encodeURIComponent(searchStr), true);
    xmlhttp.send();
}

// 切換手機版底部頁籤 (menu / playlist / control)
function switchMobileTab(tab) {
    $(".tab-btn").removeClass("active");
    $("#tab-btn-" + tab).addClass("active");

    if (tab === "menu") {
        $("#tab-menu").fadeIn(150);
        $("#tab-playlist").hide();
        $("#tab-control").hide();
    } else if (tab === "playlist") {
        $("#tab-menu").hide();
        $("#tab-playlist").fadeIn(150);
        $("#tab-control").hide();
        getPlaylist();
    } else if (tab === "control") {
        $("#tab-menu").hide();
        $("#tab-playlist").hide();
        $("#tab-control").fadeIn(150);
    }
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// 點擊分類膠囊切換
function selectCategoryPill(btn, category) {
    $(".pill-item").removeClass("active");
    $(btn).addClass("active");
    getMenu(category);
}

// 顯示 Toast 訊息
function showToast(message) {
    let $container = $("#toast-container");
    if ($container.length === 0) {
        $("body").append('<div id="toast-container"></div>');
        $container = $("#toast-container");
    }

    let $toast = $('<div class="toast-msg"><span>✨</span> ' + message + '</div>');
    $container.append($toast);

    setTimeout(() => {
        $toast.addClass('toast-out');
        setTimeout(() => $toast.remove(), 300);
    }, 2200);
}

// 貼上 URL Modal
function openPasteModal() {
    $("#modalUrlInput").val("");
    $("#modal-overlay").css("display", "flex");
    $("#modalUrlInput").focus();
}

function closePasteModal() {
    $("#modal-overlay").hide();
}

function submitPasteModal() {
    let url = $("#modalUrlInput").val().trim();
    if (!url) {
        alert("請輸入有效的影片網址！");
        return;
    }
    if (url.startsWith("http://") || url.startsWith("https://")) {
        doFunc("url_" + encodeURIComponent(url));
        showToast("🎬 已加入網路影片點播！");
        closePasteModal();
        switchMobileTab("playlist");
    } else {
        alert("網址格式不正確，需以 http:// 或 https:// 開頭！");
    }
}
