// GO想頁面 JavaScript 功能

// 模擬公告資料
const mockAnnouncements = [
    {
        id: '1',
        type: 'emergency',
        title: '緊急通知：社區停水公告',
        content: '因水管維修工程，本社區將於明日上午8:00-下午6:00進行停水作業，請各位里民提前做好儲水準備。造成不便敬請見諒。',
        keywords: ['停水', '維修', '緊急'],
        publishedAt: '2025-01-17',
        pinnedUntil: '2025-01-20',
        photos: ['images/1.jpg']
    },
    {
        id: '2',
        type: 'event',
        title: '社區健康講座',
        content: '邀請專業醫師分享健康養生知識，歡迎全體里民踴躍參加。現場提供免費健康檢測服務。',
        keywords: ['健康', '講座', '醫師'],
        publishedAt: '2025-01-16',
        eventMeta: {
            location: '社區活動中心',
            date: '2025-01-25',
            timeSlot: '14:00'
        },
        photos: ['images/2.jpg']
    },
    {
        id: '3',
        type: 'general',
        title: '社區環境清潔日',
        content: '為維護社區環境品質，將定期舉辦清潔日活動，歡迎里民共同參與，一起打造美好家園。',
        keywords: ['清潔', '環境', '參與'],
        publishedAt: '2025-01-15',
        photos: ['images/3.png']
    },
    {
        id: '4',
        type: 'event',
        title: '新春團拜活動',
        content: '農曆新年將至，社區將舉辦團拜活動，共同迎接新年到來。活動包含表演、摸彩等精彩內容。',
        keywords: ['新春', '團拜', '活動'],
        publishedAt: '2025-01-14',
        eventMeta: {
            location: '社區廣場',
            date: '2025-01-30',
            timeSlot: '18:30'
        },
        photos: ['images/1.jpg']
    },
    {
        id: '5',
        type: 'general',
        title: '垃圾分類宣導',
        content: '響應環保政策，請里民確實做好垃圾分類工作。詳細分類方式請參考社區公布欄說明。',
        keywords: ['垃圾分類', '環保', '宣導'],
        publishedAt: '2025-01-13',
        photos: []
    }
];

// 頁面狀態
let currentView = 'latest'; // 'latest' 或 'all'
let currentFilter = 'all';
let currentPage = 1;
let isSearchActive = false;
let searchQuery = '';

// DOM 元素
let latestAnnouncementsContainer;
let allAnnouncementsContainer;
let allAnnouncementsSection;
let searchContainer;
let searchInput;
let clearSearchBtn;
let filterBtns;
let loadMoreBtn;

// 頁面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    initializeSearch();
    initializeFilters();
    loadLatestAnnouncements();
    
    console.log('GO想頁面初始化完成');
});

// 初始化 DOM 元素
function initializeElements() {
    latestAnnouncementsContainer = document.getElementById('latestAnnouncements');
    allAnnouncementsContainer = document.getElementById('allAnnouncements');
    allAnnouncementsSection = document.getElementById('allAnnouncementsSection');
    searchContainer = document.getElementById('searchContainer');
    searchInput = document.getElementById('searchInput');
    clearSearchBtn = document.getElementById('clearSearch');
    loadMoreBtn = document.getElementById('loadMoreBtn');
    
    // 篩選按鈕
    filterBtns = document.querySelectorAll('.filter-btn');
}


// 初始化搜尋功能
function initializeSearch() {
    const searchToggle = document.getElementById('searchToggle');
    
    if (searchToggle) {
        searchToggle.addEventListener('click', toggleSearch);
    }
    
    if (searchInput) {
        searchInput.addEventListener('input', handleSearchInput);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }
    
    if (clearSearchBtn) {
        clearSearchBtn.addEventListener('click', clearSearch);
    }
}

// 切換搜尋顯示
function toggleSearch() {
    isSearchActive = !isSearchActive;
    
    if (isSearchActive) {
        searchContainer.style.display = 'block';
        setTimeout(() => {
            searchInput.focus();
        }, 100);
    } else {
        searchContainer.style.display = 'none';
        clearSearch();
    }
}

// 處理搜尋輸入
function handleSearchInput() {
    const value = searchInput.value.trim();
    
    if (value) {
        clearSearchBtn.style.display = 'block';
    } else {
        clearSearchBtn.style.display = 'none';
    }
    
    // 即時搜尋（延遲300ms）
    clearTimeout(window.searchTimeout);
    window.searchTimeout = setTimeout(() => {
        searchQuery = value;
        performSearch();
    }, 300);
}

// 執行搜尋
function performSearch() {
    if (currentView === 'latest') {
        showAllAnnouncements();
    }
    
    loadAnnouncements(1, currentFilter, searchQuery);
}

// 清除搜尋
function clearSearch() {
    searchInput.value = '';
    clearSearchBtn.style.display = 'none';
    searchQuery = '';
    
    if (currentView === 'all') {
        loadAnnouncements(1, currentFilter);
    }
}

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

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

// 載入最新公告
function loadLatestAnnouncements() {
    const container = latestAnnouncementsContainer;
    if (!container) return;
    
    // 顯示載入骨架
    container.innerHTML = generateSkeletonHTML(3);
    
    // 模擬 API 調用延遲
    setTimeout(() => {
        const latestAnnouncements = mockAnnouncements.slice(0, 3);
        container.innerHTML = latestAnnouncements.map(announcement => 
            generateAnnouncementHTML(announcement)
        ).join('');
        
        // 添加點擊事件
        addAnnouncementClickEvents(container);
    }, 500);
}

// 載入所有公告
function loadAnnouncements(page = 1, filter = 'all', query = '') {
    const container = allAnnouncementsContainer;
    if (!container) return;
    
    if (page === 1) {
        // 顯示載入骨架
        container.innerHTML = generateSkeletonHTML(5);
    }
    
    // 模擬 API 調用延遲
    setTimeout(() => {
        let filteredAnnouncements = mockAnnouncements;
        
        // 應用篩選器
        if (filter !== 'all') {
            filteredAnnouncements = filteredAnnouncements.filter(
                announcement => announcement.type === filter
            );
        }
        
        // 應用搜尋
        if (query) {
            const lowerQuery = query.toLowerCase();
            filteredAnnouncements = filteredAnnouncements.filter(
                announcement => 
                    announcement.title.toLowerCase().includes(lowerQuery) ||
                    announcement.content.toLowerCase().includes(lowerQuery) ||
                    announcement.keywords.some(keyword => 
                        keyword.toLowerCase().includes(lowerQuery)
                    )
            );
        }
        
        // 分頁
        const pageSize = 5;
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedAnnouncements = filteredAnnouncements.slice(startIndex, endIndex);
        
        if (page === 1) {
            container.innerHTML = paginatedAnnouncements.map(announcement => 
                generateAnnouncementHTML(announcement)
            ).join('');
        } else {
            container.innerHTML += paginatedAnnouncements.map(announcement => 
                generateAnnouncementHTML(announcement)
            ).join('');
        }
        
        // 添加點擊事件
        addAnnouncementClickEvents(container);
        
        // 更新載入更多按鈕
        const hasMore = endIndex < filteredAnnouncements.length;
        if (loadMoreBtn) {
            loadMoreBtn.style.display = hasMore ? 'block' : 'none';
        }
        
        // 如果沒有結果，顯示提示
        if (filteredAnnouncements.length === 0 && page === 1) {
            container.innerHTML = `
                <div class="no-results">
                    <div class="no-results-icon">📢</div>
                    <h3>沒有找到相關公告</h3>
                    <p>請嘗試調整搜尋條件或篩選器</p>
                </div>
            `;
        }
    }, 300);
}

// 載入更多公告
function loadMoreAnnouncements() {
    currentPage++;
    loadAnnouncements(currentPage, currentFilter, searchQuery);
}

// 生成公告 HTML
function generateAnnouncementHTML(announcement) {
    const typeText = {
        'general': '一般公告',
        'emergency': '緊急公告',
        'event': '活動公告'
    };
    
    const eventInfoHTML = announcement.eventMeta ? `
        <div class="event-info">
            <div class="event-location">
                <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>
                ${announcement.eventMeta.location}
            </div>
            <div class="event-datetime">
                <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>
                ${formatDate(announcement.eventMeta.date)} ${announcement.eventMeta.timeSlot}
            </div>
        </div>
    ` : '';
    
    const keywordsHTML = announcement.keywords.length > 0 ? `
        <div class="announcement-keywords">
            ${announcement.keywords.map(keyword => 
                `<span class="keyword-tag">${keyword}</span>`
            ).join('')}
        </div>
    ` : '';
    
    return `
        <div class="announcement-item ${announcement.type}" data-id="${announcement.id}">
            <div class="announcement-header">
                <span class="announcement-type ${announcement.type}">${typeText[announcement.type]}</span>
                <span class="announcement-date">${formatDate(announcement.publishedAt)}</span>
            </div>
            <h3 class="announcement-title">${announcement.title}</h3>
            <p class="announcement-content">${announcement.content}</p>
            ${eventInfoHTML}
            <div class="announcement-meta">
                ${keywordsHTML}
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8.59 16.59L10 18L16 12L10 6L8.59 7.41L13.17 12L8.59 16.59Z" fill="currentColor"/>
                </svg>
            </div>
        </div>
    `;
}

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

// 添加公告點擊事件
function addAnnouncementClickEvents(container) {
    const items = container.querySelectorAll('.announcement-item');
    items.forEach(item => {
        item.addEventListener('click', () => {
            const announcementId = item.dataset.id;
            viewAnnouncementDetail(announcementId);
        });
    });
}

// 查看公告詳細
function viewAnnouncementDetail(id) {
    // 導航到公告詳細頁面
    const announcement = mockAnnouncements.find(a => a.id === id);
    if (announcement) {
        window.location.href = `announcement-detail.html?id=${id}`;
        console.log('導航到公告詳細頁面:', id);
    }
}

// 顯示所有公告
function showAllAnnouncements() {
    currentView = 'all';
    
    // 隱藏最新公告區塊
    const latestSection = document.querySelector('.latest-announcements');
    if (latestSection) {
        latestSection.style.display = 'none';
    }
    
    // 顯示所有公告區塊
    if (allAnnouncementsSection) {
        allAnnouncementsSection.style.display = 'block';
    }
    
    // 載入所有公告
    currentPage = 1;
    currentFilter = 'all';
    loadAnnouncements(1, 'all', searchQuery);
    
    // 重置篩選器按鈕狀態
    filterBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.filter === 'all');
    });
}

// 返回最新公告檢視
function showLatestAnnouncements() {
    currentView = 'latest';
    
    // 顯示最新公告區塊
    const latestSection = document.querySelector('.latest-announcements');
    if (latestSection) {
        latestSection.style.display = 'block';
    }
    
    // 隱藏所有公告區塊
    if (allAnnouncementsSection) {
        allAnnouncementsSection.style.display = 'none';
    }
}

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

// 前往里民信箱
function goToMailbox() {
    // 導航到里民信箱頁面
    window.location.href = 'citizen-mailbox.html';
}

// 返回上一頁
function goBack() {
    if (currentView === 'all') {
        showLatestAnnouncements();
    } else {
        window.location.href = 'index.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;
        
        // 設定圖示
        switch (type) {
            case 'success':
                toastIcon.textContent = '✓';
                toast.style.background = '#2ed573';
                break;
            case 'error':
                toastIcon.textContent = '✕';
                toast.style.background = '#ff4757';
                break;
            case 'info':
                toastIcon.textContent = 'i';
                toast.style.background = '#3742fa';
                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'
        });
    }
}

// 工具函數：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 工具函數：節流
function throttle(func, limit) {
    let inThrottle;
    return function executedFunction(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 導出主要功能（供其他頁面使用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        showToast,
        formatDate,
        debounce,
        throttle
    };
}
