var timeList = new Array();
var currentPage = 1;
var pageSize = 10;
var totalPages = 1;
var currentVersion = (typeof window !== 'undefined' && window.INDEX_DEFAULT_VERSION) ? window.INDEX_DEFAULT_VERSION : 'cloud'; // cloud / dg / qzone

function showLoading() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.classList.remove('hidden');
    }
}

function hideLoading() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.classList.add('hidden');
    }
}

function showToast(message, duration = 3000, type = 'info') {
    const toastWrap = document.getElementById('toastWrap');
    if (!toastWrap) return;

    const toast = document.createElement('div');
    toast.className = `px-4 py-2 rounded-lg shadow-md transform transition-all duration-300 ease-in-out opacity-0 translate-y-[-10px]`;

    switch (type) {
        case 'success':
            toast.className += ' bg-green-500 text-white';
            break;
        case 'error':
            toast.className += ' bg-red-500 text-white';
            break;
        case 'warning':
            toast.className += ' bg-yellow-500 text-white';
            break;
        default:
            toast.className += ' bg-gray-700 text-white';
    }

    toast.textContent = message;
    toastWrap.appendChild(toast);

    setTimeout(() => {
        toast.classList.remove('opacity-0', 'translate-y-[-10px]');
        toast.classList.add('opacity-100', 'translate-y-0');
    }, 10);

    setTimeout(() => {
        toast.classList.remove('opacity-100', 'translate-y-0');
        toast.classList.add('opacity-0', 'translate-y-[-10px]');
        setTimeout(() => {
            if (toastWrap.contains(toast)) {
                toastWrap.removeChild(toast);
            }
        }, 300);
    }, duration);
}

function openModal(title, content, footerCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    
    const modalFooter = document.getElementById('modalFooter');
    if (footerCallback) {
        modalFooter.innerHTML = footerCallback();
        modalFooter.classList.remove('hidden');
    } else {
        modalFooter.classList.add('hidden');
    }
    
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

$(document).ready(function() {
    switchVersion(currentVersion);
    loadNotifications();
    loadCarousel();
    
    var combinedAlertContent = alertContentAll + alertContent + alertGonggao;
    if (combinedAlertContent.trim()) {
        var shouldShow = true;
        
        if (alertFreq == '1') {
            var lastShown = localStorage.getItem('alertShownDate');
            var today = new Date().toDateString();
            if (lastShown == today) {
                shouldShow = false;
            }
        }
        
        if (shouldShow) {
            openModal('公告', combinedAlertContent, function() {
                return '<button onclick="closeModal()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">我知道了</button>';
            });
            if (alertFreq == '1') {
                localStorage.setItem('alertShownDate', new Date().toDateString());
            }
        }
    }
});

var currentSlide = 0;
var carouselData = [];
var carouselInterval;

function loadCarousel() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=get_carousel&t=' + Date.now(),
        data: {pagesize: 10, page: 1},
        dataType: 'json',
        success: function(data) {
            if (data.code == 1 && data.data && data.data.length > 0) {
                carouselData = data.data.filter(item => item.status == 1);
                if (carouselData.length > 0) {
                    initCarousel();
                } else {
                    showNoCarousel();
                }
            } else {
                showNoCarousel();
            }
        },
        error: function() {
            showNoCarousel();
        }
    });
}

function showNoCarousel() {
    $('#carousel-container').html('<div class="flex items-center justify-center h-full text-gray-500"><i class="fas fa-images text-xl mb-2"></i><p class="text-xs">暂无轮播图</p></div>');
    $('#carousel-indicators').hide();
}

function initCarousel() {
    showSlide(currentSlide);
    renderIndicators();
    autoPlay();
    bindEvents();
}

function showSlide(index) {
    const container = $('#carousel-container');
    container.empty();
    
    if (!carouselData[index]) {
        return;
    }
    
    const item = carouselData[index];
    const slide = $('<div>').addClass('w-full h-full');
    const img = $('<img>')
        .attr('src', item.image)
        .attr('alt', item.title || '')
        .addClass('w-full h-full object-cover rounded-2xl cursor-pointer');
    
    slide.append(img);
    container.append(slide);
}

function renderIndicators() {
    const indicators = $('#carousel-indicators');
    indicators.empty().show();
    
    carouselData.forEach((item, index) => {
        const indicator = $('<button>')
            .addClass('w-2 h-2 rounded-full transition-all')
            .css('background-color', index === currentSlide ? '#3b82f6' : '#cbd5e1');
        
        indicator.on('click', function() {
            currentSlide = index;
            showSlide(currentSlide);
            updateIndicators();
        });
        
        indicators.append(indicator);
    });
}

function updateIndicators() {
    $('#carousel-indicators button').each(function(index) {
        $(this).css('background-color', index === currentSlide ? '#3b82f6' : '#cbd5e1');
    });
}

function autoPlay() {
    if (carouselData.length <= 1) return;
    
    clearInterval(carouselInterval);
    carouselInterval = setInterval(function() {
        currentSlide = (currentSlide + 1) % carouselData.length;
        showSlide(currentSlide);
        updateIndicators();
    }, 5000);
}

function bindEvents() {
    const container = $('#carousel-container');
    let startX = 0;
    let isDragging = false;
    
    container.on('click', function() {
        if (carouselData[currentSlide] && carouselData[currentSlide].link) {
            const link = carouselData[currentSlide].link.toString().trim();
            if (link) {
                window.location.href = link;
            }
        }
    });
    
    container.on('touchstart', function(e) {
        startX = e.touches[0].clientX;
        isDragging = true;
        clearInterval(carouselInterval);
    });
    
    container.on('touchmove', function(e) {
        if (!isDragging) return;
        const currentX = e.touches[0].clientX;
        const diffX = currentX - startX;
        
        if (Math.abs(diffX) > 10) {
            e.preventDefault();
        }
    });
    
    container.on('touchend', function(e) {
        if (!isDragging) return;
        
        const endX = e.changedTouches[0].clientX;
        const diffX = endX - startX;
        
        if (Math.abs(diffX) > 50) {
            if (diffX > 0) {
                currentSlide = (currentSlide - 1 + carouselData.length) % carouselData.length;
            } else {
                currentSlide = (currentSlide + 1) % carouselData.length;
            }
            showSlide(currentSlide);
            updateIndicators();
        }
        
        isDragging = false;
        autoPlay();
    });
    
    container.on('mousedown', function(e) {
        startX = e.clientX;
        isDragging = true;
        clearInterval(carouselInterval);
    });
    
    container.on('mousemove', function(e) {
        if (!isDragging) return;
        const currentX = e.clientX;
        const diffX = currentX - startX;
        
        if (Math.abs(diffX) > 10) {
            e.preventDefault();
        }
    });
    
    container.on('mouseup mouseleave', function(e) {
        if (!isDragging) return;
        
        const endX = e.clientX;
        const diffX = endX - startX;
        
        if (Math.abs(diffX) > 50) {
            if (diffX > 0) {
                currentSlide = (currentSlide - 1 + carouselData.length) % carouselData.length;
            } else {
                currentSlide = (currentSlide + 1) % carouselData.length;
            }
            showSlide(currentSlide);
            updateIndicators();
        }
        
        isDragging = false;
        autoPlay();
    });
}

function loadNotifications() {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=get_message',
        data: {pagesize: 5, page: 1},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            renderNotifications(data.data || []);
            $('#unreadCount').text(data.read_num || 0);
        },
        error: function(xhr, status, error) {
            hideLoading();
            showToast('加载通知失败', 'error');
        }
    });
}

function renderNotifications(data) {
    var notificationList = $('#notification-list');
    notificationList.empty();
    
    if (data.length === 0) {
        notificationList.html('<div class="text-center py-8 text-gray-500"><i class="fas fa-bell-slash text-xl mb-2"></i><p class="text-xs">暂无消息通知</p></div>');
        return;
    }
    
    $.each(data, function(i, value) {
        var statusBadge = value.read == false ? 
            '<span class="px-1.5 py-0.5 bg-red-100 text-red-700 rounded-full text-xs font-medium">未读</span>' : 
            '<span class="px-1.5 py-0.5 bg-green-100 text-green-700 rounded-full text-xs font-medium">已读</span>';
        
        var cardClass = value.read == false ? 'bg-gray-50' : '';
        
        var tmp = '<div class="p-3 ' + cardClass + ' hover:bg-gray-50 transition-colors">' +
            '<div class="flex justify-between items-start">' +
            '<div class="flex-1 min-w-0">' +
            '<h4 class="text-sm font-medium text-gray-800 mb-1 truncate">主题：' + value.title + '</h4>' +
            '<p class="text-xs text-gray-500">' + value.addtime + '</p>' +
            '</div>' +
            '<div class="flex items-center gap-2">' +
            statusBadge +
            '<button onclick="showNotification(' + value.id + ',' + value.read + ',\'' + encodeURI(value.content) + '\',\'' + encodeURI(value.title) + '\')" class="px-2 py-1 bg-indigo-100 text-indigo-700 rounded text-xs hover:bg-indigo-200 transition-colors">' +
            '查看' +
            '</button>' +
            '</div>' +
            '</div>' +
            '</div>';
        
        notificationList.append(tmp);
    });
}

function showNotification(id, read, content, title) {
    if (read == false) {
        $.get('ajax.php?act=set_message&id=' + id, function(d) {
            if (d.code == 1) {
                loadNotifications();
            }
        }, 'json');
    }
    var modalContent = '<div>' + decodeURI(content) + '</div>';
    openModal(decodeURI(title), modalContent, function() {
        return '<button onclick="closeModal()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">关闭</button>';
    });
}

function loadQQList() {
    showLoading();
    var act = currentVersion === 'qzone' ? 'qzone_qqlist' : 'qqlist';
    var url = currentVersion === 'qzone'
        ? ('ajax.php?act=' + act + '&page=' + currentPage + '&pagesize=' + pageSize)
        : ('ajax.php?act=' + act + '&biz=' + (currentVersion === 'dg' ? 'dg' : 'cloud') + '&page=' + currentPage + '&pagesize=' + pageSize);
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code === -1) {
                renderQQList([]);
                $('#total').text(0);
                totalPages = 1;
                $('#current-page').text(1);
                return;
            }
            renderQQList(data.data || []);
            $('#total').text(data.total || 0);
            totalPages = Math.ceil((data.total || 0) / pageSize) || 1;
            $('#current-page').text(currentPage);
        },
        error: function() {
            hideLoading();
            showToast('加载失败', 'error');
        }
    });
}

function switchVersion(version) {
    if (!version) return;
    currentVersion = version;
    currentPage = 1;
    
    // 更新按钮样式
    var versions = ['cloud', 'dg', 'qzone'];
    for (var i = 0; i < versions.length; i++) {
        var v = versions[i];
        var btn = document.getElementById('btn-' + v);
        if (!btn) continue;
        if (v === version) {
            btn.className = 'text-xs px-2.5 py-1 rounded-md transition-all bg-indigo-600 text-white';
        } else {
            btn.className = 'text-xs px-2.5 py-1 rounded-md transition-all text-gray-600 hover:bg-gray-200';
        }
    }
    
    loadQQList();
}

function renderQQList(list) {
    if (list.length === 0) {
        var addUrl = currentVersion === 'qzone'
            ? './qzone.php'
            : (currentVersion === 'dg' ? './add.php?biz=dg' : './add.php');
        $('#list').html(`<div class="p-8 text-center">
            <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fab fa-qq text-gray-400 text-2xl"></i>
            </div>
            <p class="text-gray-500 mb-3">暂无QQ账号</p>
            <a href="${addUrl}" class="inline-flex items-center px-3 py-1.5 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-lg text-xs font-medium transition-colors">
                <i class="fas fa-plus mr-1"></i>点击添加
            </a>
        </div>`);
        return;
    }
    
    var html = '';
    $.each(list, function(i, v) {
        var statusClass = v.login_zt == 1 ? 'bg-green-500' : 'bg-gray-400';
        var statusText = v.login_zt == 1 ? '在线' : '离线';
        
        // 秒赞版使用简化的渲染
        if (currentVersion === 'qzone') {
            var remainHtml = '';
            if (v.endtime) {
                var endDate = new Date(v.endtime);
                var now = new Date();
                if (endDate < now) {
                    remainHtml = '<span class="text-red-500">已过期</span>';
                } else {
                    var diffMs = endDate - now;
                    var diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
                    var diffYears = diffMs / (1000 * 60 * 60 * 24 * 365);
                    if (diffYears >= 5) {
                        remainHtml = '<span class="text-green-600">永久</span>';
                    } else {
                        remainHtml = '<span class="text-indigo-600">到期: ' + v.endtime + '</span>';
                    }
                }
            }
            var subText = '秒赞版 VIP ' + (remainHtml || '-');
            
            html += `<div class="p-4 flex items-center gap-3 hover:bg-gray-50 transition-colors">
                <div class="relative">
                    <img src="//q4.qlogo.cn/headimg_dl?dst_uin=${v.qq}&spec=100" class="w-12 h-12 rounded-full border border-gray-100">
                    <div class="absolute -bottom-1 -right-1 w-4 h-4 ${statusClass} rounded-full border-2 border-white"></div>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="font-medium text-gray-800 truncate">${v.qq}</div>
                    <div class="text-xs text-gray-500">${subText}</div>
                </div>
                <a href="./qzone.php" class="px-2 py-1 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-lg text-xs font-medium transition-colors">
                    管理
                </a>
            </div>`;
            return;
        }
        
        // 云端版渲染
        var isFree = v.apipwd === '0' || v.apipwd === 0;

        timeList[v.id] = v.endtime_arr;
        var remainHtml = calcRemainDays(v.id, v.isend, v.endtime, v.endtime_arr, isFree);
        var moreTimeBtn = '';
        if (v.endtime_arr && v.endtime_arr.length > 1) {
            moreTimeBtn = ' <button class="text-xs text-indigo-600 hover:underline ml-1" onclick="get_endtime(' + v.id + ')">详情</button>';
        }
        
        var subText = '';
        if (isFree) {
            subText = remainHtml;
        } else {
            subText = (v.login_class_name || '未分类') + ' 剩余 ' + remainHtml + moreTimeBtn;
        }
        
        var manageUrl = currentVersion === 'dg'
            ? `./qqlist.php?biz=dg&qq=${v.qq}`
            : `./qqlist.php?qq=${v.qq}`;
        html += `<div class="p-4 flex items-center gap-3 hover:bg-gray-50 transition-colors">
            <div class="relative">
                <img src="//q4.qlogo.cn/headimg_dl?dst_uin=${v.qq}&spec=100" class="w-12 h-12 rounded-full border border-gray-100">
                <div class="absolute -bottom-1 -right-1 w-4 h-4 ${statusClass} rounded-full border-2 border-white"></div>
            </div>
            <div class="flex-1 min-w-0">
                <div class="font-medium text-gray-800 truncate">${v.qq}</div>
                <div class="text-xs text-gray-500">${subText}</div>
            </div>
            <a href="${manageUrl}" class="px-2 py-1 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-lg text-xs font-medium transition-colors">
                管理
            </a>
        </div>`;
    });
    $('#list').html(html);
}

function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        loadQQList();
    }
}

function nextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        loadQQList();
    }
}

function parseDate(dateStr) {
    if (!dateStr) return null;
    var formats = [
        /^(\d{4})-(\d{2})-(\d{2})$/,
        /^(\d{4})\/(\d{2})\/(\d{2})$/,
        /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/,
        /^(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})$/
    ];
    for (var fi = 0; fi < formats.length; fi++) {
        var match = dateStr.match(formats[fi]);
        if (match) {
            var year = parseInt(match[1], 10);
            var month = parseInt(match[2], 10) - 1;
            var day = parseInt(match[3], 10);
            var hours = match[4] ? parseInt(match[4], 10) : 0;
            var minutes = match[5] ? parseInt(match[5], 10) : 0;
            var seconds = match[6] ? parseInt(match[6], 10) : 0;
            var date = new Date(year, month, day, hours, minutes, seconds);
            if (date.getFullYear() === year && date.getMonth() === month && date.getDate() === day) {
                return date;
            }
        }
    }
    var date = new Date(dateStr);
    return isNaN(date.getTime()) ? null : date;
}

function _getDateDiff(nowDate, targetDate) {
    var years = targetDate.getFullYear() - nowDate.getFullYear();
    var months = targetDate.getMonth() - nowDate.getMonth();
    var days = targetDate.getDate() - nowDate.getDate();
    if (days < 0) { days += new Date(targetDate.getFullYear(), targetDate.getMonth(), 0).getDate(); months--; }
    if (months < 0) { months += 12; years--; }
    return { years: years, months: months, days: days };
}

function _calcRemainText(timeStr) {
    var endDate = new Date(timeStr);
    if (isNaN(endDate.getTime())) return '时间格式异常';
    var now = new Date();
    var diff = _getDateDiff(now, endDate);
    if (diff.years < 0 || (diff.years === 0 && diff.months < 0) || (diff.years === 0 && diff.months === 0 && diff.days < 0)) return '已过期';
    if (diff.years === 0 && diff.months === 0 && diff.days === 0) return '今天到期';
    var tm = diff.years * 12 + diff.months;
    if (tm > 50) return '永久';
    var p = [];
    if (diff.years > 0) p.push(diff.years + '年');
    if (diff.months > 0) p.push(diff.months + '月');
    if (diff.days > 0) p.push(diff.days + '天');
    return p.join('');
}

function calcRemainDays(id, isend, endtime, endtime_arr, isFree) {
    timeList[id] = endtime_arr;

    if (isFree) {
        return '<span class="text-green-600 cursor-pointer font-medium" onclick="get_endtime(' + id + ')">当前节点免费</span>';
    }

    var endDate = parseDate(endtime);
    if (!endDate) {
        return '<span class="text-red-500 cursor-pointer" onclick="get_endtime(' + id + ')">时间格式异常</span>';
    }

    var now = new Date(); now.setHours(0,0,0,0);
    var targetDate = new Date(endDate); targetDate.setHours(0,0,0,0);

    var diff = _getDateDiff(now, targetDate);
    var displayText = '', colorClass = 'text-indigo-600';

    if (diff.years < 0 || (diff.years === 0 && diff.months < 0) || (diff.years === 0 && diff.months === 0 && diff.days < 0)) {
        displayText = '已过期'; colorClass = 'text-red-500';
    } else if (diff.years === 0 && diff.months === 0 && diff.days === 0) {
        displayText = '今天到期'; colorClass = 'text-orange-500';
    } else {
        var totalMonths = diff.years * 12 + diff.months;
        if (totalMonths > 50) { displayText = '永久'; colorClass = 'text-green-600'; }
        else {
            var parts = [];
            if (diff.years > 0) parts.push(diff.years + '年');
            if (diff.months > 0) parts.push(diff.months + '月');
            if (diff.days > 0) parts.push(diff.days + '天');
            displayText = parts.join('');
        }
    }
    return '<span class="' + colorClass + ' cursor-pointer font-medium" onclick="get_endtime(' + id + ')">' + displayText + '</span>';
}

function get_endtime(id) {
    var list = timeList[id];
    if (!list || !list.length) { showToast('无时长数据'); return; }
    var html = '<div class="space-y-3">';
    $.each(list, function(i, v) {
        var isExpired = v.isend == 1;
        var remainText = isExpired ? '已过期' : _calcRemainText(v.time);
        var expiredTag = isExpired ? '<span class="ml-2 px-1.5 py-0.5 text-xs bg-red-100 text-red-600 rounded">过期</span>' : '';
        var delBtn = isExpired ? '<button class="px-2 py-1 text-xs bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors" onclick="del_time(' + id + ',' + v.id + ')">删除</button>' : '';
        html += '<div class="flex items-center justify-between p-3 bg-gray-50 rounded-xl">'+
            '<div>'+
                '<div class="text-sm font-medium text-gray-800">' + (v.name || '未知') + expiredTag + '</div>'+
                '<div class="text-xs text-gray-500 mt-1">到期: ' + (v.time || '-') + '</div>'+
                '<div class="text-xs mt-0.5">剩余: <span class="' + (isExpired ? 'text-red-500' : 'text-indigo-600') + ' font-medium">' + remainText + '</span></div>'+
            '</div>'+
            '<div>' + delBtn + '</div>'+
        '</div>';
    });
    html += '</div>';
    openModal('时长详情', html);
}

function del_time(id, cids) {
    showLoading();
    $.ajax({
        type: 'POST', url: 'ajax.php?act=del_time',
        data: {id:id, cids:cids, biz:(currentVersion === 'dg' ? 'dg' : 'cloud')}, dataType: 'json',
        success: function(data) {
            hideLoading(); showToast(data.msg);
            if (data.code == 1) { closeModal(); loadQQList(); }
        },
        error: function() { hideLoading(); showToast('服务器错误'); }
    });
}

function buildRecoverQQBody() {
    var body = '<div style="padding:10px;">'+ 
        '<div class="text-center font-bold" id="login">'+ 
            '<span id="loginmsg">请先使用QQ手机版扫描二维码</span>'+ 
            '<span id="loginload" style="padding-left:10px;color:#790909;">.</span>'+ 
        '</div>'+ 
        '<div class="flex justify-center my-3" id="qrimg"></div>'+ 
        '<div class="flex flex-col gap-2">'+ 
            '<button class="w-full px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm transition-colors" onclick="getqrpic(true)">刷新二维码</button>';
    
    if (typeof quick_qq_enabled !== 'undefined' && quick_qq_enabled) {
        body += '<button class="w-full px-4 py-2 bg-yellow-500 hover:bg-yellow-600 text-white rounded-lg text-sm transition-colors" onclick="oauthQuickLogin()">快捷登录</button>';
    }
    
    body += '</div></div>';
    return body;
}

function startRecoverQQ(biz) {
    window.RECOVER_BIZ = (biz === 'dg') ? 'dg' : 'cloud';
    openModal('找回QQ', buildRecoverQQBody());
    $.getScript('qqlogin/qrlogin.js');
}

function recoverQQ() {
    var cloudEnabled = !!window.INDEX_CLOUD_ENABLED;
    var dgEnabled = !!window.INDEX_DG_ENABLED;
    if (cloudEnabled && dgEnabled) {
        var cloudName = window.VERSION_NAME_CLOUD || '云端版';
        var dgName = window.VERSION_NAME_DG || '代挂版';
        openModal('选择找回版本',
            '<div class="p-3 space-y-3">'+
                '<div class="text-sm text-gray-600">请先选择要找回的版本</div>'+
                '<div class="grid grid-cols-2 gap-2">'+
                    '<button type="button" class="px-3 py-2 rounded-lg bg-blue-500 hover:bg-blue-600 text-white text-sm transition-colors" onclick="startRecoverQQ(\'cloud\')">'+cloudName+'</button>'+
                    '<button type="button" class="px-3 py-2 rounded-lg bg-indigo-500 hover:bg-indigo-600 text-white text-sm transition-colors" onclick="startRecoverQQ(\'dg\')">'+dgName+'</button>'+
                '</div>'+
            '</div>'
        );
        return;
    }
    if (dgEnabled) {
        startRecoverQQ('dg');
        return;
    }
    startRecoverQQ('cloud');
}

function oauthQuickLogin() {
    var returnUrl = encodeURIComponent(window.location.href + '?action=check_qq_bind');
    window.location.href = './connect.php?type=qq&return_url=' + returnUrl;
}

function copyQQ(qq) {
    navigator.clipboard.writeText(qq).then(function() {
        showToast('QQ号已复制', 'success');
    }, function() {
        showToast('复制失败，请手动复制', 'error');
    });
}

function showNotice() {
    var content = '';
    if (noticeUpContent) {
        content = noticeUpContent;
    } else if (noticeContent) {
        content = noticeContent;
    } else if (noticeUserContent) {
        content = noticeUserContent;
    }
    
    openModal('公告', content || '暂无公告', function() {
        return '<button onclick="closeModal()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">关闭</button>';
    });
}

function showKf() {
    var content = `<div class="text-center p-4">
        <img src="//q4.qlogo.cn/headimg_dl?dst_uin=${kfQQ}&spec=100" class="w-20 h-20 rounded-full mx-auto mb-3">
        <div class="text-lg font-semibold mb-2">QQ: ${kfQQ}</div>
        <button onclick="copyQQ('${kfQQ}')" class="px-3 py-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors mb-4">
            复制QQ号
        </button>
        <div class="flex flex-wrap gap-2 justify-center">
            <a href="mqq://card/show_pslcard?src_type=internal&version=1&uin=${kfQQ}&card_type=person" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg text-sm font-medium transition-colors">
                手机联系
            </a>
            <a href="https://wpa.qq.com/msgrd?v=3&uin=${kfQQ}&site=qq&menu=yes" target="_blank" class="px-4 py-2 bg-gray-700 hover:bg-gray-800 text-white rounded-lg text-sm font-medium transition-colors">
                电脑联系
            </a>
        </div>
        ${kfWX ? '<div class="mt-4 text-gray-600">微信客服: ' + kfWX + '</div>' : ''}
    </div>`;
    
    openModal('联系客服', content, function() {
        return '<button onclick="closeModal()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">关闭</button>';
    });
}
