// 我的共餐頁面JavaScript功能

// 全域變數
let currentFilter = 'all';
let currentSort = 'date';
let userParticipations = JSON.parse(localStorage.getItem('meal_participations') || '[]');
let myEvents = [];
let isLoading = false;
let selectedEventId = null;

// DOM元素
const totalEventsEl = document.getElementById('totalEvents');
const upcomingEventsEl = document.getElementById('upcomingEvents');
const votingEventsEl = document.getElementById('votingEvents');
const myEventsContainer = document.getElementById('myEventsContainer');
const loadingIndicator = document.getElementById('loadingIndicator');
const emptyState = document.getElementById('emptyState');
const refreshBtn = document.getElementById('refreshBtn');
const sortSelect = document.getElementById('sortSelect');
const previewModal = document.getElementById('previewModal');
const previewTitle = document.getElementById('previewTitle');
const previewBody = document.getElementById('previewBody');
const previewActionBtn = document.getElementById('previewActionBtn');

// 模擬活動資料（與其他頁面同步）
const mockEvents = [
    {
        id: 1,
        title: '週末聚餐同樂會',
        type: 'single',
        visibility: 'public',
        status: 'open',
        restaurantId: 1,
        restaurantName: '金華小籠包',
        place: '金華社區活動中心',
        date: '2024-10-20',
        time: '12:00',
        deadline: '2024-10-19 18:00',
        initiator: '王小明',
        maxParticipants: 15,
        currentParticipants: 8,
        description: '大家一起來享用美味小籠包！',
        myChoice: '小籠包 (8顆)',
        joinedAt: '2024-10-16 14:30'
    },
    {
        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: '讓我們一起投票選擇今晚的美食！',
        myChoice: '日式拉麵屋',
        joinedAt: '2024-10-15 09:15',
        needsVote: true
    },
    {
        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: '傳統好味道，等你來品嚐',
        myChoice: '紅燒牛肉麵',
        joinedAt: '2024-10-17 16:45'
    }
];

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

// 初始化頁面
document.addEventListener('DOMContentLoaded', function() {
    initializeMyMeals();
    loadMyEvents();
});

// 初始化我的共餐頁面
function initializeMyMeals() {
    // 顯示歡迎提示
    showToast('歡迎回到我的共餐！', 2000);
    
    // 設定排序選項
    sortSelect.value = currentSort;
}

// 載入我的活動
function loadMyEvents() {
    if (isLoading) return;
    
    isLoading = true;
    loadingIndicator.style.display = 'flex';
    emptyState.style.display = 'none';
    myEventsContainer.innerHTML = '';
    
    // 模擬API延遲
    setTimeout(() => {
        // 篩選出用戶參與的活動
        myEvents = mockEvents.filter(event => 
            userParticipations.includes(event.id)
        );
        
        // 根據當前篩選條件過濾
        const filteredEvents = filterEvents(myEvents);
        
        // 排序
        const sortedEvents = sortEvents(filteredEvents);
        
        // 更新統計
        updateStatistics();
        
        // 渲染活動
        if (sortedEvents.length === 0) {
            emptyState.style.display = 'block';
        } else {
            renderMyEvents(sortedEvents);
        }
        
        isLoading = false;
        loadingIndicator.style.display = 'none';
        
        showToast(`載入了 ${sortedEvents.length} 個活動`, 1500);
    }, 800);
}

// 過濾活動
function filterEvents(events) {
    const now = new Date();
    
    switch (currentFilter) {
        case 'upcoming':
            return events.filter(event => {
                const eventDate = new Date(`${event.date} ${event.time}`);
                return eventDate > now && ['open', 'voting', 'finalized'].includes(event.status);
            });
        case 'voting':
            return events.filter(event => 
                event.status === 'voting' || event.needsVote
            );
        case 'completed':
            return events.filter(event => {
                const eventDate = new Date(`${event.date} ${event.time}`);
                return eventDate < now || event.status === 'ended';
            });
        default: // 'all'
            return events;
    }
}

// 排序活動
function sortEvents(events) {
    switch (currentSort) {
        case 'date':
            return events.sort((a, b) => 
                new Date(`${b.date} ${b.time}`) - new Date(`${a.date} ${a.time}`)
            );
        case 'status':
            const statusOrder = { 'voting': 0, 'open': 1, 'finalized': 2, 'ended': 3 };
            return events.sort((a, b) => 
                (statusOrder[a.status] || 999) - (statusOrder[b.status] || 999)
            );
        case 'restaurant':
            return events.sort((a, b) => 
                a.restaurantName.localeCompare(b.restaurantName)
            );
        default:
            return events;
    }
}

// 更新統計數據
function updateStatistics() {
    const total = myEvents.length;
    const upcoming = filterEvents(myEvents).length;
    const voting = myEvents.filter(event => 
        event.status === 'voting' || event.needsVote
    ).length;
    
    // 數字動畫
    animateNumber(totalEventsEl, 0, total, 800);
    animateNumber(upcomingEventsEl, 0, upcoming, 1000);
    animateNumber(votingEventsEl, 0, voting, 1200);
}

// 數字動畫
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 renderMyEvents(events) {
    const fragment = document.createDocumentFragment();
    
    events.forEach((event, index) => {
        const eventCard = createMyEventCard(event);
        
        // 延遲動畫
        setTimeout(() => {
            fragment.appendChild(eventCard);
            myEventsContainer.appendChild(fragment);
        }, index * 100);
    });
}

// 創建我的活動卡片
function createMyEventCard(event) {
    const card = document.createElement('div');
    card.className = 'my-event-card';
    card.dataset.eventId = event.id;
    
    const now = new Date();
    const eventDate = new Date(`${event.date} ${event.time}`);
    const statusInfo = getEventStatus(event, now, eventDate);
    const progressPercentage = Math.round((event.currentParticipants / event.maxParticipants) * 100);
    
    card.innerHTML = `
        <div class="my-event-status ${statusInfo.class}">${statusInfo.text}</div>
        
        <div class="my-event-header">
            <h3 class="my-event-title">${event.title}</h3>
            <div class="my-event-restaurant">${event.restaurantName}</div>
        </div>
        
        <div class="my-event-details">
            <div class="my-event-detail">
                <svg class="my-event-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>${formatDate(eventDate)}</span>
            </div>
            
            <div class="my-event-detail">
                <svg class="my-event-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>${formatTime(eventDate)}</span>
            </div>
            
            <div class="my-event-detail">
                <svg class="my-event-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="my-event-detail">
                <svg class="my-event-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M11 9H9V2H7V9H5V2H3V9C3 11.12 4.66 12.84 6.75 12.97V22H9.25V12.97C11.34 12.84 13 11.12 13 9V2H11V9Z" fill="currentColor"/>
                </svg>
                <span>${event.myChoice}</span>
            </div>
        </div>
        
        <div class="my-event-progress">
            <div class="progress-header">
                <span class="progress-label">
                    ${event.status === 'voting' ? '投票進度' : '參與人數'}
                </span>
                <span class="progress-count">
                    ${event.status === 'voting' ? event.votingParticipants : event.currentParticipants}/${event.maxParticipants}
                </span>
            </div>
            <div class="progress-bar-container">
                <div class="my-progress-bar" style="width: ${progressPercentage}%"></div>
            </div>
        </div>
        
        <div class="my-event-actions">
            ${generateActionButtons(event, statusInfo)}
        </div>
    `;
    
    // 點擊事件
    card.addEventListener('click', (e) => {
        if (!e.target.closest('.my-event-actions')) {
            showEventPreview(event);
        }
    });
    
    return card;
}

// 獲取活動狀態
function getEventStatus(event, now, eventDate) {
    if (event.status === 'voting' || event.needsVote) {
        return { class: 'voting', text: '投票中' };
    }
    
    if (eventDate > now && ['open', 'finalized'].includes(event.status)) {
        return { class: 'upcoming', text: '即將開始' };
    }
    
    if (eventDate < now || event.status === 'ended') {
        return { class: 'completed', text: '已完成' };
    }
    
    if (event.status === 'cancelled') {
        return { class: 'cancelled', text: '已取消' };
    }
    
    return { class: 'upcoming', text: '進行中' };
}

// 生成操作按鈕
function generateActionButtons(event, statusInfo) {
    let buttons = '';
    
    if (statusInfo.class === 'voting') {
        buttons += `
            <button class="action-btn-small action-btn-primary" onclick="goToVote(${event.id})">
                前往投票
            </button>
        `;
    }
    
    if (statusInfo.class === 'upcoming') {
        buttons += `
            <button class="action-btn-small action-btn-outline" onclick="shareEvent(${event.id})">
                分享活動
            </button>
        `;
    }
    
    buttons += `
        <button class="action-btn-small action-btn-outline" onclick="goToEventDetail(${event.id})">
            查看詳情
        </button>
    `;
    
    return buttons;
}

// 設定狀態篩選
function setStatusFilter(filter) {
    currentFilter = filter;
    
    // 更新UI
    document.querySelectorAll('.filter-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`[data-status="${filter}"]`).classList.add('active');
    
    // 重新載入
    loadMyEvents();
}

// 改變排序
function changeSorting() {
    currentSort = sortSelect.value;
    loadMyEvents();
}

// 刷新資料
function refreshData() {
    refreshBtn.classList.add('loading');
    
    setTimeout(() => {
        loadMyEvents();
        refreshBtn.classList.remove('loading');
        showToast('資料已更新', 2000);
    }, 1000);
}

// 顯示活動預覽
function showEventPreview(event) {
    selectedEventId = event.id;
    previewTitle.textContent = event.title;
    
    const eventDate = new Date(`${event.date} ${event.time}`);
    const joinDate = new Date(event.joinedAt);
    
    previewBody.innerHTML = `
        <div class="preview-detail">
            <div class="preview-label">餐廳</div>
            <div class="preview-value">${event.restaurantName}</div>
        </div>
        
        <div class="preview-detail">
            <div class="preview-label">時間</div>
            <div class="preview-value">${formatDateTime(eventDate)}</div>
        </div>
        
        <div class="preview-detail">
            <div class="preview-label">地點</div>
            <div class="preview-value">${event.place}</div>
        </div>
        
        <div class="preview-detail">
            <div class="preview-label">我的選擇</div>
            <div class="preview-value">${event.myChoice}</div>
        </div>
        
        <div class="preview-detail">
            <div class="preview-label">參加時間</div>
            <div class="preview-value">${formatDateTime(joinDate)}</div>
        </div>
        
        ${event.description ? `
            <div class="preview-detail">
                <div class="preview-label">活動說明</div>
                <div class="preview-value">${event.description}</div>
            </div>
        ` : ''}
        
        <div class="preview-detail">
            <div class="preview-label">發起人</div>
            <div class="preview-value">${event.initiator}</div>
        </div>
    `;
    
    // 更新按鈕
    if (event.status === 'voting' || event.needsVote) {
        previewActionBtn.textContent = '前往投票';
        previewActionBtn.onclick = () => goToVote(event.id);
    } else {
        previewActionBtn.textContent = '查看詳情';
        previewActionBtn.onclick = () => goToEventDetail(event.id);
    }
    
    showPreview();
}

// 顯示預覽
function showPreview() {
    previewModal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// 關閉預覽
function closePreview() {
    previewModal.style.display = 'none';
    document.body.style.overflow = '';
    selectedEventId = null;
}

// 前往投票
function goToVote(eventId) {
    window.location.href = `meal-detail.html?id=${eventId}&action=vote`;
}

// 前往活動詳情
function goToEventDetail(eventId = null) {
    const id = eventId || selectedEventId;
    if (id) {
        window.location.href = `meal-detail.html?id=${id}`;
    }
}

// 分享活動
function shareEvent(eventId) {
    const event = mockEvents.find(e => e.id === eventId);
    if (!event) return;
    
    const shareData = {
        title: event.title,
        text: `來參加「${event.title}」共餐活動！`,
        url: `${window.location.origin}/meal-detail.html?id=${eventId}`
    };
    
    if (navigator.share) {
        navigator.share(shareData);
    } else {
        navigator.clipboard.writeText(shareData.url).then(() => {
            showToast('活動連結已複製到剪貼板', 2000);
        });
    }
}

// 格式化日期
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 formatDateTime(date) {
    return `${formatDate(date)} ${formatTime(date)}`;
}

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

// Toast 提示功能
function showToast(message, duration = 3000) {
    const existingToast = document.querySelector('.toast');
    if (existingToast) {
        existingToast.remove();
    }

    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    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.setStatusFilter = setStatusFilter;
window.changeSorting = changeSorting;
window.refreshData = refreshData;
window.closePreview = closePreview;
window.goToEventDetail = goToEventDetail;
window.goToVote = goToVote;
window.shareEvent = shareEvent;
