var importCloudEnabled = false;
var importDgEnabled = false;
var currentQid = 0;
var qrTimer = null;
var qrsig = '';
var loginMode = 'add';
var loginTargetQid = 0;
var loginTargetQQ = '';
var loginCanCloudSync = false;
var logDataRaw = [];
var logMetaRaw = null;
var qzScrollTop = 0;
var qzScrollLockCount = 0;
var qzoneNodeList = [];

function initQzone(cloudEnabled, dgEnabled) {
    importCloudEnabled = cloudEnabled;
    importDgEnabled = dgEnabled;
}

function showToast(msg, duration) {
    duration = duration || 2500;
    var id = 'toast_' + Date.now();
    var el = document.createElement('div');
    el.id = id;
    el.className = 'px-5 py-2.5 bg-gray-800 text-white text-sm rounded-xl shadow-lg animate-fade-in';
    el.style.maxWidth = '92vw';
    el.style.wordBreak = 'break-word';
    el.style.overflowWrap = 'anywhere';
    el.style.whiteSpace = 'normal';
    el.style.textAlign = 'center';
    el.textContent = msg;
    var wrap = document.getElementById('toastWrap');
    if (wrap) wrap.appendChild(el);
    setTimeout(function() {
        var target = document.getElementById(id);
        if (target) {
            target.style.transition = 'opacity 0.3s';
            target.style.opacity = '0';
            setTimeout(function() { if (target.parentNode) target.parentNode.removeChild(target); }, 300);
        }
    }, duration);
}

function lockPageScroll() {
    if (qzScrollLockCount === 0) {
        qzScrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
        document.body.style.position = 'fixed';
        document.body.style.top = '-' + qzScrollTop + 'px';
        document.body.style.left = '0';
        document.body.style.right = '0';
        document.body.style.width = '100%';
        document.body.style.overflow = 'hidden';
        document.documentElement.style.overflow = 'hidden';
    }
    qzScrollLockCount++;
}

function unlockPageScroll() {
    if (qzScrollLockCount > 0) qzScrollLockCount--;
    if (qzScrollLockCount === 0) {
        document.body.style.position = '';
        document.body.style.top = '';
        document.body.style.left = '';
        document.body.style.right = '';
        document.body.style.width = '';
        document.body.style.overflow = '';
        document.documentElement.style.overflow = '';
        window.scrollTo(0, qzScrollTop);
    }
}

function loadLoginNodes() {
    $.get('ajax_qzone.php?act=get_qzone_nodes', function(res) {
        if (res.code === 1) {
            var sel = document.getElementById('login_node');
            var mainName = (res.main_name && String(res.main_name).trim()) ? String(res.main_name).trim() : '主站';
            var mainEnabled = (res.main_enabled === undefined) ? 1 : (parseInt(res.main_enabled, 10) ? 1 : 0);
            var mainSort = (res.main_sort === undefined || res.main_sort === null || res.main_sort === '') ? 0 : (parseInt(res.main_sort, 10) || 0);

            qzoneNodeList = (res.nodes && res.nodes.length > 0) ? res.nodes : [];

            var items = [];
            if (mainEnabled) {
                items.push({ value: '0', label: mainName, sort: mainSort, isMain: true });
            }
            qzoneNodeList.forEach(function(n, i) {
                var s = (n && n.sort !== undefined && n.sort !== null && n.sort !== '') ? (parseInt(n.sort, 10) || 0) : 0;
                items.push({ value: String(i + 1), label: (n && n.name) ? n.name : ('节点' + (i + 1)), sort: s, isMain: false });
            });

            items.sort(function(a, b) {
                if (a.sort === b.sort) {
                    if (a.isMain === b.isMain) return 0;
                    return a.isMain ? -1 : 1;
                }
                return a.sort < b.sort ? -1 : 1;
            });

            sel.innerHTML = '';
            items.forEach(function(it) {
                sel.appendChild(new Option(String(it.label).replace(/</g, '&lt;'), it.value));
            });

            if (items.length > 0) {
                document.getElementById('login_node_wrap').classList.remove('hidden');
            } else {
                document.getElementById('login_node_wrap').classList.add('hidden');
            }
        } else {
            qzoneNodeList = [];
            document.getElementById('login_node_wrap').classList.add('hidden');
        }
    }, 'json');
}
function getLoginNodeIndex() {
    var sel = document.getElementById('login_node');
    return sel ? parseInt(sel.value, 10) || 0 : 0;
}
function showLoginModal() {
    loginMode = 'add';
    loginTargetQid = 0;
    loginTargetQQ = '';
    loginCanCloudSync = false;
    isSmsMode = false;
    currentEncryptedP = '';
    currentVcode = '';
    currentSmsTicket = '';
    document.getElementById('sms_container').classList.add('hidden');
    document.getElementById('pwd_pwd').value = '';
    document.getElementById('pwd_sms').value = '';
    document.getElementById('pwd_submit_btn').innerHTML = '开始';

    document.getElementById('login_modal_title').innerText = '添加QQ账号';
    document.getElementById('login_modal_tip').innerText = '请选择方式添加账号';
    updateLoginModalCloudButton();
    document.getElementById('login_modal').classList.remove('hidden');
    document.getElementById('login_modal').classList.add('flex');
    lockPageScroll();
    loadLoginNodes();
    switchLoginTab('qr');
}

function showUpdateLoginModal(qid, qq, canCloudSync) {
    loginMode = 'update';
    loginTargetQid = parseInt(qid, 10) || 0;
    loginTargetQQ = String(qq || '');
    loginCanCloudSync = !!canCloudSync;
    isSmsMode = false;
    currentEncryptedP = '';
    currentVcode = '';
    currentSmsTicket = '';
    document.getElementById('sms_container').classList.add('hidden');
    document.getElementById('pwd_pwd').value = '';
    document.getElementById('pwd_sms').value = '';
    document.getElementById('pwd_submit_btn').innerHTML = '开始';

    document.getElementById('login_modal_title').innerText = '更新QQ状态';
    document.getElementById('login_modal_tip').innerText = '请选择方式更新状态';
    updateLoginModalCloudButton();
    document.getElementById('login_modal').classList.remove('hidden');
    document.getElementById('login_modal').classList.add('flex');
    lockPageScroll();
    loadLoginNodes();
    switchLoginTab('qr');
}

function updateLoginModalCloudButton() {
    var wrap = document.getElementById('login_modal_cloud_wrap');
    if (!wrap) return;
    if (loginMode === 'update' && loginTargetQid > 0 && loginCanCloudSync) {
        wrap.classList.remove('hidden');
    } else {
        wrap.classList.add('hidden');
    }
}

function syncCloudStatusFromModal() {
    if (!(loginMode === 'update' && loginTargetQid > 0 && loginCanCloudSync)) return;
    var btn = document.getElementById('login_modal_cloud_btn');
    if (!btn) return;
    var oldHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>更新中...';
    $.get('ajax_qzone.php?act=get_cloud_cookie&qid=' + loginTargetQid, function(res) {
        btn.disabled = false;
        btn.innerHTML = oldHtml;
        if (res.code === 1) {
            showToast(res.msg || '云端更新成功');
            setTimeout(function() { location.reload(); }, 800);
        } else {
            showToast(res.msg || '云端更新失败');
        }
    }, 'json').fail(function() {
        btn.disabled = false;
        btn.innerHTML = oldHtml;
        showToast('网络错误');
    });
}

function hideLoginModal() {
    var modal = document.getElementById('login_modal');
    modal.style.transition = 'opacity 0.15s';
    modal.style.opacity = '0';
    setTimeout(function() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        modal.style.opacity = '';
        unlockPageScroll();
    }, 150);
    if (qrTimer) clearInterval(qrTimer);
}

function showImportCkModal() {
    document.getElementById('import_cookie').value = '';
    document.getElementById('import_batch_data').value = '';
    document.getElementById('import_batch_mode').checked = false;
    document.getElementById('import_batch_progress').classList.add('hidden');
    document.getElementById('batch_result_msg').innerHTML = '';
    toggleBatchMode();
    document.getElementById('import_ck_modal').classList.remove('hidden');
    document.getElementById('import_ck_modal').classList.add('flex');
    lockPageScroll();
}

function hideImportCkModal() {
    var modal = document.getElementById('import_ck_modal');
    modal.style.transition = 'opacity 0.15s';
    modal.style.opacity = '0';
    setTimeout(function() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        modal.style.opacity = '';
        unlockPageScroll();
    }, 150);
}

function toggleBatchMode() {
    var isBatch = document.getElementById('import_batch_mode').checked;
    if (isBatch) {
        document.getElementById('import_single_mode').classList.add('hidden');
        document.getElementById('import_batch_mode_content').classList.remove('hidden');
    } else {
        document.getElementById('import_single_mode').classList.remove('hidden');
        document.getElementById('import_batch_mode_content').classList.add('hidden');
    }
}

var batchImportData = [];
var batchImportIndex = 0;
var batchImportSuccess = 0;
var batchImportFail = 0;

function getAvailableImportSources() {
    var list = [];
    if (importCloudEnabled) list.push('cloud');
    if (importDgEnabled) list.push('dg');
    return list;
}

function getDefaultImportSourceType() {
    var list = getAvailableImportSources();
    return list.length > 0 ? list[0] : '';
}

function showImportSourceModal() {
    var availableSources = getAvailableImportSources();
    if (availableSources.length === 0) {
        showToast('当前没有可用的账号来源');
        return;
    }
    var typeSel = document.getElementById('import_src_type');
    if (typeSel) {
        var currentType = String(typeSel.value || '');
        if (availableSources.indexOf(currentType) === -1) {
            currentType = getDefaultImportSourceType();
        }
        typeSel.value = currentType;
    }
    var typeWrap = document.getElementById('import_src_type_wrap');
    if (typeWrap) {
        if (availableSources.length <= 1) typeWrap.classList.add('hidden');
        else typeWrap.classList.remove('hidden');
    }
    resetImportSourceUI();
    document.getElementById('import_src_modal').classList.remove('hidden');
    document.getElementById('import_src_modal').classList.add('flex');
    lockPageScroll();
    loadImportSourceList();
}

function hideImportSourceModal() {
    var modal = document.getElementById('import_src_modal');
    modal.style.transition = 'opacity 0.15s';
    modal.style.opacity = '0';
    setTimeout(function() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        modal.style.opacity = '';
        unlockPageScroll();
    }, 150);
}

function getImportSourceType() {
    var availableSources = getAvailableImportSources();
    if (availableSources.length === 1) {
        return availableSources[0];
    }
    var typeSel = document.getElementById('import_src_type');
    var t = typeSel ? String(typeSel.value || getDefaultImportSourceType()) : getDefaultImportSourceType();
    if (t === 'dg' && importDgEnabled) return 'dg';
    if (t === 'cloud' && importCloudEnabled) return 'cloud';
    return getDefaultImportSourceType();
}

function resetImportSourceUI() {
    var sel = document.getElementById('import_src_qq');
    if (sel) sel.innerHTML = '<option value="">加载中...</option>';
    var type = getImportSourceType();
    document.getElementById('import_src_qq_label').innerText = (type === 'dg') ? '选择代挂QQ' : '选择云端QQ';
    document.getElementById('import_src_hint').innerText = (type === 'dg') ? '正在加载代挂QQ列表...' : '正在加载云端QQ列表...';
}

function onImportSourceTypeChange() {
    resetImportSourceUI();
    loadImportSourceList();
}

function loadImportSourceList() {
    var type = getImportSourceType();
    var act = (type === 'dg') ? 'get_dg_qq_options' : 'get_cloud_qq_options';
    $.get('ajax_qzone.php?act=' + act, function(res) {
        var sel = document.getElementById('import_src_qq');
        if (res.code !== 1 || !Array.isArray(res.data)) {
            sel.innerHTML = '<option value="">暂无可选QQ</option>';
            document.getElementById('import_src_hint').innerText = res.msg || ((type === 'dg') ? '未获取到代挂账号' : '未获取到云端账号');
            return;
        }
        sel.innerHTML = '<option value="">请选择QQ</option>';
        res.data.forEach(function(item) {
            var qq = String(item.qq || '');
            var nickname = String(item.nickname || '');
            var label = qq + (nickname ? '（' + nickname + '）' : '');
            var opt = new Option(label, item.id);
            sel.appendChild(opt);
        });
        document.getElementById('import_src_hint').innerText = (type === 'dg') ? '可直接选择代挂QQ导入到秒赞版' : '可直接选择云端QQ导入到秒赞版';
    }, 'json').fail(function() {
        var sel = document.getElementById('import_src_qq');
        sel.innerHTML = '<option value="">暂无可选QQ</option>';
        document.getElementById('import_src_hint').innerText = '网络错误，加载失败';
    });
}

function submitImportSourceQQ() {
    var type = getImportSourceType();
    var id = parseInt(document.getElementById('import_src_qq').value || '0', 10);
    if (!id) {
        showToast((type === 'dg') ? '请选择代挂QQ' : '请选择云端QQ');
        return;
    }
    var btn = document.querySelector('#import_src_modal button[onclick="submitImportSourceQQ()"]');
    var originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>导入中...';
    btn.disabled = true;
    var act = (type === 'dg') ? 'import_dg_qq' : 'import_cloud_qq';
    var payload = (type === 'dg') ? {dg_id: id} : {cloud_id: id};
    $.post('ajax_qzone.php?act=' + act, payload, function(res) {
        btn.innerHTML = originalText;
        btn.disabled = false;
        if (res.code === 0) {
            showToast(res.msg || '导入成功', 4000);
            setTimeout(function() {
                hideImportSourceModal();
                location.reload();
            }, 1000);
        } else {
            showToast(res.msg || '导入失败');
        }
    }, 'json').fail(function() {
        btn.innerHTML = originalText;
        btn.disabled = false;
        showToast('网络错误');
    });
}

function submitImportCk() {
    var isBatch = document.getElementById('import_batch_mode').checked;

    if (isBatch) {
        var batchDataStr = document.getElementById('import_batch_data').value.trim();
        if (!batchDataStr) {
            showToast('请输入批量导入数据');
            return;
        }

        var lines = batchDataStr.split('\n');
        batchImportData = [];

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i].trim();
            if (!line) continue;

            var parts = line.split('----');
            if (parts.length >= 2) {
                var qq = parts[0].trim();
                var cookie = parts.slice(1).join('----').trim();

                if (/^\d{5,11}$/.test(qq) && cookie) {
                    if (cookie.indexOf('skey=') === -1 || cookie.indexOf('p_skey=') === -1) {
                        addBatchResultMsg('<span class="text-red-500">Cookie缺少skey/p_skey跳过: ' + line + '</span>');
                        continue;
                    }
                    batchImportData.push({qq: qq, cookie: cookie});
                } else {
                    addBatchResultMsg('<span class="text-red-500">格式错误跳过: ' + line + '</span>');
                }
            } else {
                var cookieOnly = line;
                if (cookieOnly) {
                    if (/^\d{5,11}$/.test(cookieOnly)) {
                        addBatchResultMsg('<span class="text-red-500">格式错误跳过: ' + line + '</span>');
                        continue;
                    }
                    if (cookieOnly.indexOf('skey=') === -1 || cookieOnly.indexOf('p_skey=') === -1) {
                        addBatchResultMsg('<span class="text-red-500">Cookie缺少skey/p_skey跳过: ' + line + '</span>');
                        continue;
                    }
                    if (!/(?:^|;\s*)(?:uin|p_uin|pt2gguin)\s*=\s*o?\d{5,11}(?:;|$)/i.test(cookieOnly)) {
                        addBatchResultMsg('<span class="text-red-500">Cookie未包含QQ号(uin/p_uin/pt2gguin)跳过: ' + line + '</span>');
                        continue;
                    }
                    batchImportData.push({qq: '', cookie: cookieOnly});
                } else {
                    addBatchResultMsg('<span class="text-red-500">格式错误跳过: ' + line + '</span>');
                }
            }
        }

        if (batchImportData.length === 0) {
            showToast('没有解析到有效的账号数据');
            return;
        }

        batchImportIndex = 0;
        batchImportSuccess = 0;
        batchImportFail = 0;

        document.getElementById('import_batch_progress').classList.remove('hidden');
        document.getElementById('batch_result_msg').innerHTML = '';

        var btn = document.querySelector('#import_ck_modal button[onclick="submitImportCk()"]');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>导入中...';

        processNextBatchItem();

    } else {
        var cookie = document.getElementById('import_cookie').value.trim();

        if (!cookie) {
            showToast('请输入Cookie');
            return;
        }
        if (cookie.indexOf('skey=') === -1 || cookie.indexOf('p_skey=') === -1) {
            showToast('Cookie缺少skey/p_skey');
            return;
        }
        if (!/(?:^|;\s*)(?:uin|p_uin|pt2gguin)\s*=\s*o?\d{5,11}(?:;|$)/i.test(cookie)) {
            showToast('Cookie中未找到QQ号(uin/p_uin/pt2gguin)');
            return;
        }

        var btn = document.querySelector('#import_ck_modal button[onclick="submitImportCk()"]');
        var originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>保存中...';
        btn.disabled = true;

        $.post('ajax_qzone.php?act=import_ck', {
            cookie: cookie
        }, function(res) {
            btn.innerHTML = originalText;
            btn.disabled = false;
            if (res.code === 0) {
                var okMsg = 'CK导入成功';
                if (res.qq) okMsg += ' (QQ: ' + res.qq + ')';
                showToast(okMsg, 4000);
                setTimeout(function() {
                    hideImportCkModal();
                    location.reload();
                }, 2000);
            } else {
                showToast(res.msg || '导入失败');
            }
        }, 'json').fail(function() {
            btn.innerHTML = originalText;
            btn.disabled = false;
            showToast('网络错误');
        });
    }
}

function processNextBatchItem() {
    if (batchImportIndex >= batchImportData.length) {
        var btn = document.querySelector('#import_ck_modal button[onclick="submitImportCk()"]');
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check mr-1"></i>导入完成';

        var msg = '批量导入完成！成功: ' + batchImportSuccess + '，失败: ' + batchImportFail;
        showToast(msg, 4000);
        addBatchResultMsg('<span class="text-green-600 font-bold">=> ' + msg + '</span>');

        setTimeout(function() {
            if (batchImportSuccess > 0) {
                location.reload();
            }
        }, 2000);
        return;
    }

    var item = batchImportData[batchImportIndex];
    var currentNum = batchImportIndex + 1;
    var totalNum = batchImportData.length;
    var percent = Math.floor((currentNum / totalNum) * 100);

    document.getElementById('batch_progress_text').innerText = currentNum + '/' + totalNum;
    document.getElementById('batch_progress_percent').innerText = percent + '%';
    document.getElementById('batch_progress_bar').style.width = percent + '%';

    addBatchResultMsg('正在导入: ' + (item.qq ? ('QQ: ' + item.qq) : '自动识别QQ') + ' ...');

    $.post('ajax_qzone.php?act=import_ck', {
        qq: item.qq,
        cookie: item.cookie
    }, function(res) {
        if (res.code === 0) {
            batchImportSuccess++;
            var okQQ = res.qq || item.qq || '';
            addBatchResultMsg('<span class="text-green-500">' + (okQQ ? ('QQ: ' + okQQ + ' ') : '') + '导入成功 (' + (res.nickname || '未获取昵称') + ')</span>');
        } else {
            batchImportFail++;
            var failQQ = item.qq ? ('QQ: ' + item.qq + ' ') : '';
            addBatchResultMsg('<span class="text-red-500">' + failQQ + '导入失败: ' + (res.msg || '未知错误') + '</span>');
        }
        batchImportIndex++;
        setTimeout(processNextBatchItem, 500);
    }, 'json').fail(function() {
        batchImportFail++;
        var failQQ = item.qq ? ('QQ: ' + item.qq + ' ') : '';
        addBatchResultMsg('<span class="text-red-500">' + failQQ + '导入失败: 网络错误</span>');
        batchImportIndex++;
        setTimeout(processNextBatchItem, 500);
    });
}

function addBatchResultMsg(html) {
    var container = document.getElementById('batch_result_msg');
    container.innerHTML += '<div>' + html + '</div>';
    container.scrollTop = container.scrollHeight;
}

function getQRCode() {
    var node = getLoginNodeIndex();
    var url = 'ajax_qzone.php?act=get_qrcode' + (node > 0 ? '&node=' + node : '');
    $.get(url, function(res) {
        if (res.code === 0) {
            qrsig = res.qrsig;
            document.getElementById('qr_img_wrap').innerHTML =
                '<img src="data:image/png;base64,' + res.image + '" class="w-48 h-48 mx-auto border">';
            if (qrTimer) clearInterval(qrTimer);
            qrTimer = setInterval(checkQRLogin, 2000);
        } else {
            document.getElementById('qr_img_wrap').innerHTML = '<p class="text-red-500">' + res.msg + '</p>';
        }
    }, 'json');
}

function checkQRLogin() {
    var data = {qrsig: qrsig};
    if (loginMode === 'update' && loginTargetQid > 0) {
        data.update_qid = loginTargetQid;
    }
    var node = getLoginNodeIndex();
    if (node > 0) data.node = node;
    $.post('ajax_qzone.php?act=check_qrlogin', data, function(res) {
        if (res.code === 0) {
            clearInterval(qrTimer);
            showToast(res.msg || '登录成功');
            hideLoginModal();
            setTimeout(function() { location.reload(); }, 1000);
        } else if (res.code === 1) {
            clearInterval(qrTimer);
            document.getElementById('qr_img_wrap').innerHTML =
                '<p class="text-red-500">二维码已过期</p><button onclick="getQRCode()" class="mt-2 text-blue-600">点击刷新</button>';
        } else if (res.code === 3) {
            document.getElementById('qr_img_wrap').innerHTML =
                '<p class="text-blue-500">请在手机上确认登录</p>';
        } else if (res.code < 0) {
            clearInterval(qrTimer);
            showToast(res.msg || '登录失败');
            document.getElementById('qr_img_wrap').innerHTML =
                '<p class="text-red-500">' + (res.msg || '登录失败') + '</p><button onclick="getQRCode()" class="mt-2 text-blue-600">点击重新扫码</button>';
        }
    }, 'json');
}

function refreshQR() {
    if (qrTimer) clearInterval(qrTimer);
    document.getElementById('qr_img_wrap').innerHTML = '<p class="text-gray-500">正在获取二维码...</p>';
    getQRCode();
}

function switchLoginTab(tab) {
    var tabQr = document.getElementById('tab_qr');
    var tabPwd = document.getElementById('tab_pwd');
    var qrBox = document.getElementById('qr_container');
    var pwdBox = document.getElementById('pwd_container');
    var qrBtn = document.getElementById('qr_refresh_btn');
    var nodeWrap = document.getElementById('login_node_wrap');

    if (tab === 'qr') {
        tabQr.classList.add('bg-gray-100');
        tabPwd.classList.remove('bg-gray-100');
        qrBox.classList.remove('hidden');
        pwdBox.classList.add('hidden');
        qrBtn.classList.remove('hidden');
        if (qzoneNodeList && qzoneNodeList.length > 0) {
            nodeWrap.classList.remove('hidden');
        }
        if (loginMode === 'update' && loginTargetQQ) {
            document.getElementById('pwd_qq').value = loginTargetQQ;
        }
        refreshQR();
    } else {
        tabPwd.classList.add('bg-gray-100');
        tabQr.classList.remove('bg-gray-100');
        if (qrTimer) { clearInterval(qrTimer); qrTimer = null; }
        qrBox.classList.add('hidden');
        pwdBox.classList.remove('hidden');
        qrBtn.classList.add('hidden');
        if (qzoneNodeList && qzoneNodeList.length > 0) {
            nodeWrap.classList.remove('hidden');
        }
        if (loginMode === 'update' && loginTargetQQ) {
            document.getElementById('pwd_qq').value = loginTargetQQ;
        }
    }
}

function sendSmsCode() {
    var qq = (document.getElementById('pwd_qq').value || '').trim();
    var btn = document.getElementById('sms_send_btn');
    var old = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '发送中...';

    var node = getLoginNodeIndex();
    $.post('ajax_qzone.php?act=send_sms_web', {qq: qq, node: node}, function(res) {
        if (res.code === 0) {
            showToast('短信验证码已发送');
            var time = 60;
            var timer = setInterval(function() {
                if (time <= 0) {
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = '获取验证码';
                } else {
                    btn.innerHTML = time + 's';
                    time--;
                }
            }, 1000);
        } else {
            showToast(res.msg || '发送失败');
            btn.disabled = false;
            btn.innerHTML = old;
        }
    }, 'json').fail(function() {
        showToast('网络错误');
        btn.disabled = false;
        btn.innerHTML = old;
    });
}

var currentEncryptedP = '';
var currentVcode = '';
var isSmsMode = false;
var currentSmsTicket = '';

function submitPwdFlow() {
    var qq = (document.getElementById('pwd_qq').value || '').trim();
    var pwd = document.getElementById('pwd_pwd').value || '';
    var sms = (document.getElementById('pwd_sms').value || '').trim();

    if (!/^\d{5,11}$/.test(qq)) {
        showToast('请输入正确QQ');
        return;
    }

    if (isSmsMode && sms && currentEncryptedP && currentVcode) {
        finalizeLogin(qq, currentEncryptedP, currentVcode, sms);
        return;
    }

    if (!pwd) {
        showToast('请输入密码');
        return;
    }

    var node = getLoginNodeIndex();

    var btn = document.getElementById('pwd_submit_btn');
    var old = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>处理中...';

    $.post('ajax_qzone.php?act=init_pwd_web', {qq: qq, node: node}, function(res) {
        if (res && res.code === 2) {
            btn.disabled = false; btn.innerHTML = old;
            var cap_url = 'cap_frame_sdk.php?vcode=' + res.vcode + '&qq=' + qq + '&sid=' + (res.sid || '') + '&v=' + Math.random();

            window.getticket = function(verifyData) {
                hideCapModal();
                if (verifyData && verifyData.ticket && verifyData.randstr) {
                    currentVcode = verifyData.randstr.toUpperCase();
                    showToast('验证成功，正在登录...');
                    startEncryptFlow(qq, pwd, currentVcode, res.uin_hex, verifyData.ticket);
                }
            };

            document.getElementById('cap_modal_body').innerHTML = '<iframe src="' + cap_url + '" class="w-full h-[360px] border-0" id="cap_iframe"></iframe>';
            document.getElementById('cap_modal').classList.remove('hidden');
            lockPageScroll();
            return;
        }

        if (!(res && res.code === 1)) {
            showToast((res && res.msg) ? res.msg : '初始化失败');
            btn.disabled = false; btn.innerHTML = old;
            return;
        }

        currentVcode = res.vcode;
        startEncryptFlow(qq, pwd, res.vcode, res.uin_hex, '');

    }, 'json').fail(function(){
        showToast('网络错误');
        btn.disabled = false; btn.innerHTML = old;
    });
}

function startEncryptFlow(qq, pwd, vcode, uin_hex, ticket) {
    var btn = document.getElementById('pwd_submit_btn');
    var old = '开始';
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>加密中...';

    var ifr = document.getElementById('qzone_pwd_iframe');
    if (!ifr) {
        ifr = document.createElement('iframe');
        ifr.id = 'qzone_pwd_iframe';
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
    }

    var encryptTimeout = setTimeout(function(){
        window.removeEventListener('message', onReady);
        window.removeEventListener('message', onEncrypted);
        showToast('加密组件加载超时，请重试');
        btn.disabled = false; btn.innerHTML = old;
    }, 15000);

    function onReady(ev){
        if (ev && ev.data && ev.data.type === 'qzone_pwd_ready') {
            window.removeEventListener('message', onReady);
            var payload = {type:'qzone_pwd_params', qq: qq, pwd: pwd, vcode: vcode, uin_hex: uin_hex};
            if (ifr.contentWindow) {
                ifr.contentWindow.postMessage(payload, '*');
            }
        }
    }
    window.addEventListener('message', onReady);

    function onEncrypted(ev){
        var d = ev.data || {};
        if (d.type !== 'pwd_encrypted') return;
        window.removeEventListener('message', onEncrypted);
        clearTimeout(encryptTimeout);

        if (!(d.ok && d.p)) {
            showToast('加密失败：' + (d.msg || ''));
            btn.disabled = false; btn.innerHTML = old;
            return;
        }

        currentEncryptedP = d.p;
        if (ticket) {
            finalizeLogin(qq, d.p, vcode, '', ticket);
        } else {
            finalizeLogin(qq, d.p, vcode, '', '');
        }
    }
    window.addEventListener('message', onEncrypted);

    ifr.src = 'qzone_pwd_sdk.php?r=' + Math.random();
}

function finalizeLogin(qq, p, vcode, sms, ticket) {
    var btn = document.getElementById('pwd_submit_btn');
    var defaultText = isSmsMode ? '验证并登录' : '开始';
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>提交中...';

    var node = getLoginNodeIndex();
    var ps = {qq: qq, p: p, vcode: vcode, node: node};
    if (sms) {
        ps.sms_code = sms;
        ps.sms_ticket = currentSmsTicket;
    }
    if (ticket) ps.ticket = ticket;
    if (loginMode === 'update' && loginTargetQid > 0) ps.update_qid = loginTargetQid;

    $.post('ajax_qzone.php?act=finalize_pwd_web', ps, function(x) {
        btn.disabled = false;

        if (x && x.code === 0) {
            showToast(x.msg || '登录成功');
            setTimeout(function(){ hideLoginModal(); location.reload(); }, 800);
        } else if (x && x.code === 10009) {
            isSmsMode = true;
            currentSmsTicket = x.sms_ticket || '';
            showToast(x.msg);
            document.getElementById('sms_container').classList.remove('hidden');
            document.getElementById('sms_label').innerText = x.msg;
            btn.innerHTML = '验证并登录';
        } else {
            var msg = (x && x.msg) ? x.msg : '登录失败';
            showToast(msg);
            if (/环境|风险|异地登录|IP|风控/.test(String(msg))) {
                var tip = document.getElementById('login_modal_tip');
                if (tip) tip.innerText = '检测到登录环境风险，建议使用扫码方式或更换节点后重试';
                switchLoginTab('qr');
            }
            btn.innerHTML = defaultText;
        }
    }, 'json').fail(function(){
        showToast('网络错误');
        btn.disabled = false;
        btn.innerHTML = defaultText;
    });
}

function showLogModal(qid) {
    currentQid = qid;
    logDataRaw = [];
    logMetaRaw = null;
    var kwInput = document.getElementById('log_search_kw');
    if (kwInput) kwInput.value = '';
    document.getElementById('log_modal').classList.remove('hidden');
    document.getElementById('log_modal').classList.add('flex');
    lockPageScroll();
    loadLogContent();
}

function hideLogModal() {
    var modal = document.getElementById('log_modal');
    modal.style.transition = 'opacity 0.15s';
    modal.style.opacity = '0';
    setTimeout(function() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        modal.style.opacity = '';
        unlockPageScroll();
    }, 150);
}

function hideCapModal() {
    var modal = document.getElementById('cap_modal');
    modal.classList.add('hidden');
    document.getElementById('cap_modal_body').innerHTML = '';
    unlockPageScroll();
}

function renderLogList(list, meta) {
    var typeMap = {ssmz: '说说秒赞', ssmp: '说说秒评', zdfss: '自动发说说', zfss: '转发说说', sign: '空间签到', clear_ss: '清空说说', clear_ly: '清空留言', cloud: '云端更新'};
    var html = '';
    var safeList = Array.isArray(list) ? list : [];
    if (safeList.length === 0) {
        var debugText = '';
        html = '<p class="text-center text-gray-400 py-8">暂无日志<br><span class="text-xs text-gray-400">请先执行一次监控任务后再查看</span>' + debugText + '</p>';
    } else {
        html = '<div class="space-y-2">';
        if (meta && meta.used_fallback) {
            html += '<div class="p-2 bg-yellow-50 border border-yellow-200 text-yellow-700 text-xs rounded">已按同QQ历史QID聚合日志：' + escHtml((meta.matched_qids || []).join(',')) + '</div>';
        }
        safeList.forEach(function(item) {
            html += '<div class="p-3 bg-gray-50 rounded text-sm">' +
                '<div class="flex justify-between text-gray-500">' +
                '<span>' + (typeMap[item.type] || item.type) + '</span>' +
                '<span>' + (item.create_time || '') + '</span></div>' +
                '<div class="mt-1 text-gray-700">' + escHtml(item.content) + '</div></div>';
        });
        html += '</div>';
    }
    document.getElementById('log_modal_content').innerHTML = html;
}

function filterLogList() {
    var kwInput = document.getElementById('log_search_kw');
    var kw = kwInput ? (kwInput.value || '').trim().toLowerCase() : '';
    if (!kw) {
        renderLogList(logDataRaw, logMetaRaw);
        return;
    }
    var typeMap = {ssmz: '说说秒赞', ssmp: '说说秒评', zdfss: '自动发说说', zfss: '转发说说', sign: '空间签到', clear_ss: '清空说说', clear_ly: '清空留言'};
    var filtered = (Array.isArray(logDataRaw) ? logDataRaw : []).filter(function(item) {
        var t = (typeMap[item.type] || item.type || '').toString().toLowerCase();
        var c = (item.content || '').toString().toLowerCase();
        var tm = (item.create_time || '').toString().toLowerCase();
        return t.indexOf(kw) !== -1 || c.indexOf(kw) !== -1 || tm.indexOf(kw) !== -1;
    });
    renderLogList(filtered, logMetaRaw);
}

function loadLogContent() {
    $.post('ajax_qzone.php?act=get_user_log', {qid: currentQid}, function(res) {
        if (res.code === 1) {
            logDataRaw = Array.isArray(res.data) ? res.data : [];
            logMetaRaw = res.meta || null;
            renderLogList(logDataRaw, logMetaRaw);
        } else {
            document.getElementById('log_modal_content').innerHTML = '<p class="text-center text-red-500 py-8">' + escHtml(res.msg || '日志加载失败') + '</p>';
        }
    }, 'json').fail(function() {
        document.getElementById('log_modal_content').innerHTML = '<p class="text-center text-red-500 py-8">网络错误，日志加载失败</p>';
    });
}

function deleteQQ(qid) {
    if (!confirm('确定要删除该QQ账号吗？')) return;

    var item = document.getElementById('qq_item_' + qid);
    if (item) {
        item.style.opacity = '0.5';
        item.style.pointerEvents = 'none';
    }

    $.post('ajax_qzone.php?act=delete_user_qq', {qid: qid}, function(res) {
        if (res.code === 1) {
            showToast('删除成功');
            location.reload();
        } else {
            showToast(res.msg);
            if (item) {
                item.style.opacity = '1';
                item.style.pointerEvents = 'auto';
            }
        }
    }, 'json').fail(function() {
        showToast('网络错误，请重试');
        if (item) {
            item.style.opacity = '1';
            item.style.pointerEvents = 'auto';
        }
    });
}

function escHtml(str) {
    if (!str) return '';
    return str.replace(/&/g, '&amp;')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;')
              .replace(/"/g, '&quot;');
}

function showLoginModalGlobal() { showLoginModal(); }
function showImportCkModalGlobal() { showImportCkModal(); }
function showImportSourceModalGlobal() { showImportSourceModal(); }

$(function() {
    loadLoginNodes();
    $(document).on('change', '#login_node', function() {
        var modal = document.getElementById('login_modal');
        var qrBox = document.getElementById('qr_container');
        if (modal && !modal.classList.contains('hidden') && qrBox && !qrBox.classList.contains('hidden')) {
            refreshQR();
        }
    });
});
