// Profile module for Overleaf Chrome Extension
// 用户资料页面、VIP购买、支付功能

// 支付状态检查定时器
let paymentCheckInterval = null;

// Show profile page
function showProfilePage() {
    // 直接在新标签页打开 overleaf.top 的个人中心页面
    chrome.tabs.create({
        url: 'https://overleaf.top/profile',
        active: true
    });
}

// Update profile page with user data
async function updateProfilePageData() {
    if (!currentUser) return;

    // Update avatar and name
    document.getElementById('profile-avatar').src = currentUser.avatar_url || '';
    document.getElementById('profile-nickname').textContent = currentUser.nickname || 'User';
    document.getElementById('profile-id').textContent = `ID: ${currentUser.id}`;
    document.getElementById('profile-tokens').textContent = Math.floor(currentUser.remaining_tokens || 0);

    // Check VIP status
    const vipStatus = await authService.checkVipStatus();

    // Update VIP cards
    updateVipCard('vip1', currentUser.is_vip1, vipStatus.vipLevel === 1, vipStatus.expireAt);
    updateVipCard('vip2', currentUser.is_vip2, vipStatus.vipLevel === 2, vipStatus.expireAt);
    updateVipCard('vip3', currentUser.is_vip3, vipStatus.vipLevel === 3, vipStatus.expireAt);
}

// Update individual VIP card
function updateVipCard(cardId, isActive, isCurrentLevel, expireAt) {
    const card = document.getElementById(`${cardId}-card`);
    const statusDiv = document.getElementById(`${cardId}-status`);
    const buyBtn = document.getElementById(`buy-${cardId}-btn`);

    if (!card) return;

    if (isActive && isCurrentLevel) {
        card.classList.add('active');
        const remainingDays = authService.calculateRemainingDays(expireAt);
        statusDiv.innerHTML = `<span class="vip-status active">当前会员 · 剩余${remainingDays}天</span>`;
        statusDiv.style.display = 'block';
        buyBtn.textContent = '续费';
    } else {
        card.classList.remove('active');
        statusDiv.style.display = 'none';
        buyBtn.textContent = '购买';
    }
}

// Setup VIP purchase buttons
function setupVipButtons() {
    ['vip1', 'vip2', 'vip3'].forEach(vipType => {
        const buyBtn = document.getElementById(`buy-${vipType}-btn`);
        if (buyBtn) {
            buyBtn.addEventListener('click', () => {
                purchaseVip(vipType);
            });
        }
    });
}

// Purchase VIP membership
async function purchaseVip(vipType) {
    if (!currentUser) {
        showError('请先登录');
        return;
    }

    try {
        // Call payment API
        const response = await fetch('https://overleaf.top/api/payment/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...authService.getAuthHeaders()
            },
            body: JSON.stringify({ vip_type: vipType })
        });

        if (!response.ok) {
            throw new Error('Payment creation failed');
        }

        const data = await response.json();

        if (data.success) {
            // Show payment modal with QR code
            showPaymentModal(data, vipType);

            // Start checking payment status
            startPaymentStatusCheck(data.out_trade_no);
        } else {
            throw new Error(data.message || 'Payment creation failed');
        }
    } catch (error) {
        console.error('[Sidepanel] Payment error:', error);
        showError('创建支付订单失败，请重试');
    }
}

// Show payment modal
function showPaymentModal(paymentData, vipType) {
    const modal = document.getElementById('payment-modal');
    const qrContainer = document.getElementById('qr-code-container');
    const amountEl = document.getElementById('payment-amount');
    const descEl = document.getElementById('payment-desc');
    const statusEl = document.getElementById('payment-status');

    if (!modal) return;

    // Generate QR code
    qrContainer.innerHTML = `<img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(paymentData.code_url)}" alt="Payment QR Code">`;

    // Set payment info
    amountEl.textContent = `¥${(paymentData.amount / 100).toFixed(2)}`;
    descEl.textContent = paymentData.description;
    statusEl.textContent = '等待支付...';
    statusEl.className = 'payment-status waiting';

    // Show modal
    modal.style.display = 'flex';
}

// Close payment modal
function closePaymentModal() {
    const modal = document.getElementById('payment-modal');
    if (modal) {
        modal.style.display = 'none';
    }

    // Stop payment status check
    if (paymentCheckInterval) {
        clearInterval(paymentCheckInterval);
        paymentCheckInterval = null;
    }
}

// Start checking payment status
function startPaymentStatusCheck(outTradeNo) {
    if (paymentCheckInterval) {
        clearInterval(paymentCheckInterval);
    }

    paymentCheckInterval = setInterval(async () => {
        try {
            const response = await fetch(`https://overleaf.top/api/payment/status/${outTradeNo}`, {
                headers: authService.getAuthHeaders()
            });

            if (response.ok) {
                const data = await response.json();

                if (data.success && data.paid) {
                    // Payment successful
                    const statusEl = document.getElementById('payment-status');
                    statusEl.textContent = '支付成功！';
                    statusEl.className = 'payment-status success';

                    // Stop checking
                    clearInterval(paymentCheckInterval);
                    paymentCheckInterval = null;

                    // Refresh user data
                    setTimeout(async () => {
                        closePaymentModal();
                        await updateAuthUI();
                        await updateProfilePageData();
                        showSuccess('支付成功！会员权益已生效');
                    }, 2000);
                }
            }
        } catch (error) {
            console.error('[Sidepanel] Payment status check error:', error);
        }
    }, 3000); // Check every 3 seconds
}
