// 全局变量
let allRewards = [];
let currentPage = 1;
const pageSize = 5;

// 获取赞助信息并展示在侧栏
fetch('https://rewards.qxzhan.cn/api/rewards')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        allRewards = data.data || [];
        showRewardsPage(currentPage);
    })
    .catch(error => {
        console.error('获取赞助信息失败:', error);
        const rewardsList = document.getElementById('rewards-list');
        if (rewardsList) {
            rewardsList.innerHTML = `
                <div style="padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 10px 0; line-height: 1.6; background: var(--efu-card-bg, #fff); color: var(--efu-fontcolor, #333);">
                    暂未获取到赞助信息，请稍后再试
                </div>
            `;
        }
    });

function showRewardsPage(page) {
    const rewardsList = document.getElementById('rewards-list');
    
    if (!rewardsList) {
        console.error('未找到赞助信息容器');
        return;
    }

    // 清空容器
    rewardsList.innerHTML = '';

    // 添加标题和赞助按钮
    const titleContainer = document.createElement('div');
    titleContainer.style.display = 'flex';
    titleContainer.style.justifyContent = 'space-between';
    titleContainer.style.alignItems = 'center';
    titleContainer.style.marginBottom = '15px';
    titleContainer.style.marginTop = '15px';
    titleContainer.style.borderBottom = '2px solid var(--efu-main, #49B1F5)';
    titleContainer.style.paddingBottom = '8px';
    
    const title = document.createElement('h3');
    title.innerHTML = '💝 赞助鸣谢';
    title.style.margin = '0';
    title.style.color = 'var(--efu-main, #49B1F5)';
    
    const sponsorButton = document.createElement('button');
    sponsorButton.innerHTML = '赞助作者';
    sponsorButton.style.background = 'var(--efu-main, #49B1F5)';
    sponsorButton.style.color = 'white';
    sponsorButton.style.border = 'none';
    sponsorButton.style.padding = '6px 12px';
    sponsorButton.style.borderRadius = '4px';
    sponsorButton.style.cursor = 'pointer';
    sponsorButton.style.fontSize = '14px';
    sponsorButton.style.transition = 'all 0.3s ease';
    
    // 按钮悬停效果
    sponsorButton.onmouseover = function() {
        this.style.background = 'var(--efu-theme, #1e9fff)';
        this.style.transform = 'translateY(-1px)';
    };
    sponsorButton.onmouseout = function() {
        this.style.background = 'var(--efu-main, #49B1F5)';
        this.style.transform = 'translateY(0)';
    };
    
    // 点击显示赞助模态框
    sponsorButton.onclick = function() {
        showSponsorModal();
    };
    
    titleContainer.appendChild(title);
    titleContainer.appendChild(sponsorButton);
    rewardsList.appendChild(titleContainer);

    // 检查是否有数据
    if (!allRewards || allRewards.length === 0) {
        const emptyMsg = document.createElement('div');
        emptyMsg.innerHTML = `
            <div style="padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 10px 0; line-height: 1.6; background: var(--efu-card-bg, #fff); color: var(--efu-fontcolor, #333); text-align: center;">
                暂无赞助记录<br>
                <small style="color: var(--efu-secondtext, #999);">成为第一位赞助者吧！</small>
            </div>
        `;
        rewardsList.appendChild(emptyMsg);
        return;
    }

    // 按赞助金额排序（从高到低）
    const sortedRewards = [...allRewards].sort((a, b) => b.money - a.money);

    // 计算分页
    const totalPages = Math.ceil(sortedRewards.length / pageSize);
    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, sortedRewards.length);
    const pageRewards = sortedRewards.slice(startIndex, endIndex);

    // 创建当前页的赞助列表
    pageRewards.forEach((reward, index) => {
        const globalIndex = startIndex + index;
        const rewardItem = document.createElement('div');
        
        // 格式化日期
        const date = new Date(reward.date);
        const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        
        // 设置不同排名样式
        let rankStyle = '';
        if (globalIndex === 0) {
            rankStyle = 'border-left: 4px solid #FFD700; background: linear-gradient(135deg, var(--efu-card-bg, #fff) 0%, rgba(255,215,0,0.1) 100%);';
        } else if (globalIndex === 1) {
            rankStyle = 'border-left: 4px solid #C0C0C0; background: linear-gradient(135deg, var(--efu-card-bg, #fff) 0%, rgba(192,192,192,0.1) 100%);';
        } else if (globalIndex === 2) {
            rankStyle = 'border-left: 4px solid #CD7F32; background: linear-gradient(135deg, var(--efu-card-bg, #fff) 0%, rgba(205,127,50,0.1) 100%);';
        } else {
            rankStyle = 'border-left: 4px solid var(--efu-main, #49B1F5);';
        }

        rewardItem.innerHTML = `
            <div style="${rankStyle} padding: 12px 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 8px 0; line-height: 1.6; background: var(--efu-card-bg, #fff); transition: all 0.3s ease; cursor: pointer;" 
                 onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.15)';" 
                 onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.1)';">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                    <span style="font-weight: bold; color: var(--efu-main, #49B1F5); font-size: 14px;">${reward.name}</span>
                    <span style="color: #FF6B6B; font-weight: bold; font-size: 14px;">¥${reward.money}</span>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <small style="color: var(--efu-secondtext, #999); font-size: 12px;">${formattedDate}</small>
                    ${globalIndex < 3 ? `<span style="background: ${globalIndex === 0 ? '#FFD700' : globalIndex === 1 ? '#C0C0C0' : '#CD7F32'}; color: white; padding: 2px 6px; border-radius: 10px; font-size: 10px; font-weight: bold;">TOP${globalIndex + 1}</span>` : ''}
                </div>
            </div>
        `;
        
        rewardsList.appendChild(rewardItem);
    });

    // 添加统计信息
    const totalAmount = sortedRewards.reduce((sum, reward) => sum + reward.money, 0);
    const totalSponsors = sortedRewards.length;
    
    const stats = document.createElement('div');
    stats.innerHTML = `
        <div style="padding: 12px 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 15px 0 10px 0; line-height: 1.6; background: var(--efu-card-bg, #fff); border-top: 2px solid var(--efu-main, #49B1F5);">
            <div style="display: flex; justify-content: space-between; font-size: 13px;">
                <span style="color: var(--efu-fontcolor, #333);">累计赞助:</span>
                <span style="color: #FF6B6B; font-weight: bold;">¥${totalAmount}</span>
            </div>
            <div style="display: flex; justify-content: space-between; font-size: 13px; margin-top: 5px;">
                <span style="color: var(--efu-fontcolor, #333);">赞助人数:</span>
                <span style="color: var(--efu-main, #49B1F5); font-weight: bold;">${totalSponsors}人</span>
            </div>
        </div>
    `;
    rewardsList.appendChild(stats);

    // 添加分页控件（只有在需要分页时才显示）
    if (totalPages > 1) {
        const pagination = document.createElement('div');
        pagination.style.display = 'flex';
        pagination.style.justifyContent = 'center';
        pagination.style.alignItems = 'center';
        pagination.style.marginTop = '15px';
        pagination.style.gap = '8px';
        
        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.innerHTML = '‹';
        prevButton.disabled = page === 1;
        prevButton.style.padding = '6px 12px';
        prevButton.style.border = '1px solid var(--efu-main, #49B1F5)';
        prevButton.style.background = page === 1 ? 'var(--efu-secondbg, #f6f6f6)' : 'var(--efu-card-bg, #fff)';
        prevButton.style.color = page === 1 ? 'var(--efu-secondtext, #999)' : 'var(--efu-main, #49B1F5)';
        prevButton.style.borderRadius = '4px';
        prevButton.style.cursor = page === 1 ? 'not-allowed' : 'pointer';
        prevButton.style.transition = 'all 0.3s ease';
        
        if (page > 1) {
            prevButton.onclick = () => {
                currentPage = page - 1;
                showRewardsPage(currentPage);
            };
            prevButton.onmouseover = () => {
                if (page > 1) prevButton.style.background = 'var(--efu-main, #49B1F5)';
                if (page > 1) prevButton.style.color = 'white';
            };
            prevButton.onmouseout = () => {
                if (page > 1) prevButton.style.background = 'var(--efu-card-bg, #fff)';
                if (page > 1) prevButton.style.color = 'var(--efu-main, #49B1F5)';
            };
        }

        // 页码信息
        const pageInfo = document.createElement('span');
        pageInfo.textContent = `${page} / ${totalPages}`;
        pageInfo.style.fontSize = '14px';
        pageInfo.style.color = 'var(--efu-fontcolor, #333)';
        pageInfo.style.padding = '0 10px';

        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.innerHTML = '›';
        nextButton.disabled = page === totalPages;
        nextButton.style.padding = '6px 12px';
        nextButton.style.border = '1px solid var(--efu-main, #49B1F5)';
        nextButton.style.background = page === totalPages ? 'var(--efu-secondbg, #f6f6f6)' : 'var(--efu-card-bg, #fff)';
        nextButton.style.color = page === totalPages ? 'var(--efu-secondtext, #999)' : 'var(--efu-main, #49B1F5)';
        nextButton.style.borderRadius = '4px';
        nextButton.style.cursor = page === totalPages ? 'not-allowed' : 'pointer';
        nextButton.style.transition = 'all 0.3s ease';
        
        if (page < totalPages) {
            nextButton.onclick = () => {
                currentPage = page + 1;
                showRewardsPage(currentPage);
            };
            nextButton.onmouseover = () => {
                if (page < totalPages) nextButton.style.background = 'var(--efu-main, #49B1F5)';
                if (page < totalPages) nextButton.style.color = 'white';
            };
            nextButton.onmouseout = () => {
                if (page < totalPages) nextButton.style.background = 'var(--efu-card-bg, #fff)';
                if (page < totalPages) nextButton.style.color = 'var(--efu-main, #49B1F5)';
            };
        }

        pagination.appendChild(prevButton);
        pagination.appendChild(pageInfo);
        pagination.appendChild(nextButton);
        rewardsList.appendChild(pagination);
    }
}

// 赞助模态框函数
function showSponsorModal() {
    // 创建模态框
    const modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
    modal.style.display = 'flex';
    modal.style.justifyContent = 'center';
    modal.style.alignItems = 'center';
    modal.style.zIndex = '1000';
    
    modal.innerHTML = `
        <div style="background: white; padding: 25px; border-radius: 12px; text-align: center; max-width: 400px; width: 90%; box-shadow: 0 10px 25px rgba(0,0,0,0.2);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0; color: var(--efu-main, #49B1F5);">支持作者</h3>
                <button id="close-modal" style="
                    background: none;
                    border: none;
                    font-size: 20px;
                    cursor: pointer;
                    color: var(--efu-secondtext, #999);
                    transition: color 0.3s;
                ">×</button>
            </div>
            
            <p style="margin-bottom: 20px; color: var(--efu-fontcolor, #333);">感谢您的支持！您的赞助将鼓励我创作更多优质内容。</p>
            
            <div style="display: flex; justify-content: space-around; margin-bottom: 25px;">
                <div style="text-align: center;">
                    <div style="font-weight: bold; margin-bottom: 8px; color: #07C160;">微信</div>
                    <div style="width: 150px; height: 150px; background: #f5f5f5; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin: 0 auto;">
                        <img src="https://image.lolimi.cn/2025/10/07/68e47ecc450c5.png" style="width: 150px; height: 150px; border-radius: 8px;" alt="微信赞赏码">
                    </div>
                </div>
                <div style="text-align: center;">
                    <div style="font-weight: bold; margin-bottom: 8px; color: #1677FF;">支付宝</div>
                    <div style="width: 150px; height: 150px; background: #f5f5f5; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin: 0 auto;">
                        <img src="https://image.lolimi.cn/2025/10/07/68e47ecc3e3a9.jpg" style="width: 150px; height: 150px; border-radius: 8px;" alt="支付宝赞赏码">
                    </div>
                </div>
            </div>
            
            <div style="border-top: 1px solid #eee; padding-top: 20px;">
                <p style="margin-bottom: 15px; color: var(--efu-secondtext, #999); font-size: 14px;">或者通过赞助网站支持</p>
                <button id="sponsor-site-btn" style="
                    background: linear-gradient(135deg, var(--efu-main, #49B1F5) 0%, var(--efu-theme, #1e9fff) 100%);
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 25px;
                    font-size: 14px;
                    font-weight: bold;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    display: inline-flex;
                    align-items: center;
                    gap: 8px;
                ">
                    <span>💝</span>
                    前往赞助网站
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 关闭按钮事件
    const closeBtn = document.getElementById('close-modal');
    closeBtn.onclick = function() {
        modal.remove();
    };
    
    // 赞助网站按钮事件
    const sponsorSiteBtn = document.getElementById('sponsor-site-btn');
    sponsorSiteBtn.onmouseover = function() {
        this.style.transform = 'translateY(-2px)';
        this.style.boxShadow = '0 4px 12px rgba(73, 177, 245, 0.4)';
    };
    sponsorSiteBtn.onmouseout = function() {
        this.style.transform = 'translateY(0)';
        this.style.boxShadow = 'none';
    };
    sponsorSiteBtn.onclick = function() {
        window.open('https://rewards.qxzhan.cn/', '_blank');
    };
    
    // 点击背景关闭
    modal.onclick = function(e) {
        if (e.target === modal) {
            modal.remove();
        }
    };
    
    // ESC键关闭
    document.addEventListener('keydown', function closeModalOnEsc(e) {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', closeModalOnEsc);
        }
    });
}

// Pjax支持
function handlePjaxComplete() {
    // 重新加载赞助信息
    fetch('https://rewards.qxzhan.cn/api/rewards')
        .then(response => response.json())
        .then(data => {
            allRewards = data.data || [];
            currentPage = 1; // 重置到第一页
            showRewardsPage(currentPage);
        })
        .catch(error => console.error('Pjax后获取赞助信息失败:', error));
}

// 添加pjax:complete事件监听
document.addEventListener('pjax:complete', handlePjaxComplete);

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 赞助信息会在页面加载时自动获取并显示
});