// GO食頁面JavaScript功能

// 全域變數
let currentPage = 1;
let isLoading = false;
let hasMoreData = true;
let currentSearchTerm = '';
let allRestaurants = [];
let displayedRestaurants = [];
let favoritesMode = false;
let favorites = JSON.parse(localStorage.getItem('gofood_favorites') || '[]');

// DOM元素
const searchInput = document.getElementById('searchInput');
const clearSearch = document.getElementById('clearSearch');
const restaurantsContainer = document.getElementById('restaurantsContainer');
const loadingIndicator = document.getElementById('loadingIndicator');
const noResults = document.getElementById('noResults');
const groupMealBtn = document.getElementById('groupMealBtn');
const startMealBtn = document.getElementById('startMealBtn');
const favoritesBtn = document.getElementById('favoritesBtn');
const favoritesText = document.getElementById('favoritesText');

// 模擬餐廳資料
const mockRestaurants = [
    {
        id: 1,
        name: '金華小籠包',
        tags: ['小籠包', '台式早餐', '熱門'],
        photos: ['images/restaurants/xiaolongbao-1.png', 'images/restaurants/xiaolongbao-2.png'],
        hours: '06:00 - 14:00',
        status: 'open',
        distance: '120m',
        phone: '02-1234-5678',
        lat: 25.0330,
        lng: 121.5654
    },
    {
        id: 2,
        name: '阿嬤的味道',
        tags: ['傳統小吃', '家常菜', '經濟實惠'],
        photos: ['images/restaurants/grandma-food-1.png', 'images/restaurants/grandma-food-2.png'],
        hours: '11:00 - 21:00',
        status: 'open',
        distance: '250m',
        phone: '02-2345-6789',
        lat: 25.0340,
        lng: 121.5664
    },
    {
        id: 3,
        name: '日式拉麵屋',
        tags: ['拉麵', '日式料理', '宵夜'],
        photos: ['images/restaurants/ramen-1.png', 'images/restaurants/ramen-2.png'],
        hours: '17:00 - 02:00',
        status: 'closed',
        distance: '300m',
        phone: '02-3456-7890',
        lat: 25.0350,
        lng: 121.5674
    },
    {
        id: 4,
        name: '老王牛肉麵',
        tags: ['牛肉麵', '傳統美食', '老店'],
        photos: ['images/restaurants/beef-noodles-1.png', 'images/restaurants/beef-noodles-2.png'],
        hours: '10:00 - 20:00',
        status: 'open',
        distance: '400m',
        phone: '02-4567-8901',
        lat: 25.0360,
        lng: 121.5684
    },
    {
        id: 5,
        name: '素食天堂',
        tags: ['素食', '健康', '有機'],
        photos: ['images/restaurants/vegetarian-1.png', 'images/restaurants/vegetarian-2.png'],
        hours: '08:00 - 22:00',
        status: 'open',
        distance: '500m',
        phone: '02-5678-9012',
        lat: 25.0370,
        lng: 121.5694
    },
    {
        id: 6,
        name: '海鮮大排檔',
        tags: ['海鮮', '熱炒', '聚餐'],
        photos: ['images/restaurants/seafood-1.png', 'images/restaurants/seafood-2.png'],
        hours: '16:00 - 01:00',
        status: 'open',
        distance: '600m',
        phone: '02-6789-0123',
        lat: 25.0380,
        lng: 121.5704
    }
];

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

// 初始化GO食頁面
function initializeGoFood() {
    // 設定搜尋輸入框焦點
    setTimeout(() => {
        searchInput.focus();
    }, 500);
    
    // 更新收藏按鈕狀態
    updateFavoritesButton();
    
    // 顯示歡迎提示
    showToast('歡迎來到GO食！找尋您喜愛的美食', 2000);
}

// 設定事件監聽器
function setupEventListeners() {
    // 搜尋功能
    searchInput.addEventListener('input', handleSearch);
    clearSearch.addEventListener('click', clearSearchInput);
    
    // 底部CTA按鈕
    groupMealBtn.addEventListener('click', () => {
        window.location.href = 'meal-events.html';
    });
    
    startMealBtn.addEventListener('click', () => {
        window.location.href = 'start-meal.html';
    });
    
    favoritesBtn.addEventListener('click', toggleFavoritesMode);
    
    // 無限捲動
    window.addEventListener('scroll', handleInfiniteScroll);
    
    // 鍵盤快捷鍵
    document.addEventListener('keydown', handleKeyDown);
}

// 處理搜尋
function handleSearch(e) {
    const searchTerm = e.target.value.trim();
    currentSearchTerm = searchTerm;
    
    // 顯示/隱藏清除按鈕
    if (searchTerm) {
        clearSearch.style.display = 'block';
    } else {
        clearSearch.style.display = 'none';
    }
    
    // 重置並重新搜尋
    currentPage = 1;
    restaurantsContainer.innerHTML = '';
    displayedRestaurants = [];
    hasMoreData = true;
    
    // 延遲搜尋以避免過度頻繁的請求
    clearTimeout(window.searchTimeout);
    window.searchTimeout = setTimeout(() => {
        loadRestaurants();
    }, 300);
}

// 清除搜尋
function clearSearchInput() {
    searchInput.value = '';
    clearSearch.style.display = 'none';
    handleSearch({ target: { value: '' } });
    searchInput.focus();
}

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

// 過濾餐廳
function filterRestaurants() {
    let filtered = mockRestaurants;
    
    // 搜尋過濾
    if (currentSearchTerm) {
        filtered = filtered.filter(restaurant => 
            restaurant.name.toLowerCase().includes(currentSearchTerm.toLowerCase()) ||
            restaurant.tags.some(tag => tag.toLowerCase().includes(currentSearchTerm.toLowerCase()))
        );
    }
    
    // 收藏模式過濾
    if (favoritesMode) {
        filtered = filtered.filter(restaurant => 
            favorites.includes(restaurant.id)
        );
    }
    
    return filtered;
}

// 渲染餐廳列表
function renderRestaurants(restaurants) {
    const fragment = document.createDocumentFragment();
    
    restaurants.forEach((restaurant, index) => {
        const restaurantCard = createRestaurantCard(restaurant);
        
        // 添加延遲動畫
        setTimeout(() => {
            fragment.appendChild(restaurantCard);
            restaurantsContainer.appendChild(fragment);
        }, index * 100);
    });
}

// 創建餐廳卡片
function createRestaurantCard(restaurant) {
    const card = document.createElement('div');
    card.className = 'restaurant-card';
    card.dataset.restaurantId = restaurant.id;
    
    const isFavorited = favorites.includes(restaurant.id);
    const statusText = restaurant.status === 'open' ? '營業中' : '休息中';
    
    card.innerHTML = `
        <div class="restaurant-photos">
            <div class="photo-carousel" id="carousel-${restaurant.id}">
                ${restaurant.photos.map((photo, index) => `
                    <div class="photo-slide ${index === 0 ? 'active' : ''}">
                        <img src="${photo}" 
                             alt="${restaurant.name}" 
                             loading="lazy"
                             onerror="handleImageError(this, '${restaurant.name}')">
                        <div class="image-placeholder" 
                             data-restaurant-name="${restaurant.name}"
                             style="display: none;">
                            圖片載入中...
                        </div>
                    </div>
                `).join('')}
            </div>
            
            ${restaurant.photos.length > 1 ? `
                <div class="photo-dots">
                    ${restaurant.photos.map((_, index) => `
                        <div class="photo-dot ${index === 0 ? 'active' : ''}" 
                             onclick="setPhotoSlide(${restaurant.id}, ${index})"></div>
                    `).join('')}
                </div>
            ` : ''}
            
            <div class="status-badge ${restaurant.status}">
                ${statusText}
            </div>
            
            <button class="favorite-btn ${isFavorited ? 'favorited' : ''}" 
                    onclick="toggleFavorite(${restaurant.id})">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 21.35L10.55 20.03C5.4 15.36 2 12.28 2 8.5C2 5.42 4.42 3 7.5 3C9.24 3 10.91 3.81 12 5.09C13.09 3.81 14.76 3 16.5 3C19.58 3 22 5.42 22 8.5C22 12.28 18.6 15.36 13.45 20.04L12 21.35Z" 
                          fill="${isFavorited ? 'currentColor' : 'none'}" 
                          stroke="currentColor" 
                          stroke-width="2"/>
                </svg>
            </button>
        </div>
        
        <div class="restaurant-info">
            <div class="restaurant-header">
                <h3 class="restaurant-name">${restaurant.name}</h3>
            </div>
            
            <div class="restaurant-tags">
                ${restaurant.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
            </div>
            
            <div class="restaurant-details">
                <div class="detail-row">
                    <svg class="detail-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 class="detail-text hours-text">${restaurant.hours}</span>
                </div>
                
                <div class="detail-row">
                    <svg class="detail-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>
                    <a href="#" class="detail-text distance-link" onclick="openMap(${restaurant.lat}, ${restaurant.lng}, '${restaurant.name}')">
                        距離 ${restaurant.distance}
                    </a>
                </div>
                
                <div class="detail-row">
                    <svg class="detail-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M6.62 10.79C8.06 13.62 10.38 15.94 13.21 17.38L15.41 15.18C15.69 14.9 16.08 14.82 16.43 14.93C17.55 15.3 18.75 15.5 20 15.5C20.55 15.5 21 15.95 21 16.5V20C21 20.55 20.55 21 20 21C10.61 21 3 13.39 3 4C3 3.45 3.45 3 4 3H7.5C8.05 3 8.5 3.45 8.5 4C8.5 5.25 8.7 6.45 9.07 7.57C9.18 7.92 9.1 8.31 8.82 8.59L6.62 10.79Z" fill="currentColor"/>
                    </svg>
                    <span class="detail-text">${restaurant.phone}</span>
                </div>
            </div>
        </div>
    `;
    
    // 設定照片輪播
    if (restaurant.photos.length > 1) {
        setupPhotoCarousel(restaurant.id, restaurant.photos.length);
    }
    
    // 點擊卡片事件（避免點擊收藏按鈕時觸發）
    card.addEventListener('click', (e) => {
        if (!e.target.closest('.favorite-btn') && !e.target.closest('.distance-link') && !e.target.closest('.photo-dot')) {
            showRestaurantDetails(restaurant);
        }
    });
    
    return card;
}

// 設定照片輪播
function setupPhotoCarousel(restaurantId, photoCount) {
    if (photoCount <= 1) return;
    
    let currentSlideIndex = 0;
    
    setInterval(() => {
        const carousel = document.getElementById(`carousel-${restaurantId}`);
        if (!carousel) return;
        
        const slides = carousel.querySelectorAll('.photo-slide');
        const dots = carousel.parentElement.querySelectorAll('.photo-dot');
        
        // 移除當前active
        slides[currentSlideIndex].classList.remove('active');
        dots[currentSlideIndex].classList.remove('active');
        
        // 下一張
        currentSlideIndex = (currentSlideIndex + 1) % photoCount;
        
        // 添加新active
        slides[currentSlideIndex].classList.add('active');
        dots[currentSlideIndex].classList.add('active');
    }, 3000);
}

// 設定照片幻燈片
function setPhotoSlide(restaurantId, slideIndex) {
    const carousel = document.getElementById(`carousel-${restaurantId}`);
    if (!carousel) return;
    
    const slides = carousel.querySelectorAll('.photo-slide');
    const dots = carousel.parentElement.querySelectorAll('.photo-dot');
    
    // 移除所有active
    slides.forEach(slide => slide.classList.remove('active'));
    dots.forEach(dot => dot.classList.remove('active'));
    
    // 添加新active
    slides[slideIndex].classList.add('active');
    dots[slideIndex].classList.add('active');
}

// 切換收藏
function toggleFavorite(restaurantId) {
    const index = favorites.indexOf(restaurantId);
    const restaurant = mockRestaurants.find(r => r.id === restaurantId);
    
    if (index > -1) {
        favorites.splice(index, 1);
        showToast(`已從收藏中移除 ${restaurant.name}`, 2000);
    } else {
        favorites.push(restaurantId);
        showToast(`已收藏 ${restaurant.name}`, 2000);
    }
    
    // 保存到localStorage
    localStorage.setItem('gofood_favorites', JSON.stringify(favorites));
    
    // 更新UI
    updateFavoriteButton(restaurantId);
    updateFavoritesButton();
    
    // 如果在收藏模式，需要重新載入
    if (favoritesMode) {
        currentPage = 1;
        restaurantsContainer.innerHTML = '';
        displayedRestaurants = [];
        hasMoreData = true;
        loadRestaurants();
    }
}

// 更新收藏按鈕
function updateFavoriteButton(restaurantId) {
    const card = document.querySelector(`[data-restaurant-id="${restaurantId}"]`);
    if (!card) return;
    
    const favoriteBtn = card.querySelector('.favorite-btn');
    const svg = favoriteBtn.querySelector('svg path');
    const isFavorited = favorites.includes(restaurantId);
    
    favoriteBtn.classList.toggle('favorited', isFavorited);
    svg.setAttribute('fill', isFavorited ? 'currentColor' : 'none');
    
    // 添加點擊動畫
    favoriteBtn.style.transform = 'scale(0.8)';
    setTimeout(() => {
        favoriteBtn.style.transform = 'scale(1)';
    }, 150);
}

// 切換收藏模式
function toggleFavoritesMode() {
    favoritesMode = !favoritesMode;
    
    // 重置載入狀態
    currentPage = 1;
    restaurantsContainer.innerHTML = '';
    displayedRestaurants = [];
    hasMoreData = true;
    
    // 更新UI
    updateFavoritesButton();
    
    // 重新載入
    loadRestaurants();
    
    const modeText = favoritesMode ? '收藏模式' : '一般模式';
    showToast(`已切換至${modeText}`, 2000);
}

// 更新收藏按鈕狀態
function updateFavoritesButton() {
    const favoritesCount = favorites.length;
    
    if (favoritesMode) {
        favoritesText.textContent = '所有店家';
        favoritesBtn.classList.add('favorites-mode');
        document.body.classList.add('favorites-mode');
    } else {
        favoritesText.textContent = favoritesCount > 0 ? `收藏店家 (${favoritesCount})` : '收藏店家';
        favoritesBtn.classList.remove('favorites-mode');
        document.body.classList.remove('favorites-mode');
    }
}

// 開啟地圖
function openMap(lat, lng, name) {
    // 統一使用指定的 Google Maps 連結
    const mapUrl = 'https://maps.app.goo.gl/QqVgWh59pNdS2eUu7';
    window.open(mapUrl, '_blank');
    
    showToast(`正在開啟 ${name} 的地圖位置...`, 2000);
}

// 顯示餐廳詳情
function showRestaurantDetails(restaurant) {
    const statusText = restaurant.status === 'open' ? '營業中' : '休息中';
    showToast(`${restaurant.name} - ${statusText}`, 2000);
}

// 處理無限捲動
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) {
        loadRestaurants();
    }
}

// 處理鍵盤快捷鍵
function handleKeyDown(e) {
    // ESC清除搜尋
    if (e.key === 'Escape') {
        if (searchInput.value) {
            clearSearchInput();
        }
    }
    
    // Ctrl/Cmd + F 聚焦搜尋
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        searchInput.focus();
        searchInput.select();
    }
}

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

// 處理圖片載入錯誤
function handleImageError(img, restaurantName) {
    // 隱藏載入失敗的圖片
    img.style.display = 'none';
    
    // 顯示佔位符
    const placeholder = img.nextElementSibling;
    if (placeholder && placeholder.classList.contains('image-placeholder')) {
        placeholder.style.display = 'flex';
        placeholder.textContent = `${restaurantName}`;
    }
    
    console.log(`圖片載入失敗: ${img.src}`);
}

// 全域函數（供HTML調用）
window.setPhotoSlide = setPhotoSlide;
window.toggleFavorite = toggleFavorite;
window.openMap = openMap;
window.goBack = goBack;
window.handleImageError = handleImageError;
