var currentPoints = 0;
const BASE_URL = window.HuSNS_Index?.apiUrls?.base || '/';

document.addEventListener('DOMContentLoaded', function() {
    loadUserPoints();
    loadPointRules();
    loadPointLogs();
    loadLevels();
});

function showTab(tabName) {
    document.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
    event.target.classList.add('active');
    
    document.querySelectorAll('.tab-content').forEach(c => c.style.display = 'none');
    document.getElementById(tabName + 'Tab').style.display = 'block';
    
    if (tabName === 'history') {
        loadPointLogs();
    } else if (tabName === 'levels') {
        loadLevels();
    }
}

function loadUserPoints() {
    fetch(BASE_URL + '/?r=mobileApi/getUserPoints')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data) {
                currentPoints = data.data.points || 0;
                
                document.getElementById('userPoints').textContent = currentPoints;
                document.getElementById('userLevel').textContent = (data.data.level || {}).name || '新手';
                document.getElementById('levelIcon').textContent = (data.data.level || {}).icon || '🌱';
                
                if (data.data.next_level) {
                    document.getElementById('progressText').textContent = 
                        `距离 ${data.data.next_level.name} 还需 ${data.data.points_to_next} 积分`;
                } else {
                    document.getElementById('progressText').textContent = '已达到最高等级';
                }
                
                document.getElementById('progressFill').style.width = (data.data.progress || 0) + '%';
            }
        })
        .catch(() => {});
}

function loadPointRules() {
    fetch(BASE_URL + '/?r=mobileApi/point/getRules')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data && data.data.length > 0) {
                const icons = {
                    'publish_post': '📝',
                    'publish_comment': '💬',
                    'receive_like': '❤️',
                    'receive_comment': '💬',
                    'follow_user': '👥',
                    'be_followed': '👤',
                    'send_message': '✉️'
                };
                
                let html = '';
                data.data.forEach(rule => {
                    html += `
                        <div class="rule-item">
                            <div class="rule-icon">${icons[rule.action] || '🎁'}</div>
                            <div class="rule-name">${rule.name}</div>
                            <div class="rule-points">+${rule.points}</div>
                        </div>
                    `;
                });
                document.getElementById('rulesList').innerHTML = html;
            } else {
                document.getElementById('rulesList').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon"><span class="iconify" data-icon="mdi:gift"></span></div>
                        <div class="empty-text">暂无积分规则</div>
                    </div>
                `;
            }
        })
        .catch(() => {
            document.getElementById('rulesList').innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon"><span class="iconify" data-icon="mdi:alert-circle"></span></div>
                    <div class="empty-text">加载失败</div>
                </div>
            `;
        });
}

function loadPointLogs() {
    fetch(BASE_URL + '/?r=mobileApi/getPointLogs')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data && data.data.items && data.data.items.length > 0) {
                const actionNames = {
                    'publish_post': '发布动态',
                    'publish_comment': '发表评论',
                    'receive_like': '获得点赞',
                    'receive_comment': '获得评论',
                    'follow_user': '关注用户',
                    'be_followed': '被关注',
                    'send_message': '发送私信'
                };
                
                let html = '';
                data.data.items.forEach(log => {
                    const isPositive = log.points > 0;
                    html += `
                        <div class="log-item">
                            <div class="log-info">
                                <div class="log-action">${actionNames[log.action] || log.action}</div>
                                <div class="log-time">${log.created_at}</div>
                            </div>
                            <div class="log-points ${isPositive ? 'positive' : 'negative'}">
                                ${isPositive ? '+' : ''}${log.points}
                            </div>
                        </div>
                    `;
                });
                document.getElementById('logsList').innerHTML = html;
            } else {
                document.getElementById('logsList').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon"><span class="iconify" data-icon="mdi:history"></span></div>
                        <div class="empty-text">暂无积分记录</div>
                    </div>
                `;
            }
        })
        .catch(() => {
            document.getElementById('logsList').innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon"><span class="iconify" data-icon="mdi:alert-circle"></span></div>
                    <div class="empty-text">加载失败</div>
                </div>
            `;
        });
}

function loadLevels() {
    fetch(BASE_URL + '/?r=mobileApi/getLevelConfig')
        .then(r => r.json())
        .then(data => {
            if (data.code === 0 && data.data && data.data.items.length > 0) {
                let html = '';
                data.data.items.forEach(level => {
                    const isCurrent = currentPoints >= level.min_points && currentPoints <= level.max_points;
                    html += `
                        <div class="level-item ${isCurrent ? 'current' : ''}">
                            <div class="level-icon">${level.icon}</div>
                            <div class="level-info">
                                <div class="level-name">${level.name}</div>
                                <div class="level-range">${level.min_points}-${level.max_points} 积分</div>
                            </div>
                            <div class="level-number">Lv.${level.level}</div>
                        </div>
                    `;
                });
                document.getElementById('levelsList').innerHTML = html;
            } else {
                document.getElementById('levelsList').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon"><span class="iconify" data-icon="mdi:trophy"></span></div>
                        <div class="empty-text">暂无等级信息</div>
                    </div>
                `;
            }
        })
        .catch(() => {
            document.getElementById('levelsList').innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon"><span class="iconify" data-icon="mdi:alert-circle"></span></div>
                    <div class="empty-text">加载失败</div>
                </div>
            `;
        });
}