// Import the ready-to-use db object from our central init file
import { db } from './firebase-init.php';

// Import the specific functions we need from the Firestore SDK
import { collection, onSnapshot } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

// DOM elements
const menuContent = document.getElementById('menu-content');
const menuLoadingMessage = document.getElementById('menu-loading-message');
const categoryFilter = document.getElementById('menu-category-filter-public');

// Global state to hold all items
let allMenuItems = [];

// Function to populate the category filter dropdown
const populateCategoryFilter = () => {
    if (!categoryFilter) return;
    const categories = [...new Set(allMenuItems.map(item => item.category))].sort();
    
    // Clear existing options except the first one
    categoryFilter.innerHTML = '<option value="all">All Categories</option>'; 
    
    categories.forEach(category => {
        if (category && category !== 'Add-ons') { // Exclude 'Add-ons' from filter
            const option = document.createElement('option');
            option.value = category;
            option.textContent = category;
            categoryFilter.appendChild(option);
        }
    });
};


// Function to render menu items from Firestore, grouped by category
const renderMenuItems = (itemsToRender) => {
    if (!menuContent) return;
    
    // Filter for available items first
    const availableItems = itemsToRender.filter(item => item.status === 'available');

    // Define the desired order and descriptions for categories
    const categoryDetails = {
        "Family Feasts": "Perfect for sharing, our feasts bring the whole table together.",
        "Entrees": "Start your culinary journey with these delicious appetizers.",
        "Bites": "Flavorful bites, perfect for snacking or as a side.",
        "Kottu": "A Sri Lankan classic! Chopped roti mixed with fresh vegetables, egg, and your choice of protein.",
        "Rice Dishes": "Aromatic and satisfying rice dishes, cooked to perfection.",
        "Pasta": "A taste of Italy with a Sri Lankan twist.",
        "Desserts": "Sweet endings to a perfect meal.",
        "Coffee Menu": "Freshly brewed coffee to complement your meal or start your day.",
        "Special Deals": "Great value and amazing taste. Don't miss out on these offers!"
    };
    const categoryOrder = Object.keys(categoryDetails);

    // Group items by category
    const groupedMenu = availableItems.reduce((acc, item) => {
        const category = item.category || 'Uncategorized';
        if (!acc[category]) {
            acc[category] = [];
        }
        acc[category].push(item);
        return acc;
    }, {});

    // Separate and remove Add-ons from the main group
    const allAddons = groupedMenu['Add-ons'] || [];
    delete groupedMenu['Add-ons'];
    
    // Filter add-ons for specific categories
    const kottuAddons = allAddons.filter(item => item.description && item.description.toLowerCase().includes('kottu'));
    const riceAddons = allAddons.filter(item => item.description && item.description.toLowerCase().includes('rice'));
    
    // Sort items within each category alphabetically by name
    for (const category in groupedMenu) {
        groupedMenu[category].sort((a, b) => (a.name || '').localeCompare(b.name || ''));
    }
     // Also sort the add-on groups
    kottuAddons.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
    riceAddons.sort((a, b) => (a.name || '').localeCompare(b.name || ''));

    let contentHtml = '';

    const renderItemHTML = (item) => {
        return `
            <div class="flex items-center space-x-4 p-4 rounded-lg bg-black/50 shadow-lg transition-transform transform hover:scale-105 duration-300">
                <img src="${item.img || 'https://placehold.co/100x100'}" alt="${item.name || ''}" class="w-20 h-20 rounded-full object-cover">
                <div class="flex-grow flex flex-col justify-center overflow-hidden">
                    <p class="text-lg font-normal text-amber-400 whitespace-nowrap overflow-hidden text-ellipsis">${item.name || 'N/A'}</p>
                    <p class="text-sm font-light text-gray-300 clamp-1">${item.description || ''}</p>
                    <span class="text-base font-normal text-gray-300 flex-shrink-0 mt-2">${item.price || ''}</span>
                </div>
            </div>
        `;
    };

    // Determine which categories to iterate over based on filter
    const categoriesToRender = categoryFilter && categoryFilter.value !== 'all' 
        ? [categoryFilter.value] 
        : categoryOrder;

    categoriesToRender.forEach(category => {
        if (groupedMenu[category]) {
            const description = categoryDetails[category] || '';
            // Add category title and description
            contentHtml += `
                <div class="col-span-full mt-10 mb-4 text-left">
                    <h2 class="font-header text-3xl sm:text-4xl uppercase tracking-wider text-amber-400 border-b-2 border-amber-400/50 pb-2 inline-block">
                        ${category}
                    </h2>
                    <p class="text-gray-300 font-light text-base mt-2 max-w-2xl">${description}</p>
                </div>
            `;
            // Add items for that category
            groupedMenu[category].forEach(item => {
                contentHtml += renderItemHTML(item);
            });

            // If the category is Kottu, append its add-ons
            if (category === 'Kottu' && kottuAddons.length > 0) {
                 contentHtml += `
                    <div class="col-span-full mt-6 mb-2 text-left">
                        <h3 class="text-xl font-normal text-amber-300 border-b border-gray-700 pb-1 inline-block">Add-ons</h3>
                    </div>
                 `;
                 kottuAddons.forEach(addon => {
                     contentHtml += renderItemHTML(addon);
                 });
            }

            // If the category is Rice Dishes, append its add-ons
            if (category === 'Rice Dishes' && riceAddons.length > 0) {
                 contentHtml += `
                    <div class="col-span-full mt-6 mb-2 text-left">
                        <h3 class="text-xl font-normal text-amber-300 border-b border-gray-700 pb-1 inline-block">Add-ons</h3>
                    </div>
                 `;
                 riceAddons.forEach(addon => {
                     contentHtml += renderItemHTML(addon);
                 });
            }
        }
    });

    if (contentHtml === '') {
        menuContent.innerHTML = `<p class="text-gray-400 text-center mt-8 col-span-full">No items found for this category. Please check back soon!</p>`;
    } else {
        menuContent.innerHTML = contentHtml;
    }
};


// --- Real-time Listener for the menu ---
const initializeMenuPage = () => {
    if(menuLoadingMessage) menuLoadingMessage.classList.remove('hidden');

    onSnapshot(collection(db, 'menu_items'), (snapshot) => {
        allMenuItems = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        
        // Populate filter and render initial full menu
        populateCategoryFilter();
        renderMenuItems(allMenuItems);

        if(menuLoadingMessage) menuLoadingMessage.classList.add('hidden');
    });
};

// Event listener for the category filter
if (categoryFilter) {
    categoryFilter.addEventListener('change', () => {
        const selectedCategory = categoryFilter.value;
        if (selectedCategory === 'all') {
            renderMenuItems(allMenuItems);
        } else {
            const filteredItems = allMenuItems.filter(item => item.category === selectedCategory);
            renderMenuItems(filteredItems);
        }
    });
}

window.addEventListener('DOMContentLoaded', initializeMenuPage);