/**
 * Maa Mado's Food - Main Script File
 */

// Application State
let menuData = [];
let categories = [];
let currentLang = "de";
let activeCategory = "all";
let currentGalleryIndex = 0;

// Category Translations
const categoryLabels = {
    de: {
        all: "Alle",
        vorspeisen: "Vorspeisen",
        sossen: "Soßen",
        gerichte: "Hauptspeisen",
        getraenke: "Getränke"
    },
    en: {
        all: "All",
        vorspeisen: "Starters",
        sossen: "Sauces",
        gerichte: "Main Dishes",
        getraenke: "Drinks"
    }
};

// Category Descriptions Data
const categoryDescriptions = {
    de: {
        all: "Entdecken Sie unsere vollständige Auswahl an traditionellen Gerichten, frischen Salaten, feinen Soßen und erfrischenden afrikanischen Getränken.",
        vorspeisen: "Knackige Salate und köstliche kleine Appetithappen für einen perfekten Start in Ihr afrikanisches Menü.",
        sossen: "Traditionelle, reichhaltige afrikanische Eintöpfe und Soßen – zubereitet mit Erdnüssen, Okra, Tomaten und aromatischen Gewürzen.",
        gerichte: "Unsere deftigen Hauptspeisen und Spezialitäten des Hauses, serviert mit hochwertigen Zutaten wie Kochbananen, Fisch und feinstem Fleisch.",
        getraenke: "Erfrischende, hausgemachte Fruchtsäfte und traditionelle afrikanische Spezialgetränke."
    },
    en: {
        all: "Discover our full selection of traditional dishes, crisp salads, rich sauces, and refreshing African beverages.",
        vorspeisen: "Fresh salads and delicious appetizers to start your traditional culinary experience.",
        sossen: "Traditional, rich African stews and sauces – prepared with peanut butter, okra, tomatoes, and noble spices.",
        gerichte: "Our hearty main dishes and chef house specialties, served with plantains, fish, and tender meats.",
        getraenke: "Refreshing homemade fruit juices and traditional African drinks."
    }
};

// Gallery Data
const galleryData = [
    {
        title: "Ndolé Royal Spezialität",
        caption: "Unser meistgeliebtes Traditionsgericht mit frittierten Kochbananen.",
        img: "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=1000&q=80"
    },
    {
        title: "Afrikanisches BBQ & Grill",
        caption: "Frisch marinierte Speisen über offener Flamme zubereitet.",
        img: "https://images.unsplash.com/photo-1544025162-d76694265947?auto=format&fit=crop&w=1000&q=80"
    },
    {
        title: "Hausgemachter Bissap & Baobab",
        caption: "Natürliche, hausgemachte Fruchtsäfte voller Aromen.",
        img: "https://images.unsplash.com/photo-1513558161293-cdaf765ed2fd?auto=format&fit=crop&w=1000&q=80"
    },
    {
        title: "Gemischte Vorspeisenteller",
        caption: "Bunte Frische mit knusprigem Alloco und feinsten Dips.",
        img: "https://images.unsplash.com/photo-1540420773420-3366772f4999?auto=format&fit=crop&w=1000&q=80"
    }
];

// Language Dictionary
const translations = {
    de: {
        nav_home: "Startseite",
        nav_menu: "Speisekarte",
        nav_gallery: "Galerie",
        nav_contact: "Kontakt & Team",
        hero_subtitle: "Authentischer Geschmack Afrikas",
        hero_desc: "Erleben Sie kulinarische Traditionsgerichte aus West- und Zentralafrika. Von schmackhafter Erdnusssoße über pikante Ndolé-Kreationen bis hin zu knusprigen Kochbananen – frisch zubereitet mit Liebe und edlen Gewürzen.",
        btn_view_menu: "Speisekarte ansehen",
        btn_visit_us: "Uns besuchen",
        hero_dish_desc: "Bitterleaves und Erdnusssoße mit Rindfleisch, getrocknetem Fisch & Shrimps. Serviert mit frittierten Kochbananen.",
        menu_title: "Unsere Speisekarte",
        menu_subtitle: "Frische Zutaten, traditionelle Rezepte und echte kulinarische Leidenschaft.",
        gallery_title: "Impressionen & Galerie",
        gallery_subtitle: "Ein visueller Einblick in unsere Spezialitäten und unser stimmungsvolles Ambiente.",
        contact_title: "Kontakt & Unser Team",
        contact_info: "Kontaktinformationen",
        team_title: "Unser Organigramm & Team",
        role_headchef: "Chefkochin & Gründerin",
        role_souschef: "Sous Chef",
        role_manager: "Restaurant Managerin",
        role_service: "Serviceleitung"
    },
    en: {
        nav_home: "Home",
        nav_menu: "Menu",
        nav_gallery: "Gallery",
        nav_contact: "Contact & Team",
        hero_subtitle: "Authentic African Taste",
        hero_desc: "Experience traditional culinary dishes from West and Central Africa. From flavorful peanut sauce to spicy Ndolé creations and crispy fried plantains.",
        btn_view_menu: "View Menu",
        btn_visit_us: "Visit Us",
        hero_dish_desc: "Bitterleaves and peanut sauce with beef, dried fish & shrimps. Served with fried plantains.",
        menu_title: "Our Menu",
        menu_subtitle: "Fresh ingredients, traditional recipes, and real culinary passion.",
        gallery_title: "Impressions & Gallery",
        gallery_subtitle: "A visual glance into our culinary specialties and restaurant atmosphere.",
        contact_title: "Contact & Our Team",
        contact_info: "Contact Information",
        team_title: "Our Team Organigram",
        role_headchef: "Head Chef & Founder",
        role_souschef: "Sous Chef",
        role_manager: "Restaurant Manager",
        role_service: "Head of Service"
    }
};

/**
 * Fetch Food Menu Data & Extract Categories
 */
async function fetchMenuData() {
    try {
        const response = await fetch("/api/food");
        if (!response.ok) throw new Error("API response error");
        const data = await response.json();

        menuData = data;

        // Extract unique categories from API data dynamically
        const fetchedCategories = [...new Set(
            data.map(i => {
                if (typeof i.category === 'object' && i.category !== null) {
                    return i.category.slug || i.category.name || i.category.id;
                }
                return i.category;
            }).filter(val => val && String(val).trim() !== "")
        )];

        categories = fetchedCategories.length > 0 ? fetchedCategories : ["vorspeisen", "sossen", "gerichte", "getraenke"];

        renderCategoryButtons();
        filterMenu(activeCategory);
    } catch (err) {
        console.error("Error fetching menu data:", err);
        categories = ["vorspeisen", "sossen", "gerichte", "getraenke"];
        renderCategoryButtons();
        renderMenu(menuData);
    }
}

/**
 * Render Dynamic Category Buttons
 */
function renderCategoryButtons() {
    const catContainer = document.getElementById("menu-categories");
    if (!catContainer) return;

    const allCatList = ["all", ...categories];
    catContainer.innerHTML = "";

    allCatList.forEach(catKey => {
        const btn = document.createElement("button");
        const label = (categoryLabels[currentLang] && categoryLabels[currentLang][catKey])
            ? categoryLabels[currentLang][catKey]
            : (catKey.charAt(0).toUpperCase() + catKey.slice(1));

        btn.className = catKey === activeCategory
            ? "cat-btn active bg-[#74b927] text-white font-bold px-4 sm:px-6 py-2 rounded-full text-xs sm:text-sm transition-all shadow-md"
            : "cat-btn bg-gray-800 text-gray-300 hover:text-white font-bold px-4 sm:px-6 py-2 rounded-full text-xs sm:text-sm transition-all";

        btn.innerHTML = `<span>${label}</span>`;
        btn.onclick = (e) => filterMenu(catKey, e);
        catContainer.appendChild(btn);
    });
}

/**
 * Change Application Language
 */
function setLanguage(lang) {
    currentLang = lang;

    // Update button styles
    const btnDe = document.getElementById("lang-de");
    const btnEn = document.getElementById("lang-en");

    if (btnDe && btnEn) {
        btnDe.className = lang === "de"
            ? "px-2.5 py-1 rounded font-bold transition-all bg-[#74b927] text-white"
            : "px-2.5 py-1 rounded font-bold transition-all text-gray-400 hover:text-white";

        btnEn.className = lang === "en"
            ? "px-2.5 py-1 rounded font-bold transition-all bg-[#74b927] text-white"
            : "px-2.5 py-1 rounded font-bold transition-all text-gray-400 hover:text-white";
    }

    // Translate marked elements
    document.querySelectorAll("[data-i18n]").forEach((elem) => {
        const key = elem.getAttribute("data-i18n");
        if (translations[lang] && translations[lang][key]) {
            elem.innerText = translations[lang][key];
        }
    });

    renderCategoryButtons();
    updateCategoryDescription(activeCategory);
    filterMenu(activeCategory);
}

/**
 * Update Category Description Banner Text
 */
function updateCategoryDescription(category) {
    const descText = document.getElementById("category-description-text");
    if (!descText) return;

    if (categoryDescriptions[currentLang] && categoryDescriptions[currentLang][category]) {
        descText.innerText = categoryDescriptions[currentLang][category];
    } else {
        descText.innerText = categoryDescriptions[currentLang]["all"];
    }
}

/**
 * Render Food Items Grid
 */
function renderMenu(items) {
    const container = document.getElementById("menu-container");
    if (!container) return;

    container.innerHTML = "";

    if (!items || items.length === 0) {
        container.innerHTML = `<div class="col-span-2 text-center text-gray-400 py-8">Keine Gerichte in dieser Kategorie gefunden.</div>`;
        return;
    }

    items.forEach((item) => {
        const card = document.createElement("div");
        card.className = "glass-panel p-5 sm:p-6 rounded-2xl flex flex-col sm:flex-row gap-5 items-center hover:border-[#74b927]/50 transition-all border border-gray-800 shadow-md";

        let priceFormatted = "";
        if (item.price !== undefined && item.price !== null) {
            const price1Num = Number(item.price) || 0;
            if (item.price_alternative && item.price2 !== undefined && item.price2 !== null) {
                const price2Num = Number(item.price2) || 0;
                priceFormatted = `${price1Num.toFixed(2).replace('.', ',')} € | ${price2Num.toFixed(2).replace('.', ',')} €`;
            } else {
                priceFormatted = `${price1Num.toFixed(2).replace('.', ',')} €`;
            }
        }

        const imageHtml = (item.img && item.img.trim() !== "")
            ? `<img src="${item.img}" class="w-full sm:w-32 h-32 object-cover rounded-xl shadow-md flex-shrink-0" alt="${item.title || 'Food Item'}">`
            : '';

        card.innerHTML = `
            ${imageHtml}
            <div class="flex-1 w-full flex flex-col justify-between">
                <div>
                    <div class="flex justify-between items-start gap-2 mb-2">
                        <h4 class="text-base sm:text-lg font-bold text-white leading-snug">${item.title || item.name || ''}</h4>
                        ${priceFormatted ? `<span class="text-[#74b927] font-black text-sm sm:text-base whitespace-nowrap bg-[#74b927]/10 px-2.5 py-1 rounded-lg border border-[#74b927]/30">${priceFormatted}</span>` : ''}
                    </div>
                    <p class="text-xs sm:text-sm text-gray-400 leading-relaxed">${item.description || ''}</p>
                </div>
            </div>
        `;
        container.appendChild(card);
    });
}

/**
 * Filter Items by Selected Category
 */
function filterMenu(category, event) {
    activeCategory = category;

    document.querySelectorAll("#menu-categories .cat-btn").forEach((btn) => {
        btn.className = "cat-btn bg-gray-800 text-gray-300 hover:text-white font-bold px-4 sm:px-6 py-2 rounded-full text-xs sm:text-sm transition-all";
    });

    if (event && event.currentTarget) {
        event.currentTarget.className = "cat-btn active bg-[#74b927] text-white font-bold px-4 sm:px-6 py-2 rounded-full text-xs sm:text-sm transition-all shadow-md";
    }

    updateCategoryDescription(category);

    if (category === "all") {
        renderMenu(menuData);
    } else {
        const filtered = menuData.filter((item) => {
            const itemCat = typeof item.category === 'object' && item.category !== null
                ? (item.category.slug || item.category.name || item.category.id)
                : item.category;
            return String(itemCat).toLowerCase() === String(category).toLowerCase();
        });
        renderMenu(filtered);
    }
}

/**
 * Gallery Carousel Logic
 */
function updateGalleryCarousel() {
    const total = galleryData.length;
    if (total === 0) return;

    const prevIndex = (currentGalleryIndex - 1 + total) % total;
    const nextIndex = (currentGalleryIndex + 1) % total;

    const activeImg = document.getElementById("active-gallery-img");
    const activeTitle = document.getElementById("active-gallery-title");
    const activeCaption = document.getElementById("active-gallery-caption");
    const prevImg = document.getElementById("prev-img-preview");
    const nextImg = document.getElementById("next-img-preview");

    if (activeImg) activeImg.src = galleryData[currentGalleryIndex].img;
    if (activeTitle) activeTitle.innerText = galleryData[currentGalleryIndex].title;
    if (activeCaption) activeCaption.innerText = galleryData[currentGalleryIndex].caption;

    if (prevImg) prevImg.src = galleryData[prevIndex].img;
    if (nextImg) nextImg.src = galleryData[nextIndex].img;

    const dotsContainer = document.getElementById("carousel-dots");
    if (dotsContainer) {
        dotsContainer.innerHTML = "";
        galleryData.forEach((_, idx) => {
            const dot = document.createElement("button");
            dot.setAttribute("aria-label", `Go to slide ${idx + 1}`);
            dot.className = idx === currentGalleryIndex
                ? "w-8 h-2.5 rounded-full bg-[#74b927] transition-all"
                : "w-2.5 h-2.5 rounded-full bg-gray-700 hover:bg-gray-500 transition-all";
            dot.onclick = () => {
                currentGalleryIndex = idx;
                updateGalleryCarousel();
            };
            dotsContainer.appendChild(dot);
        });
    }
}

function prevSlide() {
    currentGalleryIndex = (currentGalleryIndex - 1 + galleryData.length) % galleryData.length;
    updateGalleryCarousel();
}

function nextSlide() {
    currentGalleryIndex = (currentGalleryIndex + 1) % galleryData.length;
    updateGalleryCarousel();
}

function toggleMobileMenu() {
    const mobileMenu = document.getElementById("mobile-menu");
    if (mobileMenu) mobileMenu.classList.toggle("hidden");
}

/**
 * Event Listener Initialization Best Practices
 */
document.addEventListener("DOMContentLoaded", () => {
    // Initial UI setup
    updateCategoryDescription("all");
    updateGalleryCarousel();
    fetchMenuData();

    // Event listener bindings
    document.getElementById("mobile-menu-btn")?.addEventListener("click", toggleMobileMenu);
    document.getElementById("prev-slide-btn")?.addEventListener("click", prevSlide);
    document.getElementById("next-slide-btn")?.addEventListener("click", nextSlide);
    document.getElementById("prev-preview-btn")?.addEventListener("click", prevSlide);
    document.getElementById("next-preview-btn")?.addEventListener("click", nextSlide);

    // Delegate clicks for elements with data attributes
    document.querySelectorAll('[data-action="set-language"]').forEach(btn => {
        btn.addEventListener('click', (e) => setLanguage(e.currentTarget.dataset.lang));
    });

    document.querySelectorAll('[data-action="close-mobile-menu"]').forEach(link => {
        link.addEventListener('click', toggleMobileMenu);
    });
});