// 里民信箱頁面 JavaScript 功能

// 模擬回報資料
const mockReports = [
    {
        id: '1',
        title: '社區大門照明設備故障',
        location: '社區大門口',
        date: '2025-01-15',
        timeSlot: '20:30',
        content: '社區大門口的照明設備已經故障好幾天了，晚上進出很不方便，也影響社區安全，希望能盡快修復。',
        status: 'replied',
        submittedAt: '2025-01-15T20:35:00Z',
        photos: ['images/1.jpg', 'images/2.jpg'],
        hasUnread: false,
        replies: [
            {
                id: 'r1',
                responderId: 'admin1',
                responderName: '管理員',
                message: '您好，感謝您的回報。我們已經聯繫維修廠商，預計本週內完成修復作業。',
                photos: [],
                createdAt: '2025-01-16T09:30:00Z',
                isPrivate: true
            }
        ]
    },
    {
        id: '2',
        title: 'A棟電梯噪音問題',
        location: 'A棟電梯',
        date: '2025-01-14',
        timeSlot: '08:00',
        content: 'A棟電梯運行時會發出異常噪音，特別是在早上和晚上，影響住戶休息。希望能安排檢修。',
        status: 'pending',
        submittedAt: '2025-01-14T08:15:00Z',
        photos: ['images/3.png'],
        hasUnread: false,
        replies: []
    },
    {
        id: '3',
        title: '垃圾分類宣導建議',
        location: '社區垃圾回收區',
        date: '2025-01-13',
        timeSlot: null,
        content: '建議在垃圾回收區增設分類指示牌，協助住戶正確分類垃圾，提升回收效率。',
        status: 'replied',
        submittedAt: '2025-01-13T16:20:00Z',
        photos: [],
        hasUnread: true,
        replies: [
            {
                id: 'r2',
                responderId: 'admin1',
                responderName: '管理員',
                message: '感謝您的建議！我們已採納您的意見，將在下週安裝新的分類指示牌。',
                photos: ['images/1.jpg'],
                createdAt: '2025-01-17T10:15:00Z',
                isPrivate: true
            }
        ]
    },
    {
        id: '4',
        title: '社區花園維護',
        location: '社區中庭花園',
        date: '2025-01-12',
        timeSlot: '15:30',
        content: '社區花園的植物需要修剪和維護，建議定期安排園藝師進行整理。',
        status: 'canceled',
        submittedAt: '2025-01-12T15:45:00Z',
        photos: [],
        hasUnread: false,
        replies: [],
        canceledAt: '2025-01-13T10:00:00Z'
    }
];

// 頁面狀態
let currentFilter = 'all';
let selectedReportId = null;

// DOM 元素
let reportsContainer;
let emptyState;
let filterBtns;
let reportDetailModal;
let cancelModal;
let totalReports, pendingReports, repliedReports;

// 頁面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    initializeFilters();
    loadReports();
    updateStats();
    
    console.log('里民信箱頁面初始化完成');
});

// 初始化 DOM 元素
function initializeElements() {
    reportsContainer = document.getElementById('reportsContainer');
    emptyState = document.getElementById('emptyState');
    reportDetailModal = document.getElementById('reportDetailModal');
    cancelModal = document.getElementById('cancelModal');
    
    totalReports = document.getElementById('totalReports');
    pendingReports = document.getElementById('pendingReports');
    repliedReports = document.getElementById('repliedReports');
    
    filterBtns = document.querySelectorAll('.filter-btn');
}

// 初始化篩選器
function initializeFilters() {
    filterBtns.forEach(btn => {
        btn.addEventListener('click', handleFilterClick);
    });
}

// 處理篩選器點擊
function handleFilterClick(e) {
    const filter = e.target.dataset.status;
    
    // 更新按鈕狀態
    filterBtns.forEach(btn => {
        btn.classList.remove('active');
    });
    e.target.classList.add('active');
    
    currentFilter = filter;
    loadReports();
}

// 載入回報列表
function loadReports() {
    if (!reportsContainer) return;
    
    // 顯示載入骨架
    reportsContainer.innerHTML = generateSkeletonHTML(3);
    
    // 模擬 API 調用延遲
    setTimeout(() => {
        let filteredReports = mockReports;
        
        // 應用篩選器
        if (currentFilter !== 'all') {
            filteredReports = filteredReports.filter(
                report => report.status === currentFilter
            );
        }
        
        // 按提交時間排序（最新的在前面）
        filteredReports.sort((a, b) => new Date(b.submittedAt) - new Date(a.submittedAt));
        
        if (filteredReports.length === 0) {
            // 顯示空狀態
            reportsContainer.style.display = 'none';
            emptyState.style.display = 'block';
            
            // 根據篩選器調整空狀態訊息
            const emptyTitle = emptyState.querySelector('.empty-title');
            const emptyMessage = emptyState.querySelector('.empty-message');
            
            switch (currentFilter) {
                case 'pending':
                    emptyTitle.textContent = '沒有審核中的回報';
                    emptyMessage.textContent = '您目前沒有待處理的回報';
                    break;
                case 'replied':
                    emptyTitle.textContent = '沒有已回覆的回報';
                    emptyMessage.textContent = '您還沒有收到任何回覆';
                    break;
                case 'canceled':
                    emptyTitle.textContent = '沒有已撤銷的回報';
                    emptyMessage.textContent = '您沒有撤銷的回報記錄';
                    break;
                default:
                    emptyTitle.textContent = '還沒有回報記錄';
                    emptyMessage.textContent = '點擊右上角「+」按鈕發起新的回報';
            }
        } else {
            // 顯示回報列表
            reportsContainer.style.display = 'flex';
            emptyState.style.display = 'none';
            
            reportsContainer.innerHTML = filteredReports.map(report => 
                generateReportHTML(report)
            ).join('');
            
            // 添加點擊事件
            addReportClickEvents();
        }
    }, 300);
}

// 生成回報 HTML
function generateReportHTML(report) {
    const statusText = {
        'pending': '審核中',
        'replied': '已回覆',
        'canceled': '已撤銷'
    };
    
    const photosCountHTML = report.photos.length > 0 ? `
        <div class="report-photos-count">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="currentColor"/>
            </svg>
            ${report.photos.length} 張照片
        </div>
    ` : '';
    
    const replyIndicatorHTML = report.status === 'replied' ? `
        <div class="report-reply-indicator">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M10 9V5L3 12L10 19V14.9C15 14.9 18.5 16.5 21 20C20 15 17 10 10 9Z" fill="currentColor"/>
            </svg>
            ${report.hasUnread ? '有新回覆' : '已回覆'}
        </div>
    ` : '';
    
    const locationHTML = report.location ? `
        <div class="report-location">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2C8.13 2 5 5.13 5 9C5 14.25 12 22 12 22S19 14.25 19 9C19 5.13 15.87 2 12 2ZM12 11.5C10.62 11.5 9.5 10.38 9.5 9S10.62 6.5 12 6.5S14.5 7.62 14.5 9S13.38 11.5 12 11.5Z" fill="currentColor"/>
            </svg>
            ${report.location}
        </div>
    ` : '';
    
    const unreadClass = report.hasUnread ? 'has-unread' : '';
    
    return `
        <div class="report-item ${report.status} ${unreadClass}" data-report-id="${report.id}">
            <div class="report-header">
                <span class="report-status ${report.status}">${statusText[report.status]}</span>
                <span class="report-date">${formatDate(report.submittedAt)}</span>
            </div>
            <h3 class="report-title">${report.title}</h3>
            ${locationHTML}
            <p class="report-content-preview">${report.content}</p>
            <div class="report-meta">
                ${photosCountHTML}
                ${replyIndicatorHTML}
            </div>
        </div>
    `;
}

// 生成骨架屏 HTML
function generateSkeletonHTML(count) {
    return Array(count).fill().map(() => `
        <div class="skeleton-report loading-skeleton">
            <div class="skeleton-header">
                <div class="skeleton-status loading-skeleton"></div>
                <div class="skeleton-date loading-skeleton"></div>
            </div>
            <div class="skeleton-title loading-skeleton"></div>
            <div class="skeleton-content loading-skeleton"></div>
            <div class="skeleton-content loading-skeleton"></div>
        </div>
    `).join('');
}

// 添加回報點擊事件
function addReportClickEvents() {
    const reportItems = reportsContainer.querySelectorAll('.report-item');
    reportItems.forEach(item => {
        item.addEventListener('click', () => {
            const reportId = item.dataset.reportId;
            viewReportDetail(reportId);
        });
    });
}

// 查看回報詳細
function viewReportDetail(reportId) {
    const report = mockReports.find(r => r.id === reportId);
    if (!report) return;
    
    selectedReportId = reportId;
    
    // 標記為已讀
    if (report.hasUnread) {
        report.hasUnread = false;
        // 重新載入列表更新顯示
        setTimeout(() => loadReports(), 100);
    }
    
    // 生成詳細內容
    generateReportDetailHTML(report);
    
    // 顯示模態框
    showModal(reportDetailModal);
}

// 生成回報詳細 HTML
function generateReportDetailHTML(report) {
    const modalTitle = document.getElementById('reportDetailTitle');
    const modalContent = document.getElementById('reportDetailContent');
    const modalActions = document.getElementById('reportDetailActions');
    
    if (modalTitle) {
        modalTitle.textContent = report.title;
    }
    
    if (modalContent) {
        const photosHTML = report.photos.length > 0 ? `
            <div class="detail-section">
                <div class="detail-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="currentColor"/>
                    </svg>
                    相關照片
                </div>
                <div class="photos-grid">
                    ${report.photos.map(photo => `
                        <div class="photo-item">
                            <img src="${photo}" alt="回報照片" onclick="viewPhoto('${photo}')">
                        </div>
                    `).join('')}
                </div>
            </div>
        ` : '';
        
        const timeHTML = report.timeSlot ? `
            <div class="detail-section">
                <div class="detail-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M16.2,16.2L11,13V7H12.5V12.2L17,14.7L16.2,16.2Z" fill="currentColor"/>
                    </svg>
                    發生時間
                </div>
                <div class="detail-value">${formatDate(report.date)} ${report.timeSlot}</div>
            </div>
        ` : `
            <div class="detail-section">
                <div class="detail-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M9 11H7V13H9V11ZM13 11H11V13H13V11ZM17 11H15V13H17V11ZM19 4H18V2H16V4H8V2H6V4H5C3.89 4 3.01 4.9 3.01 6L3 20C3 21.1 3.89 22 5 22H19C20.1 22 21 21.1 21 20V6C21 4.9 20.1 4 19 4ZM19 20H5V9H19V20Z" fill="currentColor"/>
                    </svg>
                    發生日期
                </div>
                <div class="detail-value">${formatDate(report.date)}</div>
            </div>
        `;
        
        const repliesHTML = report.replies.length > 0 ? `
            <div class="replies-section">
                <div class="detail-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M10 9V5L3 12L10 19V14.9C15 14.9 18.5 16.5 21 20C20 15 17 10 10 9Z" fill="currentColor"/>
                    </svg>
                    管理員回覆
                </div>
                ${report.replies.map(reply => `
                    <div class="reply-item">
                        <div class="reply-header">
                            <span class="reply-author">${reply.responderName}</span>
                            <span class="reply-date">${formatDate(reply.createdAt)}</span>
                        </div>
                        <p class="reply-content">${reply.message}</p>
                        ${reply.photos.length > 0 ? `
                            <div class="reply-photos">
                                <div class="photos-grid">
                                    ${reply.photos.map(photo => `
                                        <div class="photo-item">
                                            <img src="${photo}" alt="回覆照片" onclick="viewPhoto('${photo}')">
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        ` : ''}
                    </div>
                `).join('')}
            </div>
        ` : '';
        
        modalContent.innerHTML = `
            <div class="detail-section">
                <div class="detail-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2C8.13 2 5 5.13 5 9C5 14.25 12 22 12 22S19 14.25 19 9C19 5.13 15.87 2 12 2ZM12 11.5C10.62 11.5 9.5 10.38 9.5 9S10.62 6.5 12 6.5S14.5 7.62 14.5 9S13.38 11.5 12 11.5Z" fill="currentColor"/>
                    </svg>
                    發生地點
                </div>
                <div class="detail-value">${report.location}</div>
            </div>
            
            ${timeHTML}
            
            <div class="detail-section">
                <div class="detail-label">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M14 2H6C4.9 2 4.01 2.9 4.01 4L4 20C4 21.1 4.89 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2ZM18 20H6V4H13V9H18V20Z" fill="currentColor"/>
                    </svg>
                    回報內容
                </div>
                <div class="detail-content">${report.content}</div>
            </div>
            
            ${photosHTML}
            ${repliesHTML}
        `;
    }
    
    // 生成動作按鈕
    if (modalActions) {
        let actionsHTML = '';
        
        if (report.status === 'pending') {
            actionsHTML = `
                <button class="modal-btn cancel-btn" onclick="showCancelConfirm('${report.id}')">撤銷回報</button>
            `;
        }
        
        modalActions.innerHTML = actionsHTML;
    }
}

// 顯示撤銷確認對話框
function showCancelConfirm(reportId) {
    selectedReportId = reportId;
    closeReportDetail();
    setTimeout(() => {
        showModal(cancelModal);
    }, 300);
}

// 關閉撤銷確認對話框
function closeCancelModal() {
    closeModal(cancelModal);
}

// 確認撤銷回報
function confirmCancelReport() {
    if (!selectedReportId) return;
    
    // 更新模擬資料
    const report = mockReports.find(r => r.id === selectedReportId);
    if (report) {
        report.status = 'canceled';
        report.canceledAt = new Date().toISOString();
    }
    
    closeCancelModal();
    showToast('回報已撤銷', 'info');
    
    // 重新載入列表和統計
    loadReports();
    updateStats();
    
    selectedReportId = null;
}

// 關閉回報詳細
function closeReportDetail() {
    closeModal(reportDetailModal);
    selectedReportId = null;
}

// 顯示模態框
function showModal(modal) {
    if (modal) {
        modal.style.display = 'flex';
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
    }
}

// 關閉模態框
function closeModal(modal) {
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
    }
}

// 查看照片
function viewPhoto(photoUrl) {
    // 這裡可以實作照片查看器
    // 暫時使用新視窗開啟
    window.open(photoUrl, '_blank');
}

// 更新統計資訊
function updateStats() {
    const total = mockReports.length;
    const pending = mockReports.filter(r => r.status === 'pending').length;
    const replied = mockReports.filter(r => r.status === 'replied').length;
    
    if (totalReports) totalReports.textContent = total;
    if (pendingReports) pendingReports.textContent = pending;
    if (repliedReports) repliedReports.textContent = replied;
}

// 發起回報
function createReport() {
    window.location.href = 'create-report.html';
}

// 返回上一頁
function goBack() {
    window.location.href = 'goxiang.html';
}

// 顯示 Toast 通知
function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    const toastMessage = toast?.querySelector('.toast-message');
    const toastIcon = toast?.querySelector('.toast-icon');
    
    if (toast && toastMessage) {
        toastMessage.textContent = message;
        
        // 重置類別
        toast.classList.remove('error', 'info', 'success');
        
        // 設定圖示和樣式
        switch (type) {
            case 'success':
                toastIcon.textContent = '✓';
                toast.classList.add('success');
                break;
            case 'error':
                toastIcon.textContent = '✕';
                toast.classList.add('error');
                break;
            case 'info':
                toastIcon.textContent = 'i';
                toast.classList.add('info');
                break;
        }
        
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = now - date;
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
        return '今天';
    } else if (diffDays === 1) {
        return '昨天';
    } else if (diffDays <= 7) {
        return `${diffDays} 天前`;
    } else {
        return date.toLocaleDateString('zh-TW', {
            month: 'long',
            day: 'numeric'
        });
    }
}

// 點擊模態框外部關閉
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
        if (e.target === reportDetailModal) {
            closeReportDetail();
        } else if (e.target === cancelModal) {
            closeCancelModal();
        }
    }
});

// 按 ESC 鍵關閉模態框
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (reportDetailModal?.style.display === 'flex') {
            closeReportDetail();
        } else if (cancelModal?.style.display === 'flex') {
            closeCancelModal();
        }
    }
});

// 導出主要功能（供測試使用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        loadReports,
        viewReportDetail,
        showToast,
        formatDate
    };
}
