// 共餐活動列表頁面JavaScript功能

// 全域變數
let currentPage = 1;
let isLoading = false;
let hasMoreData = true;
let currentFilter = 'all';
let allEvents = [];
let displayedEvents = [];
let userParticipations = JSON.parse(localStorage.getItem('meal_participations') || '[]');

// DOM元素
const filterBtn = document.getElementById('filterBtn');
const filterMenu = document.getElementById('filterMenu');
const eventsContainer = document.getElementById('eventsContainer');
const loadingIndicator = document.getElementById('loadingIndicator');
const noResults = document.getElementById('noResults');
const totalEventsEl = document.getElementById('totalEvents');
const openEventsEl = document.getElementById('openEvents');
const myEventsEl = document.getElementById('myEvents');

// 模擬共餐活動資料
const mockEvents = [
    {
        id: 1,
        title: '週末聚餐同樂會',
        type: 'single', // single 或 multi
        visibility: 'public', // public 或 private
        status: 'open', // open, voting, finalized, ended, cancelled
        restaurantId: 1,
        restaurantName: '金華小籠包',
        place: '金華社區活動中心',
        date: '2024-10-20',
        time: '12:00',
        deadline: '2024-10-19 18:00',
        initiator: '王小明',
        maxParticipants: 15,
        currentParticipants: 8,
        description: '大家一起來享用美味小籠包！',
        inviteToken: 'abc123'
    },
    {
        id: 2,
        title: '美食探索投票',
        type: 'multi',
        visibility: 'public',
        status: 'voting',
        restaurantId: null,
        restaurantName: '投票決定',
        place: '金華社區廣場',
        date: '2024-10-22',
        time: '18:30',
        deadline: '2024-10-21 12:00',
        initiator: '李小華',
        maxParticipants: 20,
        currentParticipants: 12,
        votingParticipants: 12,
        description: '讓我們一起投票選擇今晚的美食！',
        restaurants: [2, 3, 4], // 多店投票的餐廳ID
        inviteToken: 'def456'
    },
    {
        id: 3,
        title: '素食健康餐聚',
        type: 'single',
        visibility: 'private',
        status: 'open',
        restaurantId: 5,
        restaurantName: '素食天堂',
        place: '社區健康中心',
        date: '2024-10-25',
        time: '11:30',
        deadline: '2024-10-24 20:00',
        initiator: '張素心',
        maxParticipants: 10,
        currentParticipants: 5,
        description: '推廣健康素食生活',
        inviteToken: 'ghi789'
    },
    {
        id: 4,
        title: '海鮮豐盛晚宴',
        type: 'single',
        visibility: 'public',
        status: 'finalized',
        restaurantId: 6,
        restaurantName: '海鮮大排檔',
        place: '金華海鮮餐廳',
        date: '2024-10-18',
        time: '19:00',
        deadline: '2024-10-17 15:00',
        initiator: '陳大海',
        maxParticipants: 25,
        currentParticipants: 22,
        description: '新鮮海鮮，歡樂聚餐',
        inviteToken: 'jkl012'
    },
    {
        id: 5,
        title: '拉麵夜宵聚會',
        type: 'single',
        visibility: 'public',
        status: 'ended',
        restaurantId: 3,
        restaurantName: '日式拉麵屋',
        place: '拉麵店內',
        date: '2024-10-15',
        time: '21:00',
        deadline: '2024-10-15 18:00',
        initiator: '田中一郎',
        maxParticipants: 8,
        currentParticipants: 8,
        description: '深夜拉麵，暖心聚會',
        inviteToken: 'mno345'
    },
    {
        id: 6,
        title: '牛肉麵品嚐會',
        type: 'single',
        visibility: 'public',
        status: 'open',
        restaurantId: 4,
        restaurantName: '老王牛肉麵',
        place: '老王麵店',
        date: '2024-10-28',
        time: '12:30',
        deadline: '2024-10-27 20:00',
        initiator: '老王',
        maxParticipants: 12,
        currentParticipants: 3,
        description: '傳統好味道，等你來品嚐',
        inviteToken: 'pqr678'
    }
];

// 從GO食頁面的餐廳資料導入
const restaurantsData = {
    1: { name: '金華小籠包', tags: ['小籠包', '台式早餐'] },
    2: { name: '阿嬤的味道', tags: ['傳統小吃', '家常菜'] },
    3: { name: '日式拉麵屋', tags: ['拉麵', '日式料理'] },
    4: { name: '老王牛肉麵', tags: ['牛肉麵', '傳統美食'] },
    5: { name: '素食天堂', tags: ['素食', '健康'] },
    6: { name: '海鮮大排檔', tags: ['海鮮', '熱炒'] }
};

// 初始化頁面
document.addEventListener('DOMContentLoaded', function() {
    initializeMealEvents();
    setupEventListeners();
    loadEvents();
});

// 初始化共餐活動頁面
function initializeMealEvents() {
    // 更新統計數據
    updateStats();
    
    // 顯示歡迎提示
    showToast('探索社區共餐活動！', 2000);
}

// 設定事件監聽器
function setupEventListeners() {
    // 篩選按鈕
    filterBtn.addEventListener('click', toggleFilterMenu);
    
    // 篩選選項
    const filterOptions = document.querySelectorAll('.filter-option');
    filterOptions.forEach(option => {
        option.addEventListener('click', (e) => {
            setFilter(e.target.dataset.filter);
        });
    });
    
    // 點擊外部關閉篩選選單
    document.addEventListener('click', (e) => {
        if (!filterBtn.contains(e.target) && !filterMenu.contains(e.target)) {
            filterMenu.style.display = 'none';
        }
    });
    
    // 無限捲動
    window.addEventListener('scroll', handleInfiniteScroll);
}

// 切換篩選選單
function toggleFilterMenu() {
    const isVisible = filterMenu.style.display === 'block';
    filterMenu.style.display = isVisible ? 'none' : 'block';
}

// 設定篩選條件
function setFilter(filter) {
    currentFilter = filter;
    
    // 更新篩選選項UI
    document.querySelectorAll('.filter-option').forEach(option => {
        option.classList.remove('active');
    });
    document.querySelector(`[data-filter="${filter}"]`).classList.add('active');
    
    // 關閉選單
    filterMenu.style.display = 'none';
    
    // 重新載入活動
    currentPage = 1;
    eventsContainer.innerHTML = '';
    displayedEvents = [];
    hasMoreData = true;
    loadEvents();
    
    // 顯示篩選提示
    const filterNames = {
        'all': '所有活動',
        'open': '可參加活動',
        'voting': '投票中活動',
        'public': '公開活動',
        'private': '私人活動'
    };
    showToast(`已切換至：${filterNames[filter]}`, 2000);
}

// 載入活動資料
function loadEvents() {
    if (isLoading || !hasMoreData) return;
    
    isLoading = true;
    loadingIndicator.style.display = 'flex';
    noResults.style.display = 'none';
    
    // 模擬API延遲
    setTimeout(() => {
        const filteredEvents = filterEvents();
        const itemsPerPage = 3;
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const pageEvents = filteredEvents.slice(startIndex, endIndex);
        
        if (pageEvents.length === 0) {
            if (currentPage === 1) {
                noResults.style.display = 'block';
            }
            hasMoreData = false;
        } else {
            displayedEvents = [...displayedEvents, ...pageEvents];
            renderEvents(pageEvents);
            currentPage++;
            
            // 檢查是否還有更多資料
            if (endIndex >= filteredEvents.length) {
                hasMoreData = false;
            }
        }
        
        isLoading = false;
        loadingIndicator.style.display = hasMoreData ? 'none' : 'none';
        
        if (!hasMoreData && displayedEvents.length > 0) {
            setTimeout(() => {
                showToast('已載入所有活動', 1500);
            }, 500);
        }
    }, 800);
}

// 過濾活動
function filterEvents() {
    let filtered = [...mockEvents];
    
    switch (currentFilter) {
        case 'open':
            filtered = filtered.filter(event => event.status === 'open' || event.status === 'voting');
            break;
        case 'voting':
            filtered = filtered.filter(event => event.status === 'voting');
            break;
        case 'public':
            filtered = filtered.filter(event => event.visibility === 'public');
            break;
        case 'private':
            filtered = filtered.filter(event => event.visibility === 'private');
            break;
        default: // 'all'
            break;
    }
    
    // 按日期排序（最新的在前）
    filtered.sort((a, b) => new Date(b.date + ' ' + b.time) - new Date(a.date + ' ' + a.time));
    
    return filtered;
}

// 渲染活動列表
function renderEvents(events) {
    const fragment = document.createDocumentFragment();
    
    events.forEach((event, index) => {
        const eventCard = createEventCard(event);
        
        // 添加延遲動畫
        setTimeout(() => {
            fragment.appendChild(eventCard);
            eventsContainer.appendChild(fragment);
        }, index * 100);
    });
}

// 創建活動卡片
function createEventCard(event) {
    const card = document.createElement('div');
    card.className = 'event-card';
    card.dataset.eventId = event.id;
    
    const statusText = getStatusText(event.status);
    const statusClass = getStatusClass(event.status, event.visibility);
    const isUserParticipated = userParticipations.includes(event.id);
    const progressPercentage = Math.round((event.currentParticipants / event.maxParticipants) * 100);
    
    // 格式化日期時間
    const eventDate = new Date(event.date + ' ' + event.time);
    const formattedDate = formatDate(eventDate);
    const formattedTime = formatTime(eventDate);
    
    // 判斷是否可以參加
    const canJoin = ['open', 'voting'].includes(event.status) && !isUserParticipated;
    const joinButtonText = event.status === 'voting' ? '參與投票' : '加入共餐';
    
    card.innerHTML = `
        <div class="event-header">
            <h3 class="event-title">${event.title}</h3>
            <div class="event-restaurant">${event.restaurantName}</div>
            <div class="event-type-indicator ${event.type}">
                ${event.type === 'single' ? '單店聚餐' : '多店投票'}
            </div>
            <div class="event-status ${statusClass}">${statusText}</div>
            ${isUserParticipated ? '<div class="participation-badge">已參加</div>' : ''}
        </div>
        
        <div class="event-details">
            <div class="event-info-grid">
                <div class="event-info-item">
                    <svg class="event-info-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M19 3H18V1H16V3H8V1H6V3H5C3.89 3 3.01 3.9 3.01 5L3 19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.9 20.1 3 19 3ZM19 19H5V8H19V19Z" fill="currentColor"/>
                    </svg>
                    <span>${formattedDate}</span>
                </div>
                
                <div class="event-info-item">
                    <svg class="event-info-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2C6.5 2 2 6.5 2 12S6.5 22 12 22 22 17.5 22 12 17.5 2 12 2ZM17 13H11V7H12.5V11.5H17V13Z" fill="currentColor"/>
                    </svg>
                    <span>${formattedTime}</span>
                </div>
                
                <div class="event-info-item">
                    <svg class="event-info-icon" 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.5 14.5 7.62 14.5 9 13.38 11.5 12 11.5Z" fill="currentColor"/>
                    </svg>
                    <span>${event.place}</span>
                </div>
                
                <div class="event-info-item">
                    <svg class="event-info-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M16 4C15.71 4 15.38 4.05 15.03 4.14L16.5 5.61C16.31 5.86 16.04 6 15.72 6H14.5C14.22 6 14 6.22 14 6.5V7.28C14.61 7.75 15 8.47 15 9.25V11.75C15 12.44 14.69 13.08 14.12 13.5L15.5 14.88C15.81 14.96 16.15 15 16.5 15H17C18.1 15 19 14.1 19 13V12C19 10.9 18.1 10 17 10H16.5C16.22 10 16 9.78 16 9.5S16.22 9 16.5 9H17C18.1 9 19 8.1 19 7V6C19 4.9 18.1 4 17 4H16ZM12 2L13.09 4.26L15 4L14.26 6.09L16 7L13.09 7.74L12 10L10.91 7.74L8 7L9.74 6.09L9 4L10.91 4.26L12 2ZM7 12C5.9 12 5 12.9 5 14V18C5 19.1 5.9 20 7 20H17C18.1 20 19 19.1 19 18V16L17 14V18H7V14C7 13.45 7.45 13 8 13H11V11H8C7.45 11 7 11.45 7 12Z" fill="currentColor"/>
                    </svg>
                    <span>${event.initiator} 發起</span>
                </div>
            </div>
            
            ${event.description ? `<p class="event-description">${event.description}</p>` : ''}
            
            <div class="event-participants">
                <div class="participants-header">
                    <h4 class="participants-title">
                        ${event.status === 'voting' ? '投票參與' : '參加人數'}
                    </h4>
                    <span class="participants-count">
                        ${event.status === 'voting' ? event.votingParticipants : event.currentParticipants}/${event.maxParticipants}
                    </span>
                </div>
                <div class="participants-progress">
                    <div class="participants-progress-bar" style="width: ${progressPercentage}%"></div>
                </div>
            </div>
            
            ${canJoin ? `
                <button class="join-event-btn" onclick="handleEventAction(${event.id}, '${event.status}')">
                    ${joinButtonText}
                </button>
            ` : ''}
        </div>
    `;
    
    // 添加樣式
    if (canJoin) {
        const joinBtn = card.querySelector('.join-event-btn');
        if (joinBtn) {
            joinBtn.style.cssText = `
                background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
                color: white;
                border: none;
                border-radius: 8px;
                padding: 12px 20px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                margin-top: 15px;
                width: 100%;
                transition: all 0.3s;
            `;
        }
    }
    
    if (isUserParticipated) {
        const badge = card.querySelector('.participation-badge');
        if (badge) {
            badge.style.cssText = `
                position: absolute;
                top: 60px;
                right: 20px;
                background: #4CAF50;
                color: white;
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 600;
            `;
        }
    }
    
    const description = card.querySelector('.event-description');
    if (description) {
        description.style.cssText = `
            margin: 15px 0;
            color: var(--text-secondary);
            font-size: 15px;
            line-height: 1.4;
        `;
    }
    
    // 點擊事件（排除按鈕區域）
    card.addEventListener('click', (e) => {
        if (!e.target.closest('.join-event-btn')) {
            showEventDetails(event);
        }
    });
    
    return card;
}

// 處理活動操作
function handleEventAction(eventId, status) {
    const event = mockEvents.find(e => e.id === eventId);
    if (!event) return;
    
    if (status === 'voting') {
        // 跳轉到投票頁面
        window.location.href = `meal-detail.html?id=${eventId}&action=vote`;
    } else {
        // 跳轉到選餐頁面
        window.location.href = `meal-detail.html?id=${eventId}&action=join`;
    }
}

// 顯示活動詳情
function showEventDetails(event) {
    window.location.href = `meal-detail.html?id=${event.id}`;
}

// 獲取狀態文字
function getStatusText(status) {
    const statusTexts = {
        'open': '開放報名',
        'voting': '投票中',
        'finalized': '已確定',
        'ended': '已結束',
        'cancelled': '已取消'
    };
    return statusTexts[status] || status;
}

// 獲取狀態樣式類別
function getStatusClass(status, visibility) {
    if (status === 'ended' || status === 'cancelled') return 'ended';
    if (status === 'voting') return 'voting';
    if (visibility === 'private') return 'private';
    return 'public';
}

// 格式化日期
function formatDate(date) {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    if (date.toDateString() === today.toDateString()) {
        return '今天';
    } else if (date.toDateString() === tomorrow.toDateString()) {
        return '明天';
    } else {
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const weekday = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
        return `${month}/${day} (${weekday})`;
    }
}

// 格式化時間
function formatTime(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
}

// 更新統計數據
function updateStats() {
    const totalEvents = mockEvents.length;
    const openEvents = mockEvents.filter(e => ['open', 'voting'].includes(e.status)).length;
    const myEvents = userParticipations.length;
    
    // 數字動畫效果
    animateNumber(totalEventsEl, 0, totalEvents, 1000);
    animateNumber(openEventsEl, 0, openEvents, 1200);
    animateNumber(myEventsEl, 0, myEvents, 1400);
}

// 數字動畫
function animateNumber(element, start, end, duration) {
    const range = end - start;
    const increment = range / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }
        element.textContent = Math.round(current);
    }, 16);
}

// 處理無限捲動
function handleInfiniteScroll() {
    if (isLoading || !hasMoreData) return;
    
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.offsetHeight;
    
    if (scrollTop + windowHeight >= documentHeight - 100) {
        loadEvents();
    }
}

// 返回上一頁
function goBack() {
    if (document.referrer && document.referrer.includes(window.location.host)) {
        history.back();
    } else {
        window.location.href = 'gofood.html';
    }
}

// Toast 提示功能（重用首頁的函數）
function showToast(message, duration = 3000) {
    // 移除現有的 toast
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
        existingToast.remove();
    }

    // 創建 toast 元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    // 添加 toast 樣式
    Object.assign(toast.style, {
        position: 'fixed',
        bottom: '30px',
        left: '50%',
        transform: 'translateX(-50%)',
        backgroundColor: 'var(--primary-color)',
        color: 'white',
        padding: '16px 24px',
        borderRadius: '8px',
        fontSize: '16px',
        fontWeight: '500',
        boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
        zIndex: '10000',
        opacity: '0',
        transition: 'all 0.3s ease',
        maxWidth: '90%',
        textAlign: 'center'
    });

    document.body.appendChild(toast);

    // 顯示動畫
    setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(-50%) translateY(-10px)';
    }, 100);

    // 自動隱藏
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(-50%) translateY(20px)';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.remove();
            }
        }, 300);
    }, duration);
}

// 全域函數
window.goBack = goBack;
window.handleEventAction = handleEventAction;
