// 發起共餐頁面JavaScript功能

// 全域變數
let currentStep = 1;
let selectedMode = null; // 'single' 或 'multi'
let selectedRestaurantIds = []; // 選中的餐廳ID列表
let eventData = {
    title: '',
    date: '',
    time: '',
    place: '',
    maxParticipants: 10,
    visibility: 'public',
    deadline: '',
    description: '',
    mode: null,
    restaurants: []
};
let newEventId = null;

// DOM元素
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const restaurantSearch = document.getElementById('restaurantSearch');
const restaurantList = document.getElementById('restaurantList');
const selectedRestaurants = document.getElementById('selectedRestaurants');
const selectedList = document.getElementById('selectedList');
const eventForm = document.getElementById('eventForm');
const deadlineGroup = document.getElementById('deadlineGroup');
const successModal = document.getElementById('successModal');
const inviteLink = document.getElementById('inviteLink');

// 模擬餐廳資料（與GO食頁面同步）
const restaurantsData = {
    1: { 
        id: 1,
        name: '金華小籠包', 
        tags: ['小籠包', '台式早餐', '熱門'],
        distance: '120m'
    },
    2: { 
        id: 2,
        name: '阿嬤的味道', 
        tags: ['傳統小吃', '家常菜', '經濟實惠'],
        distance: '250m'
    },
    3: { 
        id: 3,
        name: '日式拉麵屋', 
        tags: ['拉麵', '日式料理', '宵夜'],
        distance: '300m'
    },
    4: { 
        id: 4,
        name: '老王牛肉麵', 
        tags: ['牛肉麵', '傳統美食', '老店'],
        distance: '400m'
    },
    5: { 
        id: 5,
        name: '素食天堂', 
        tags: ['素食', '健康', '有機'],
        distance: '500m'
    },
    6: { 
        id: 6,
        name: '海鮮大排檔', 
        tags: ['海鮮', '熱炒', '聚餐'],
        distance: '600m'
    }
};

// 初始化頁面
document.addEventListener('DOMContentLoaded', function() {
    initializeStartMeal();
    generateTimeOptions();
    setupEventListeners();
    renderRestaurantList();
});

// 初始化發起共餐頁面
function initializeStartMeal() {
    updateProgress();
    setDefaultDates();
    updateButtons(); // 確保按鈕狀態正確
    showToast('歡迎發起共餐活動！', 2000);
}

// 設定預設日期
function setDefaultDates() {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    // 設定活動日期預設為明天
    document.getElementById('eventDate').value = tomorrow.toISOString().split('T')[0];
    
    // 設定截止日期預設為今天
    document.getElementById('deadlineDate').value = today.toISOString().split('T')[0];
}

// 生成時間選項
function generateTimeOptions() {
    const timeSelects = ['eventTime', 'deadlineTime'];
    
    timeSelects.forEach(selectId => {
        const select = document.getElementById(selectId);
        select.innerHTML = '';
        
        for (let hour = 6; hour < 24; hour++) {
            for (let minute = 0; minute < 60; minute += 30) {
                const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
                const option = document.createElement('option');
                option.value = timeStr;
                option.textContent = timeStr;
                
                // 預設選擇12:00
                if (selectId === 'eventTime' && timeStr === '12:00') {
                    option.selected = true;
                }
                // 預設選擇18:00
                if (selectId === 'deadlineTime' && timeStr === '18:00') {
                    option.selected = true;
                }
                
                select.appendChild(option);
            }
        }
    });
}

// 設定事件監聽器
function setupEventListeners() {
    // 餐廳搜尋
    restaurantSearch.addEventListener('input', handleRestaurantSearch);
    
    // 表單驗證
    const formInputs = eventForm.querySelectorAll('input, select, textarea');
    formInputs.forEach(input => {
        input.addEventListener('input', validateCurrentStep);
        input.addEventListener('change', validateCurrentStep);
    });
    
    // 幫助按鈕
    document.getElementById('helpBtn').addEventListener('click', showHelp);
}

// 選擇模式
function selectMode(mode) {
    selectedMode = mode;
    eventData.mode = mode;
    
    // 更新UI
    document.querySelectorAll('.mode-option').forEach(option => {
        option.classList.remove('selected');
    });
    document.querySelector(`[data-mode="${mode}"]`).classList.add('selected');
    
    // 更新步驟2的描述
    const step2Description = document.getElementById('step2Description');
    if (mode === 'single') {
        step2Description.textContent = '請選擇一家餐廳進行聚餐';
    } else {
        step2Description.textContent = '請選擇2-5家餐廳供大家投票';
    }
    
    // 更新下一步按鈕狀態
    validateCurrentStep();
}

// 餐廳搜尋處理
function handleRestaurantSearch(e) {
    const searchTerm = e.target.value.toLowerCase();
    renderRestaurantList(searchTerm);
}

// 渲染餐廳列表
function renderRestaurantList(searchTerm = '') {
    const restaurants = Object.values(restaurantsData);
    const filteredRestaurants = restaurants.filter(restaurant => 
        restaurant.name.toLowerCase().includes(searchTerm) ||
        restaurant.tags.some(tag => tag.toLowerCase().includes(searchTerm))
    );
    
    restaurantList.innerHTML = '';
    
    filteredRestaurants.forEach(restaurant => {
        const isSelected = selectedRestaurantIds.includes(restaurant.id);
        const restaurantEl = document.createElement('div');
        restaurantEl.className = `restaurant-item ${isSelected ? 'selected' : ''}`;
        restaurantEl.onclick = () => toggleRestaurantSelection(restaurant.id);
        
        restaurantEl.innerHTML = `
            <div class="restaurant-item-header">
                <span class="restaurant-item-name">${restaurant.name}</span>
                <div class="restaurant-item-check">
                    ${isSelected ? '✓' : ''}
                </div>
            </div>
            <div class="restaurant-item-tags">
                ${restaurant.tags.map(tag => `<span class="restaurant-item-tag">${tag}</span>`).join('')}
            </div>
        `;
        
        restaurantList.appendChild(restaurantEl);
    });
}

// 切換餐廳選擇
function toggleRestaurantSelection(restaurantId) {
    const index = selectedRestaurantIds.indexOf(restaurantId);
    
    if (index > -1) {
        selectedRestaurantIds.splice(index, 1);
    } else {
        // 限制選擇數量
        if (selectedMode === 'single' && selectedRestaurantIds.length >= 1) {
            selectedRestaurantIds = [restaurantId]; // 單店模式只能選一家
        } else if (selectedMode === 'multi' && selectedRestaurantIds.length >= 5) {
            showToast('最多只能選擇5家餐廳', 2000);
            return;
        } else {
            selectedRestaurantIds.push(restaurantId);
        }
    }
    
    updateSelectedRestaurants();
    renderRestaurantList(restaurantSearch.value.toLowerCase());
    validateCurrentStep();
}

// 更新已選餐廳顯示
function updateSelectedRestaurants() {
    if (selectedRestaurantIds.length === 0) {
        selectedRestaurants.style.display = 'none';
        return;
    }
    
    selectedRestaurants.style.display = 'block';
    selectedList.innerHTML = '';
    
    selectedRestaurantIds.forEach(restaurantId => {
        const restaurant = restaurantsData[restaurantId];
        const itemEl = document.createElement('div');
        itemEl.className = 'selected-item';
        
        itemEl.innerHTML = `
            <span class="selected-item-name">${restaurant.name}</span>
            <button class="remove-btn" onclick="removeRestaurant(${restaurantId})">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41Z" fill="currentColor"/>
                </svg>
            </button>
        `;
        
        selectedList.appendChild(itemEl);
    });
}

// 移除餐廳
function removeRestaurant(restaurantId) {
    const index = selectedRestaurantIds.indexOf(restaurantId);
    if (index > -1) {
        selectedRestaurantIds.splice(index, 1);
        updateSelectedRestaurants();
        renderRestaurantList(restaurantSearch.value.toLowerCase());
        validateCurrentStep();
    }
}

// 下一步
function nextStep() {
    if (!validateCurrentStep()) {
        return;
    }
    
    // 保存當前步驟的資料
    saveCurrentStepData();
    
    if (currentStep === 4) {
        // 最後一步，提交表單
        submitEvent();
    } else {
        // 前進到下一步
        currentStep++;
        showStep(currentStep);
        updateProgress();
        updateButtons();
    }
}

// 上一步
function previousStep() {
    if (currentStep > 1) {
        currentStep--;
        showStep(currentStep);
        updateProgress();
        updateButtons();
    }
}

// 顯示指定步驟
function showStep(step) {
    // 隱藏所有步驟
    document.querySelectorAll('.step-section').forEach(section => {
        section.style.display = 'none';
    });
    
    // 顯示當前步驟
    document.getElementById(`step${step}`).style.display = 'block';
    
    // 特殊處理
    if (step === 3) {
        // 根據模式顯示/隱藏截止時間
        if (selectedMode === 'multi') {
            deadlineGroup.classList.add('show');
        } else {
            deadlineGroup.classList.remove('show');
        }
    }
    
    if (step === 4) {
        // 顯示總結資訊
        renderSummary();
        
        // 為勾選框添加事件監聽器
        setTimeout(() => {
            const agreeTermsCheckbox = document.getElementById('agreeTerms');
            if (agreeTermsCheckbox) {
                // 移除可能存在的舊監聽器
                agreeTermsCheckbox.removeEventListener('change', handleCheckboxChange);
                
                // 添加新監聽器
                agreeTermsCheckbox.addEventListener('change', handleCheckboxChange);
                
                // 初始驗證
                validateCurrentStep();
                
                console.log('第4步初始化完成，勾選框狀態:', agreeTermsCheckbox.checked);
            } else {
                console.error('找不到 agreeTerms 勾選框元素');
            }
        }, 200);
    }
}

// 更新進度
function updateProgress() {
    const progress = (currentStep / 4) * 100;
    progressFill.style.width = `${progress}%`;
    progressText.textContent = `步驟 ${currentStep} / 4`;
}

// 更新按鈕狀態
function updateButtons() {
    // 上一步按鈕
    if (currentStep === 1) {
        prevBtn.style.display = 'none';
    } else {
        prevBtn.style.display = 'block';
    }
    
    // 下一步按鈕
    if (currentStep === 4) {
        nextBtn.textContent = '發起活動';
        nextBtn.className = 'btn-primary';
    } else {
        nextBtn.textContent = '下一步';
        nextBtn.className = 'btn-primary';
    }
    
    // 驗證當前步驟
    validateCurrentStep();
}

// 驗證當前步驟
function validateCurrentStep() {
    let isValid = false;
    
    switch (currentStep) {
        case 1:
            isValid = selectedMode !== null;
            break;
        case 2:
            if (selectedMode === 'single') {
                isValid = selectedRestaurantIds.length === 1;
            } else {
                isValid = selectedRestaurantIds.length >= 2;
            }
            break;
        case 3:
            isValid = validateForm();
            break;
        case 4:
            const agreeTermsEl = document.getElementById('agreeTerms');
            isValid = agreeTermsEl ? agreeTermsEl.checked : false;
            console.log('第4步驗證:', { 
                element: !!agreeTermsEl, 
                checked: agreeTermsEl?.checked, 
                isValid 
            });
            break;
    }
    
    nextBtn.disabled = !isValid;
    
    // 視覺反饋
    if (isValid) {
        nextBtn.style.opacity = '1';
        nextBtn.style.cursor = 'pointer';
    } else {
        nextBtn.style.opacity = '0.5';
        nextBtn.style.cursor = 'not-allowed';
    }
    
    console.log('按鈕狀態更新:', { step: currentStep, isValid, disabled: !isValid });
    return isValid;
}

// 驗證表單
function validateForm() {
    const title = document.getElementById('eventTitle').value.trim();
    const date = document.getElementById('eventDate').value;
    const time = document.getElementById('eventTime').value;
    const place = document.getElementById('eventPlace').value.trim();
    
    let isValid = title && date && time && place;
    
    // 多店模式需要驗證截止時間
    if (selectedMode === 'multi') {
        const deadlineDate = document.getElementById('deadlineDate').value;
        const deadlineTime = document.getElementById('deadlineTime').value;
        isValid = isValid && deadlineDate && deadlineTime;
        
        // 檢查截止時間是否早於活動時間
        if (isValid) {
            const eventDateTime = new Date(`${date} ${time}`);
            const deadlineDateTime = new Date(`${deadlineDate} ${deadlineTime}`);
            if (deadlineDateTime >= eventDateTime) {
                showToast('投票截止時間必須早於活動時間', 3000);
                isValid = false;
            }
        }
    }
    
    return isValid;
}

// 保存當前步驟資料
function saveCurrentStepData() {
    switch (currentStep) {
        case 1:
            eventData.mode = selectedMode;
            break;
        case 2:
            eventData.restaurants = [...selectedRestaurantIds];
            break;
        case 3:
            eventData.title = document.getElementById('eventTitle').value.trim();
            eventData.date = document.getElementById('eventDate').value;
            eventData.time = document.getElementById('eventTime').value;
            eventData.place = document.getElementById('eventPlace').value.trim();
            eventData.maxParticipants = parseInt(document.getElementById('maxParticipants').value) || 10;
            eventData.visibility = document.getElementById('eventVisibility').value;
            eventData.description = document.getElementById('eventDescription').value.trim();
            
            if (selectedMode === 'multi') {
                eventData.deadline = `${document.getElementById('deadlineDate').value} ${document.getElementById('deadlineTime').value}`;
            }
            break;
    }
}

// 渲染總結資訊
function renderSummary() {
    // 基本資訊
    const basicInfo = document.getElementById('summaryBasic');
    const eventDate = new Date(`${eventData.date} ${eventData.time}`);
    
    basicInfo.innerHTML = `
        <div class="summary-item">
            <span class="summary-label">活動名稱：</span>
            <span class="summary-value">${eventData.title}</span>
        </div>
        <div class="summary-item">
            <span class="summary-label">活動時間：</span>
            <span class="summary-value">${formatDateTime(eventDate)}</span>
        </div>
        <div class="summary-item">
            <span class="summary-label">聚餐地點：</span>
            <span class="summary-value">${eventData.place}</span>
        </div>
        <div class="summary-item">
            <span class="summary-label">參加人數：</span>
            <span class="summary-value">最多 ${eventData.maxParticipants} 人</span>
        </div>
        <div class="summary-item">
            <span class="summary-label">活動類型：</span>
            <span class="summary-value">${eventData.visibility === 'public' ? '公開活動' : '私人活動'}</span>
        </div>
        ${eventData.mode === 'multi' ? `
            <div class="summary-item">
                <span class="summary-label">投票截止：</span>
                <span class="summary-value">${formatDateTime(new Date(eventData.deadline))}</span>
            </div>
        ` : ''}
        ${eventData.description ? `
            <div class="summary-item">
                <span class="summary-label">活動說明：</span>
                <span class="summary-value">${eventData.description}</span>
            </div>
        ` : ''}
    `;
    
    // 餐廳資訊
    const restaurantsInfo = document.getElementById('summaryRestaurants');
    const modeText = eventData.mode === 'single' ? '指定餐廳' : '投票選項';
    
    restaurantsInfo.innerHTML = `
        <div class="summary-item">
            <span class="summary-label">共餐模式：</span>
            <span class="summary-value">${eventData.mode === 'single' ? '單店聚餐' : '多店投票'}</span>
        </div>
        <div class="summary-item">
            <span class="summary-label">${modeText}：</span>
            <div class="summary-value">
                ${eventData.restaurants.map(id => restaurantsData[id].name).join('、')}
            </div>
        </div>
    `;
}

// 提交活動
function submitEvent() {
    // 模擬API調用
    nextBtn.disabled = true;
    nextBtn.textContent = '發起中...';
    
    setTimeout(() => {
        // 生成新的活動ID
        newEventId = Date.now();
        
        // 生成邀請連結
        const inviteLinkUrl = `${window.location.origin}/meal-detail.html?id=${newEventId}&invite=${generateInviteToken()}`;
        inviteLink.value = inviteLinkUrl;
        
        // 顯示成功對話框
        showSuccessModal();
        
        // 重置按鈕
        nextBtn.disabled = false;
        nextBtn.textContent = '發起活動';
        
        showToast('共餐活動發起成功！', 3000);
    }, 2000);
}

// 生成邀請令牌
function generateInviteToken() {
    return Math.random().toString(36).substr(2, 9);
}

// 顯示成功對話框
function showSuccessModal() {
    successModal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // 啟動自動跳轉倒數計時
    startAutoRedirect();
}

// 自動跳轉倒數計時
let redirectTimer = null;
let redirectCountdown = 5;

function startAutoRedirect() {
    const countdownText = document.getElementById('countdownText');
    const autoRedirect = document.getElementById('autoRedirect');
    
    if (!countdownText || !autoRedirect) return;
    
    autoRedirect.style.display = 'block';
    redirectCountdown = 5;
    
    redirectTimer = setInterval(() => {
        redirectCountdown--;
        countdownText.textContent = `${redirectCountdown} 秒後自動跳轉到活動列表...`;
        
        if (redirectCountdown <= 0) {
            clearInterval(redirectTimer);
            goToMealEvents();
        }
    }, 1000);
}

// 取消自動跳轉
function cancelAutoRedirect() {
    if (redirectTimer) {
        clearInterval(redirectTimer);
        redirectTimer = null;
    }
    
    const autoRedirect = document.getElementById('autoRedirect');
    if (autoRedirect) {
        autoRedirect.style.display = 'none';
    }
    
    showToast('已取消自動跳轉', 2000);
}

// 跳轉到活動列表
function goToMealEvents() {
    if (redirectTimer) {
        clearInterval(redirectTimer);
    }
    window.location.href = 'meal-events.html';
}

// 跳轉到活動管理
function goToMealManagement() {
    if (redirectTimer) {
        clearInterval(redirectTimer);
    }
    // TODO: 實作活動管理頁面後啟用
    showToast('活動管理功能開發中，將跳轉到活動列表', 2000);
    setTimeout(() => {
        window.location.href = 'meal-events.html';
    }, 2000);
}

// 複製邀請連結
function copyInviteLink() {
    navigator.clipboard.writeText(inviteLink.value).then(() => {
        showToast('邀請連結已複製到剪貼板', 2000);
    }).catch(() => {
        // 備用方案
        inviteLink.select();
        document.execCommand('copy');
        showToast('邀請連結已複製到剪貼板', 2000);
    });
}

// 處理勾選框變更
function handleCheckboxChange() {
    console.log('勾選框狀態變更:', this.checked);
    validateCurrentStep();
}

// 強制啟用按鈕（測試用）
function forceEnableButton() {
    const agreeTermsEl = document.getElementById('agreeTerms');
    if (agreeTermsEl) {
        agreeTermsEl.checked = true;
        validateCurrentStep();
        showToast('已強制啟用發起活動按鈕', 2000);
        
        // 隱藏測試按鈕
        const testBtn = document.querySelector('.test-enable-btn');
        if (testBtn) {
            testBtn.style.display = 'none';
        }
    }
}

// 顯示說明
function showHelp() {
    const helpMessages = {
        1: '選擇單店聚餐可以直接指定餐廳，選擇多店投票讓參與者一起決定。',
        2: '單店模式選擇一家餐廳，多店模式可選擇2-5家餐廳供投票。',
        3: '填寫活動的基本資訊，多店投票需要設定投票截止時間。',
        4: '確認所有資訊無誤後，即可發起共餐活動。'
    };
    
    showToast(helpMessages[currentStep] || '如需協助請聯繫管理員', 4000);
}

// 格式化日期時間
function formatDateTime(date) {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekday = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}/${day} (${weekday}) ${hours}:${minutes}`;
}

// 返回上一頁
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.addEventListener('beforeunload', function() {
    if (redirectTimer) {
        clearInterval(redirectTimer);
    }
});

// 全域函數
window.goBack = goBack;
window.nextStep = nextStep;
window.previousStep = previousStep;
window.selectMode = selectMode;
window.removeRestaurant = removeRestaurant;
window.copyInviteLink = copyInviteLink;
window.forceEnableButton = forceEnableButton;
window.goToMealEvents = goToMealEvents;
window.goToMealManagement = goToMealManagement;
window.cancelAutoRedirect = cancelAutoRedirect;
