const BASE_URL = window.HuSNS_Index?.apiUrls?.base || window.location.origin;
let currentFilter = 'all';
let currentPage = 1;
let hasMore = true;
let isLoading = false;

document.addEventListener('DOMContentLoaded', function() {
    loadReports(true);
    
    window.addEventListener('scroll', function() {
        if (hasMore && !isLoading) {
            const scrollHeight = document.documentElement.scrollHeight;
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            const clientHeight = document.documentElement.clientHeight;
            if (scrollTop + clientHeight >= scrollHeight - 100) {
                loadReports(false);
            }
        }
    });
});

function filterReports(filter) {
    if (filter === currentFilter) return;
    currentFilter = filter;
    currentPage = 1;
    hasMore = true;
    
    document.querySelectorAll('.page-tab').forEach(function(tab) {
        tab.classList.remove('active');
    });
    event.target.classList.add('active');
    
    loadReports(true);
}

async function loadReports(reset) {
    if (isLoading) return;
    if (!reset && !hasMore) return;
    
    isLoading = true;
    
    if (reset) {
        currentPage = 1;
        hasMore = true;
        document.getElementById('reportList').innerHTML = '<div class="loading-indicator">加载中...</div>';
    }
    
    try {
        let url = BASE_URL + '/?r=mobileApi/getMyReports&page=' + currentPage;
        if (currentFilter !== 'all') {
            url += '&status=' + (currentFilter === 'pending' ? '0' : '1');
        }
        
        const response = await fetch(url);
        const result = await response.json();

        const container = document.getElementById('reportList');

        if (result.code === 0 && result.data) {
            const reports = result.data.items || result.data || [];
            
            if (reset && reports.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon">📭</div>
                        <div>暂无举报记录</div>
                        <div style="font-size: 12px; margin-top: 8px;">举报内容后可在此处查看处理进度</div>
                    </div>
                `;
                hasMore = false;
            } else {
                if (reset) {
                    container.innerHTML = '';
                }
                
                reports.forEach(function(report) {
                    container.insertAdjacentHTML('beforeend', renderReportItem(report));
                });
                
                hasMore = result.data.pagination ? result.data.pagination.has_more : false;
                currentPage++;
                
                if (hasMore) {
                    const existingLoadMore = container.querySelector('.load-more');
                    if (!existingLoadMore) {
                        container.insertAdjacentHTML('beforeend', '<div class="load-more" onclick="loadReports(false)">加载更多</div>');
                    }
                } else {
                    const existingLoadMore = container.querySelector('.load-more');
                    if (existingLoadMore) existingLoadMore.remove();
                }
            }
        } else if (result.code === 401) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">🔒</div>
                    <div>请先登录</div>
                </div>
            `;
            hasMore = false;
        } else {
            throw new Error(result.message || '加载失败');
        }
    } catch (error) {
        console.error('加载举报列表失败:', error);
        document.getElementById('reportList').innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">❌</div>
                <div>加载失败，请重试</div>
                <div style="margin-top: 8px;"><a href="javascript:;" onclick="loadReports(true)">点击重新加载</a></div>
            </div>
        `;
    } finally {
        isLoading = false;
    }
}

function renderReportItem(report) {
    const reasonMap = {
        spam: '垃圾广告',
        porn: '色情低俗',
        violence: '暴力血腥',
        fraud: '欺诈诈骗',
        harassment: '人身攻击',
        privacy: '侵犯隐私',
        copyright: '抄袭侵权',
        other: '其他'
    };

    const statusMap = {
        0: { label: '待处理', class: 'pending' },
        1: { label: '已处理', class: 'resolved' },
        2: { label: '已驳回', class: 'dismissed' }
    };

    const status = statusMap[report.status] || statusMap[0];

    let handleResult = '';
    if (report.status === 1 && report.handle_result) {
        handleResult = '<div class="report-handle-result"><strong>处理结果：</strong>' + escapeHtml(report.handle_result) + '</div>';
    } else if (report.status === 2) {
        handleResult = '<div class="report-handle-result"><strong>驳回原因：</strong>管理员认为该内容未违规</div>';
    }

    return `
        <div class="report-item" data-id="${report.id}">
            <div class="report-header">
                <span>举报 #${report.id}</span>
                <span class="report-status ${status.class}">${status.label}</span>
            </div>
            <div class="report-content">
                <div class="report-reason">${reasonMap[report.reason] || report.reason}</div>
                ${report.detail ? `<div class="report-detail">${escapeHtml(report.detail)}</div>` : ''}
                <div class="report-time">举报时间：${formatTime(report.created_at)}</div>
            </div>
            ${report.post ? `
                <div class="post-preview">
                    <div class="post-preview-content">${escapeHtml(report.post.content || '')}</div>
                    <div class="post-preview-user">@${escapeHtml(report.post.username || '')}</div>
                </div>
            ` : ''}
            ${handleResult}
            ${report.post_id ? `
                <div class="report-actions">
                    <button class="report-action-btn view" onclick="viewPost(${report.post_id})">查看原帖</button>
                </div>
            ` : ''}
        </div>
    `;
}

function viewPost(postId) {
    window.location.href = BASE_URL + '/?r=mobile/detail&id=' + postId;
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
}