// 共餐活動詳情頁面JavaScript功能

// 全域變數
let currentEvent = null;
let selectedRestaurant = null;
let selectedMeals = [];
let currentStep = 'info';
let userParticipations = JSON.parse(localStorage.getItem('meal_participations') || '[]');

// URL 參數
const urlParams = new URLSearchParams(window.location.search);
const eventId = parseInt(urlParams.get('id'));
const action = urlParams.get('action'); // vote, join

// DOM元素
const eventInfoSection = document.getElementById('eventInfoSection');
const progressSection = document.getElementById('progressSection');
const contentSection = document.getElementById('contentSection');
const participantsSection = document.getElementById('participantsSection');
const actionContainer = document.getElementById('actionContainer');
const modalOverlay = document.getElementById('modalOverlay');
const modalTitle = document.getElementById('modalTitle');
const modalBody = document.getElementById('modalBody');
const confirmBtn = document.getElementById('confirmBtn');

// 模擬活動資料（與meal-events-script.js同步）
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: '大家一起來享用美味小籠包！',
        participants: ['王小明', '李小華', '張素心', '陳大海', '田中一郎', '老王', '小美', '阿強']
    },
    {
        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: [
            { id: 2, votes: 5 },
            { id: 3, votes: 4 },
            { id: 4, votes: 3 }
        ],
        participants: ['李小華', '王小明', '張素心', '陳大海', '田中一郎', '老王', '小美', '阿強', '林大明', '陳小玉', '黃大同', '劉小芬']
    },
    {
        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: '推廣健康素食生活',
        participants: ['張素心', '李小華', '陳大海', '小美', '林大明']
    },
    {
        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: '新鮮海鮮，歡樂聚餐',
        participants: ['陳大海', '王小明', '李小華', '張素心', '田中一郎', '老王', '小美', '阿強', '林大明', '陳小玉', '黃大同', '劉小芬', '趙小美', '錢大力', '孫小花', '李大明', '周小玲', '吳大華', '鄭小芳', '何大勇', '姚小雅', '馬大山']
    },
    {
        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: '深夜拉麵，暖心聚會',
        participants: ['田中一郎', '王小明', '李小華', '張素心', '陳大海', '老王', '小美', '阿強']
    },
    {
        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: '傳統好味道，等你來品嚐',
        participants: ['老王', '王小明', '李小華']
    }
];

// 模擬餐廳資料
const restaurantsData = {
    1: { 
        name: '金華小籠包', 
        tags: ['小籠包', '台式早餐'],
        menu: {
            '主食': [
                { id: 1, name: '小籠包 (8顆)', price: 120, description: '皮薄餡多，湯汁鮮美' },
                { id: 2, name: '煎餃 (6顆)', price: 80, description: '外酥內軟，香氣撲鼻' },
                { id: 3, name: '蛋餅', price: 60, description: '古早味蛋餅，配菜豐富' }
            ],
            '湯品': [
                { id: 4, name: '酸辣湯', price: 40, description: '酸甜開胃，暖胃好湯' },
                { id: 5, name: '蛋花湯', price: 35, description: '清淡營養，老少咸宜' }
            ],
            '飲品': [
                { id: 6, name: '豆漿', price: 25, description: '現磨豆漿，濃醇香甜' },
                { id: 7, name: '奶茶', price: 30, description: '香醇奶茶，溫暖好喝' }
            ]
        }
    },
    2: { 
        name: '阿嬤的味道', 
        tags: ['傳統小吃', '家常菜'],
        menu: {
            '主食': [
                { id: 11, name: '滷肉飯', price: 70, description: '傳統古早味，肥瘦適中' },
                { id: 12, name: '炒麵', price: 90, description: '配菜豐富，口感Q彈' },
                { id: 13, name: '排骨便當', price: 120, description: '大塊排骨，配菜豐盛' }
            ],
            '小菜': [
                { id: 14, name: '滷蛋', price: 15, description: '入味十足的茶葉蛋' },
                { id: 15, name: '泡菜', price: 20, description: '清爽開胃的韓式泡菜' }
            ]
        }
    },
    3: { 
        name: '日式拉麵屋', 
        tags: ['拉麵', '日式料理'],
        menu: {
            '拉麵': [
                { id: 21, name: '豚骨拉麵', price: 180, description: '濃郁豚骨湯頭，麵條彈牙' },
                { id: 22, name: '味噌拉麵', price: 160, description: '香醇味噌湯底，營養豐富' },
                { id: 23, name: '醬油拉麵', price: 150, description: '清淡醬油湯頭，經典口味' }
            ],
            '副食': [
                { id: 24, name: '叉燒', price: 40, description: '香嫩叉燒，入口即化' },
                { id: 25, name: '溏心蛋', price: 25, description: '完美溏心蛋，口感豐富' }
            ]
        }
    },
    4: { 
        name: '老王牛肉麵', 
        tags: ['牛肉麵', '傳統美食'],
        menu: {
            '麵食': [
                { id: 31, name: '紅燒牛肉麵', price: 150, description: '大塊牛肉，濃郁湯頭' },
                { id: 32, name: '清燉牛肉麵', price: 140, description: '清淡鮮甜，原味呈現' },
                { id: 33, name: '牛肉餃子', price: 120, description: '手工水餃，牛肉餡料' }
            ],
            '小菜': [
                { id: 34, name: '滷豆干', price: 30, description: '入味豆干，口感紮實' },
                { id: 35, name: '海帶絲', price: 25, description: '清爽海帶絲，解膩好菜' }
            ]
        }
    },
    5: {
        name: '素食天堂',
        tags: ['素食', '健康', '有機'],
        menu: {
            '主食': [
                { id: 41, name: '素食便當', price: 120, description: '營養均衡的素食便當' },
                { id: 42, name: '蔬菜炒飯', price: 90, description: '多種蔬菜炒製，營養豐富' },
                { id: 43, name: '素食麵條', price: 100, description: '清爽素食麵條' }
            ],
            '湯品': [
                { id: 44, name: '蔬菜湯', price: 40, description: '新鮮蔬菜熬製' },
                { id: 45, name: '豆腐湯', price: 45, description: '嫩豆腐配菜湯' }
            ]
        }
    },
    6: {
        name: '海鮮大排檔',
        tags: ['海鮮', '熱炒', '聚餐'],
        menu: {
            '海鮮': [
                { id: 51, name: '炒蛤蜊', price: 180, description: '新鮮蛤蜊，蒜香炒製' },
                { id: 52, name: '烤魚', price: 250, description: '新鮮魚類，炭火烤製' },
                { id: 53, name: '蝦子料理', price: 200, description: '活跳蝦，鮮甜美味' }
            ],
            '熱炒': [
                { id: 54, name: '宮保雞丁', price: 150, description: '經典川菜，香辣下飯' },
                { id: 55, name: '糖醋排骨', price: 180, description: '酸甜可口，老少咸宜' }
            ]
        }
    }
};

// 初始化頁面
document.addEventListener('DOMContentLoaded', function() {
    console.log('初始化活動詳情頁面');
    console.log('URL參數:', { 
        eventId: eventId, 
        eventIdType: typeof eventId, 
        action: action,
        originalUrl: window.location.href 
    });
    console.log('可用活動列表:', mockEvents.map(e => ({ id: e.id, title: e.title })));
    
    if (!eventId || isNaN(eventId)) {
        console.error('無效的活動ID:', eventId);
        showToast('活動ID無效', 2000);
        setTimeout(() => {
            window.location.href = 'meal-events.html';
        }, 2000);
        return;
    }
    
    currentEvent = mockEvents.find(event => event.id === eventId);
    console.log('找到的活動:', currentEvent);
    
    if (!currentEvent) {
        console.error('找不到活動:', { 
            searchId: eventId, 
            availableIds: mockEvents.map(e => e.id),
            allEvents: mockEvents 
        });
        showToast(`找不到ID為 ${eventId} 的活動`, 3000);
        setTimeout(() => {
            window.location.href = 'meal-events.html';
        }, 3000);
        return;
    }
    
    initializeMealDetail();
    renderEventInfo();
    updateProgressSteps();
    renderContent();
    renderParticipants();
    renderActionButtons();
});

// 初始化活動詳情頁面
function initializeMealDetail() {
    // 根據動作設定初始步驟
    if (action === 'vote' && currentEvent.type === 'multi') {
        currentStep = 'select';
        updateStepLabel('投票選擇');
    } else if (action === 'join') {
        if (currentEvent.type === 'single') {
            currentStep = 'select';
            updateStepLabel('選擇餐點');
        } else {
            currentStep = 'select';
            updateStepLabel('投票選擇');
        }
    }
    
    // 檢查用戶是否已參加
    const isParticipated = userParticipations.includes(eventId);
    if (isParticipated) {
        showToast('您已參加此活動', 2000);
    }
}

// 更新步驟標籤
function updateStepLabel(label) {
    const stepLabel = document.getElementById('stepLabel');
    if (stepLabel) {
        stepLabel.textContent = label;
    }
}

// 渲染活動資訊
function renderEventInfo() {
    const eventDate = new Date(currentEvent.date + ' ' + currentEvent.time);
    const formattedDate = formatDate(eventDate);
    const formattedTime = formatTime(eventDate);
    
    eventInfoSection.innerHTML = `
        <h2 class="event-detail-title">${currentEvent.title}</h2>
        <div class="event-detail-restaurant">${currentEvent.restaurantName}</div>
        
        <div class="event-meta">
            <div class="event-meta-item">
                <svg class="event-meta-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-meta-item">
                <svg class="event-meta-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-meta-item">
                <svg class="event-meta-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>${currentEvent.place}</span>
            </div>
            
            <div class="event-meta-item">
                <svg class="event-meta-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>${currentEvent.initiator} 發起</span>
            </div>
        </div>
        
        ${currentEvent.description ? `<div class="event-description">${currentEvent.description}</div>` : ''}
    `;
}

// 更新進度步驟
function updateProgressSteps() {
    const steps = document.querySelectorAll('.progress-step');
    steps.forEach((step, index) => {
        step.classList.remove('active', 'completed');
        
        const stepName = step.dataset.step;
        if (stepName === currentStep) {
            step.classList.add('active');
        } else if (isStepCompleted(stepName)) {
            step.classList.add('completed');
        }
    });
}

// 判斷步驟是否完成
function isStepCompleted(stepName) {
    switch (stepName) {
        case 'info':
            return currentStep !== 'info';
        case 'select':
            return currentStep === 'confirm' || (selectedRestaurant !== null && selectedMeals.length > 0);
        default:
            return false;
    }
}

// 渲染內容區域
function renderContent() {
    if (currentEvent.type === 'single') {
        renderSingleRestaurantMenu();
    } else {
        if (currentEvent.status === 'voting') {
            renderMultiRestaurantVoting();
        } else {
            renderFinalizedEvent();
        }
    }
}

// 渲染單店菜單
function renderSingleRestaurantMenu() {
    const restaurant = restaurantsData[currentEvent.restaurantId];
    if (!restaurant) {
        contentSection.innerHTML = '<p>餐廳資訊載入中...</p>';
        return;
    }
    
    let menuHTML = `<h3 class="content-title">選擇餐點</h3>`;
    
    Object.keys(restaurant.menu).forEach(category => {
        menuHTML += `
            <div class="menu-category">
                <h4 class="menu-category-title">${category}</h4>
                <div class="menu-items">
        `;
        
        restaurant.menu[category].forEach(item => {
            const isSelected = selectedMeals.some(meal => meal.id === item.id);
            menuHTML += `
                <div class="menu-item ${isSelected ? 'selected' : ''}" 
                     onclick="toggleMealSelection(${item.id}, '${item.name}', ${item.price})">
                    <div class="menu-item-header">
                        <span class="menu-item-name">${item.name}</span>
                        <span class="menu-item-price">$${item.price}</span>
                    </div>
                    ${item.description ? `<div class="menu-item-description">${item.description}</div>` : ''}
                </div>
            `;
        });
        
        menuHTML += `
                </div>
            </div>
        `;
    });
    
    contentSection.innerHTML = menuHTML;
}

// 渲染多店投票
function renderMultiRestaurantVoting() {
    let votingHTML = `<h3 class="content-title">投票選擇餐廳</h3><div class="restaurant-options">`;
    
    currentEvent.restaurants.forEach(restaurantData => {
        const restaurant = restaurantsData[restaurantData.id];
        if (!restaurant) return;
        
        const isSelected = selectedRestaurant === restaurantData.id;
        votingHTML += `
            <div class="restaurant-option ${isSelected ? 'selected' : ''}" 
                 onclick="selectRestaurant(${restaurantData.id})">
                <div class="restaurant-option-header">
                    <span class="restaurant-option-name">${restaurant.name}</span>
                    <span class="restaurant-option-votes">${restaurantData.votes} 票</span>
                </div>
                <div class="restaurant-option-tags">
                    ${restaurant.tags.map(tag => `<span class="restaurant-option-tag">${tag}</span>`).join('')}
                </div>
            </div>
        `;
    });
    
    votingHTML += '</div>';
    contentSection.innerHTML = votingHTML;
}

// 渲染已確定的活動
function renderFinalizedEvent() {
    contentSection.innerHTML = `
        <h3 class="content-title">活動已確定</h3>
        <p>此活動的投票已結束，餐廳已確定為：<strong>${currentEvent.restaurantName}</strong></p>
    `;
}

// 切換餐點選擇
function toggleMealSelection(mealId, mealName, mealPrice) {
    const existingIndex = selectedMeals.findIndex(meal => meal.id === mealId);
    
    if (existingIndex > -1) {
        selectedMeals.splice(existingIndex, 1);
    } else {
        selectedMeals.push({
            id: mealId,
            name: mealName,
            price: mealPrice
        });
    }
    
    // 重新渲染以更新選中狀態
    renderContent();
    updateActionButtons();
}

// 選擇餐廳（多店投票）
function selectRestaurant(restaurantId) {
    selectedRestaurant = restaurantId;
    renderContent();
    updateActionButtons();
}

// 渲染參與者列表
function renderParticipants() {
    const participants = currentEvent.participants || [];
    
    participantsSection.innerHTML = `
        <h3 class="participants-title">參與者 (${participants.length}/${currentEvent.maxParticipants})</h3>
        <div class="participants-grid">
            ${participants.map(participant => `
                <div class="participant-item">
                    <div class="participant-name">${participant}</div>
                    <div class="participant-choice">已報名</div>
                </div>
            `).join('')}
        </div>
    `;
}

// 渲染操作按鈕
function renderActionButtons() {
    const isParticipated = userParticipations.includes(eventId);
    
    if (isParticipated) {
        actionContainer.innerHTML = `
            <button class="action-btn-full action-btn-secondary" onclick="window.location.href='my-meals.html'">
                查看我的共餐
            </button>
        `;
        return;
    }
    
    if (currentEvent.status === 'ended' || currentEvent.status === 'cancelled') {
        actionContainer.innerHTML = `
            <button class="action-btn-full" disabled>
                活動已結束
            </button>
        `;
        return;
    }
    
    if (currentEvent.type === 'single') {
        const canJoin = selectedMeals.length > 0;
        actionContainer.innerHTML = `
            <button class="action-btn-full" ${canJoin ? '' : 'disabled'} onclick="confirmJoinEvent()">
                ${canJoin ? `加入共餐 (共 $${calculateTotal()})` : '請選擇餐點'}
            </button>
        `;
    } else {
        if (currentEvent.status === 'voting') {
            const canVote = selectedRestaurant !== null;
            actionContainer.innerHTML = `
                <button class="action-btn-full" ${canVote ? '' : 'disabled'} onclick="confirmVote()">
                    ${canVote ? '確認投票' : '請選擇餐廳'}
                </button>
            `;
        }
    }
}

// 更新操作按鈕
function updateActionButtons() {
    renderActionButtons();
}

// 計算總金額
function calculateTotal() {
    return selectedMeals.reduce((total, meal) => total + meal.price, 0);
}

// 確認加入活動
function confirmJoinEvent() {
    const totalPrice = calculateTotal();
    const mealNames = selectedMeals.map(meal => meal.name).join('、');
    
    modalTitle.textContent = '確認加入共餐';
    modalBody.innerHTML = `
        <div style="margin-bottom: 15px;">
            <h4>活動：${currentEvent.title}</h4>
            <p>餐廳：${currentEvent.restaurantName}</p>
            <p>時間：${formatDate(new Date(currentEvent.date))} ${formatTime(new Date(currentEvent.date + ' ' + currentEvent.time))}</p>
        </div>
        <div style="margin-bottom: 15px;">
            <h4>已選餐點：</h4>
            <ul style="margin: 10px 0; padding-left: 20px;">
                ${selectedMeals.map(meal => `<li>${meal.name} - $${meal.price}</li>`).join('')}
            </ul>
        </div>
        <div style="font-weight: 600; font-size: 18px; color: var(--primary-color);">
            總金額：$${totalPrice}
        </div>
    `;
    
    confirmBtn.onclick = function() {
        joinEvent();
    };
    
    showModal();
}

// 確認投票
function confirmVote() {
    const restaurant = restaurantsData[selectedRestaurant];
    
    modalTitle.textContent = '確認投票';
    modalBody.innerHTML = `
        <div style="margin-bottom: 15px;">
            <h4>活動：${currentEvent.title}</h4>
            <p>投票截止：${formatDateTime(new Date(currentEvent.deadline))}</p>
        </div>
        <div style="margin-bottom: 15px;">
            <h4>您選擇的餐廳：</h4>
            <p style="font-size: 18px; font-weight: 600; color: var(--primary-color);">${restaurant.name}</p>
            <p style="color: var(--text-secondary);">${restaurant.tags.join('、')}</p>
        </div>
        <p style="color: var(--text-secondary); font-size: 14px;">
            投票後將在結果確定時通知您選餐。
        </p>
    `;
    
    confirmBtn.onclick = function() {
        submitVote();
    };
    
    showModal();
}

// 加入活動
function joinEvent() {
    // 模擬API調用
    setTimeout(() => {
        userParticipations.push(eventId);
        localStorage.setItem('meal_participations', JSON.stringify(userParticipations));
        
        closeModal();
        showToast('成功加入共餐！', 2000);
        
        // 更新UI
        renderActionButtons();
        
        setTimeout(() => {
            window.location.href = 'my-meals.html';
        }, 2000);
    }, 500);
}

// 提交投票
function submitVote() {
    // 模擬API調用
    setTimeout(() => {
        userParticipations.push(eventId);
        localStorage.setItem('meal_participations', JSON.stringify(userParticipations));
        
        closeModal();
        showToast('投票成功！', 2000);
        
        // 更新UI
        renderActionButtons();
        
        setTimeout(() => {
            window.location.href = 'meal-events.html';
        }, 2000);
    }, 500);
}

// 顯示模態框
function showModal() {
    modalOverlay.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// 關閉模態框
function closeModal() {
    modalOverlay.style.display = 'none';
    document.body.style.overflow = '';
}

// 分享功能
function shareEvent() {
    if (navigator.share) {
        navigator.share({
            title: currentEvent.title,
            text: `來參加「${currentEvent.title}」共餐活動！`,
            url: window.location.href
        });
    } else {
        // 複製連結到剪貼板
        navigator.clipboard.writeText(window.location.href).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);
}

// 設定分享按鈕事件
document.getElementById('shareBtn').addEventListener('click', shareEvent);

// 全域函數
window.goBack = goBack;
window.closeModal = closeModal;
window.confirmAction = function() {
    if (confirmBtn.onclick) {
        confirmBtn.onclick();
    }
};
window.toggleMealSelection = toggleMealSelection;
window.selectRestaurant = selectRestaurant;
