document.addEventListener('DOMContentLoaded', function() {
    const themeToggle = document.getElementById('theme-toggle');
    const darkThemeLink = document.getElementById('dark-theme');
    const darkMode = localStorage.getItem('darkMode') === 'true';
    if (darkMode) {
        document.documentElement.classList.add('dark');
        if (darkThemeLink) darkThemeLink.disabled = false;
    } else {
        document.documentElement.classList.remove('dark');
        if (darkThemeLink) darkThemeLink.disabled = true;
    }
    if (themeToggle) {
        themeToggle.addEventListener('click', function() {
            const isDark = document.documentElement.classList.toggle('dark');
            localStorage.setItem('darkMode', isDark);
            if (darkThemeLink) darkThemeLink.disabled = !isDark;
            window.dispatchEvent(new CustomEvent('themeChanged', { detail: { dark: isDark } }));
        });
    }

    const mobileMenuBtn = document.getElementById('mobileMenuBtn');
    const mobileMenu = document.getElementById('mobileMenu');
    if (mobileMenuBtn && mobileMenu) {
        mobileMenuBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            mobileMenu.classList.toggle('show');
        });
        document.addEventListener('click', function(e) {
            if (!mobileMenu.contains(e.target) && e.target !== mobileMenuBtn) mobileMenu.classList.remove('show');
        });
    }

    window.showToast = function(message, type = 'success', duration = 3000) {
        const existing = document.querySelector('.global-toast');
        if (existing) existing.remove();
        const toast = document.createElement('div');
        toast.className = `global-toast toast-${type}`;
        toast.innerHTML = `<div class="toast-content"><span class="toast-icon">${type === 'success' ? '✓' : '✗'}</span><span class="toast-message">${message}</span></div>`;
        toast.style.cssText = `position: fixed; top: 20px; right: 20px; z-index: 9999; background: var(--bg-primary); border-left: 4px solid ${type === 'success' ? '#10b981' : '#ef4444'}; border-radius: 8px; padding: 12px 20px; box-shadow: var(--shadow-lg); animation: slideIn 0.3s ease; color: var(--text-primary);`;
        document.body.appendChild(toast);
        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, duration);
    };
    const style = document.createElement('style');
    style.textContent = `@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes slideOut { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } } .input-error { color: var(--danger-color); font-size: 12px; margin-top: 4px; } input.error, select.error, textarea.error { border-color: var(--danger-color) !important; }`;
    document.head.appendChild(style);

    window.confirmDialog = function(message, onConfirm, onCancel) {
        const existing = document.querySelector('.custom-confirm');
        if (existing) existing.remove();
        const overlay = document.createElement('div');
        overlay.className = 'confirm-overlay';
        overlay.style.cssText = `position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;`;
        const dialog = document.createElement('div');
        dialog.className = 'custom-confirm';
        dialog.style.cssText = `background: var(--bg-primary); border-radius: 12px; padding: 24px; min-width: 300px; max-width: 400px; box-shadow: var(--shadow-lg);`;
        dialog.innerHTML = `<p style="margin-bottom: 20px;">${message}</p><div style="display: flex; gap: 12px; justify-content: flex-end;"><button class="confirm-cancel" style="padding: 8px 20px; border: 1px solid var(--border-color); background: none; border-radius: 6px; cursor: pointer;">取消</button><button class="confirm-ok" style="padding: 8px 20px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer;">确定</button></div>`;
        overlay.appendChild(dialog);
        document.body.appendChild(overlay);
        dialog.querySelector('.confirm-cancel').onclick = () => { overlay.remove(); onCancel && onCancel(); };
        dialog.querySelector('.confirm-ok').onclick = () => { overlay.remove(); onConfirm && onConfirm(); };
        overlay.onclick = (e) => { if (e.target === overlay) { overlay.remove(); onCancel && onCancel(); } };
    };
});

/**
 * 发起支付请求
 */
window.initPayment = function(url, orderNo, amount, type, name) {
    console.log('发起支付:', {url, orderNo, amount, type, name});
    
    fetch(url + '?order_no=' + encodeURIComponent(orderNo) + 
          '&amount=' + encodeURIComponent(amount) + 
          '&type=' + encodeURIComponent(type) + 
          '&name=' + encodeURIComponent(name))
        .then(response => response.json())
        .then(data => {
            console.log('支付响应:', data);
            
            // 易支付返回格式：code=1 表示成功
            if (data.code == 1) {
                if (data.qrcode) {
                    // 有二维码，显示弹窗
                    window.showQRCodeModal(data.qrcode, data.money || amount, type, orderNo);
                } else if (data.payurl) {
                    // 有支付链接，直接跳转
                    window.location.href = data.payurl;
                } else if (data.urlscheme) {
                    // 有 URL Scheme，跳转（如支付宝、微信）
                    window.location.href = data.urlscheme;
                } else {
                    window.showToast('获取支付信息失败', 'error');
                }
            } else {
                window.showToast(data.msg || '支付请求失败', 'error');
            }
        })
        .catch(error => {
            console.error('支付请求错误:', error);
            window.showToast('网络错误：' + error.message, 'error');
        });
};

/**
 * 显示二维码弹窗
 */
window.showQRCodeModal = function(qrcodeUrl, amount, type, orderNo) {
    const existing = document.querySelector('.qrcode-modal');
    if (existing) existing.remove();
    
    const overlay = document.createElement('div');
    overlay.className = 'qrcode-modal';
    overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:10001;';
    
    const payTypeName = type === 'alipay' ? '支付宝' : '微信支付';
    
    overlay.innerHTML = `
        <div style="background:var(--bg-primary);border-radius:16px;padding:30px;max-width:350px;width:90%;text-align:center;">
            <h3 style="margin-bottom:10px;">扫码支付</h3>
            <p style="color:var(--text-secondary);margin-bottom:20px;">请使用${payTypeName}扫码支付 ¥${amount}</p>
            <div id="qrcode-container" style="margin:20px auto;width:200px;height:200px;"></div>
            <p style="color:var(--text-muted);font-size:12px;margin-top:15px;">支付成功后自动跳转</p>
            <button id="closeQRModal" style="margin-top:20px;padding:8px 20px;background:var(--primary-color);color:white;border:none;border-radius:8px;cursor:pointer;">关闭</button>
        </div>
    `;
    
    document.body.appendChild(overlay);
    
    // 生成二维码
    if (typeof QRCode !== 'undefined') {
        new QRCode(document.getElementById('qrcode-container'), {
            text: qrcodeUrl,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    } else {
        // 降级方案：显示图片
        const img = document.createElement('img');
        img.src = qrcodeUrl;
        img.style.width = '200px';
        img.style.height = '200px';
        document.getElementById('qrcode-container').appendChild(img);
    }
    
    document.getElementById('closeQRModal').addEventListener('click', function() {
        overlay.remove();
    });
    
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) overlay.remove();
    });
    
    // 轮询订单状态
    if (orderNo) {
        window.checkOrderStatus(orderNo, overlay);
    }
};

/**
 * 轮询检查订单支付状态
 */
window.checkOrderStatus = function(orderNo, modalElement) {
    console.log('开始轮询订单状态:', orderNo);
    let count = 0;
    const maxAttempts = 60; // 最多轮询60次（约5分钟）
    
    const interval = setInterval(() => {
        count++;
        console.log('第' + count + '次查询订单状态');
        
        fetch('/api/check_order.php?order_no=' + orderNo)
            .then(response => response.json())
            .then(data => {
                console.log('订单状态返回:', data);
                if (data.status === 'paid') {
                    clearInterval(interval);
                    console.log('支付成功，关闭弹窗');
                    if (modalElement) modalElement.remove();
                    window.showToast('支付成功！', 'success');
                    setTimeout(() => {
                        window.location.href = '/admin.php?page=orders';
                    }, 1500);
                } else if (count >= maxAttempts) {
                    clearInterval(interval);
                    console.log('轮询超时');
                    window.showToast('支付超时，请稍后查看订单状态', 'warning');
                }
            })
            .catch(error => {
                console.error('查询订单状态错误:', error);
            });
    }, 3000); // 每3秒查询一次
};

/**
 * 复制到剪贴板
 */
window.copyToClipboard = function(text, message) {
    navigator.clipboard.writeText(text).then(() => {
        window.showToast(message || '复制成功', 'success');
    }).catch(() => {
        const ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        window.showToast(message || '复制成功', 'success');
    });
};