
class MenuApp {
    constructor() {
        this.restaurantSlug = window.restaurantSlug;
        this.restaurant = null;
        this.categoryTypes = [];
        this.allCategories = []; // All categories combined
        this.categories = {}; // Legacy property, initialize to prevent errors
        this.currentType = null; // Legacy property, initialize to prevent errors
        this.selectedCategoryType = null; // Currently selected category type for filtering
        this.menuItems = {};
        this.saleItems = [];
        this.hotItems = [];
        this.comboPromotions = [];
        this.celebrationMenus = [];
        this.selectedCategory = null;
        this.cart = [];
        this.cartVisible = false;

        this.currentLanguage = localStorage.getItem('menu_language') || 'mk';
        this.init();
    }

    async init() {

        this.clearCache();
        

        
        await this.loadRestaurant();
        await this.loadAndApplyTheme();
        // Load cart for this specific restaurant
        this.loadCart();
        await this.loadCategoryTypes();
        await this.loadAllCategories();
        await this.loadComboPromotions();
        await this.loadHotItems();
        await this.loadCelebrationMenus();
        this.render();
        this.updateCartCount();
        // Language selector is now handled by language-selector.js
    }
    
    changeLanguage(language) {
        this.currentLanguage = language;
        localStorage.setItem('menu_language', language);
        this.render();
        // Language selector will auto-update via changeMenuLanguage in language-selector.js
    }
    
    getLocalizedText(item, field) {
        if (!item) return '';
        
        const mkField = `${field}_mk`;
        const enField = `${field}_en`;
        const alField = `${field}_al`;
        
        if (this.currentLanguage === 'mk') {
            return item[mkField] || item[enField] || item[alField] || item[field] || '';
        } else if (this.currentLanguage === 'al') {
            return item[alField] || item[mkField] || item[enField] || item[field] || '';
        } else {
            return item[enField] || item[mkField] || item[alField] || item[field] || '';
        }
    }
    
    getUIText(key) {
        const translations = {
            mk: {
                cart: 'Кошничка',
                order: 'Нарачка',
                total: 'Вкупно',
                clearAll: 'Исчисти се',
                menu: 'Мени',
                promotions: 'Промоции',
                sale: 'Попуст',
                hot_items: 'Врели Специјалитети',
                celebration_menu: 'Мени за Прослави',
                size: 'Големина',
                allergens: 'Алергени',
                includes: 'Содржи',
                save: 'Заштеди',
                comboPromotion: 'Комбо Промоција',
                currency: 'ден',
                pricePerPerson: 'Цена по лице'
            },
            en: {
                cart: 'Cart',
                order: 'Order',
                total: 'Total',
                clearAll: 'Clear All',
                menu: 'Menu',
                promotions: 'Promotions',
                sale: 'Sale',
                hot_items: 'Hot Items',
                celebration_menu: 'Celebration Menu',
                size: 'Size',
                allergens: 'Allergens',
                includes: 'Includes',
                save: 'Save',
                comboPromotion: 'Combo Promotion',
                currency: 'den',
                pricePerPerson: 'Price Per Person'
            },
            al: {
                cart: 'Shporta',
                order: 'Porosia',
                total: 'Totali',
                clearAll: 'Pastro të gjitha',
                menu: 'Meny',
                promotions: 'Promovime',
                sale: 'Zbritje',
                hot_items: 'Artikuj të nxehtë',
                celebration_menu: 'Meny festash',
                size: 'Madhësia',
                allergens: 'Alergjikë',
                includes: 'Përfshin',
                save: 'Ruaj',
                comboPromotion: 'Promovim Combo',
                currency: 'den',
                pricePerPerson: 'Çmimi për person'
            }
        };
        
        return translations[this.currentLanguage]?.[key] || translations['en']?.[key] || key;
    }

    getHotItemsLabel() {
        // Check if restaurant has custom hot items label
        if (this.restaurant) {
            if (this.currentLanguage === 'mk' && this.restaurant.hot_items_label_mk) {
                return this.restaurant.hot_items_label_mk;
            } else if (this.currentLanguage === 'en' && this.restaurant.hot_items_label_en) {
                return this.restaurant.hot_items_label_en;
            } else if (this.currentLanguage === 'al' && this.restaurant.hot_items_label_al) {
                return this.restaurant.hot_items_label_al;
            } else if (this.restaurant.hot_items_label) {
                return this.restaurant.hot_items_label;
            }
        }
        // Fallback to default translations
        return this.getUIText('hot_items');
    }
    
    // Transliterate text between Latin and Cyrillic
    transliterateAddress(text, toLatin = true) {
        if (!text) return '';
        
        // Latin to Cyrillic mapping
        const latinToCyrillic = {
    'A': 'А', 'B': 'Б', 'V': 'В', 'G': 'Г', 'D': 'Д', 'Gj': 'Ѓ',
    'E': 'Е', 'Zh': 'Ж', 'Z': 'З', 'Dz': 'Ѕ', 'I': 'И', 'J': 'Ј',
    'K': 'К', 'L': 'Л', 'Lj': 'Љ', 'M': 'М', 'N': 'Н', 'Nj': 'Њ', 'O': 'О',
    'P': 'П', 'R': 'Р', 'S': 'С', 'T': 'Т', 'Kj': 'Ќ', 'U': 'У',
    'F': 'Ф', 'H': 'Х', 'C': 'Ц', 'Ch': 'Ч', 'Dz': 'Џ',
    'Sh': 'Ш',
    'a': 'а', 'b': 'б', 'v': 'в', 'g': 'г', 'd': 'д', 'gj': 'ѓ',
    'e': 'е', 'zh': 'ж', 'z': 'з', 'dz': 'ѕ', 'i': 'и', 'j': 'ј',
    'k': 'к', 'l': 'л', 'lj': 'љ', 'm': 'м', 'n': 'н', 'nj': 'њ', 'o': 'о',
    'p': 'п', 'r': 'р', 's': 'с', 't': 'т', 'kj': 'ќ', 'u': 'у',
    'f': 'ф', 'h': 'х', 'c': 'ц', 'ch': 'ч', 'dz': 'џ',
    'sh': 'ш'
};

// Cyrillic to Latin mapping
const cyrillicToLatin = {
    'А': 'A', 'Б': 'B', 'В': 'V', 'Г': 'G', 'Д': 'D', 'Ѓ': 'Gj',
    'Е': 'E', 'Ж': 'Zh', 'З': 'Z', 'Ѕ': 'Dz', 'И': 'I', 'Ј': 'J',
    'К': 'K', 'Л': 'L', 'Љ': 'Lj', 'М': 'M', 'Н': 'N', 'Њ': 'Nj', 'О': 'O',
    'П': 'P', 'Р': 'R', 'С': 'S', 'Т': 'T', 'Ќ': 'Kj', 'У': 'U',
    'Ф': 'F', 'Х': 'H', 'Ц': 'C', 'Ч': 'Ch', 'Џ': 'Dz',
    'Ш': 'Sh',
    'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'ѓ': 'gj',
    'е': 'e', 'ж': 'zh', 'з': 'z', 'и': 'i', 'ј': 'j',
    'к': 'k', 'л': 'l', 'љ': 'lj', 'м': 'm', 'н': 'n', 'њ': 'nj', 'о': 'o',
    'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'ќ': 'kj', 'у': 'u',
    'ф': 'f', 'х': 'h', 'ц': 'c', 'ч': 'ch', 'џ': 'dz',
    'ш': 'sh'
};
        
        const mapping = toLatin ? cyrillicToLatin : latinToCyrillic;
        
        // Sort keys by length (longest first) to handle multi-character mappings
        const sortedKeys = Object.keys(mapping).sort((a, b) => b.length - a.length);
        
        let result = text;
        for (const key of sortedKeys) {
            const regex = new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
            result = result.replace(regex, mapping[key]);
        }
        
        return result;
    }
    
    // Get address with proper transliteration based on language
    getLocalizedAddress(address) {
        if (!address) return '';
        
        // Detect if address is in Cyrillic
        const hasCyrillic = /[А-Яа-яЈ-Џј-џ]/.test(address);
        
        if (this.currentLanguage === 'en') {
            // English: convert to Latin
            return hasCyrillic ? this.transliterateAddress(address, true) : address;
        } else {
            // Macedonian: convert to Cyrillic
            return hasCyrillic ? address : this.transliterateAddress(address, false);
        }
    }

    clearCache() {

        this.categoryTypes = [];
        this.allCategories = [];
        this.menuItems = {};
        this.saleItems = [];
        this.hotItems = [];
        this.comboPromotions = [];
        this.celebrationMenus = [];
        this.selectedCategory = null;
        this.selectedCategoryType = null;
    }

    showLoading(message = 'Loading...') {
        const app = document.getElementById('app');
        if (app) {
            app.innerHTML = `
                <div class="text-center py-8">
                    <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-brand-orange mx-auto"></div>
                    <p class="mt-4 text-gray-600">${message}</p>
                </div>
            `;
        }
    }

    async loadRestaurant() {
        try {

            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}?t=${Date.now()}`);
            if (response.data.success) {
                this.restaurant = response.data.data;

                document.title = `${this.restaurant.name} - Menu`;
            } else {
                this.showError('Restaurant not found');
            }
        } catch (error) {
            console.error('Error loading restaurant:', error);
            this.showError('Failed to load restaurant information');
        }
    }

    async loadAndApplyTheme() {
        try {
            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/theme?t=${Date.now()}`);
            if (response.data.success) {
                const theme = response.data.data;
                this.applyTheme(theme);
            }
        } catch (error) {
            console.error('Error loading theme:', error);
            // Continue with default theme if loading fails
        }
    }

    applyTheme(theme) {
        if (!theme) return;
        
        this.currentTheme = theme;
        const root = document.documentElement;
        
        // Apply CSS custom properties for the theme
        root.style.setProperty('--theme-bg', theme.background_color);
        root.style.setProperty('--theme-text', theme.text_color);
        root.style.setProperty('--theme-accent', theme.accent_color);
        root.style.setProperty('--theme-cta', theme.cta_color);
        root.style.setProperty('--theme-header', theme.header_color || theme.accent_color);
        root.style.setProperty('--theme-button', theme.button_color || theme.cta_color);
        root.style.setProperty('--theme-font', theme.font_style);
        
        // Apply to body for immediate effect
        document.body.style.backgroundColor = theme.background_color;
        document.body.style.color = theme.text_color;
        document.body.style.fontFamily = theme.font_style;
        
        // Create dynamic style overrides for theme-specific colors
        let styleEl = document.getElementById('theme-overrides');
        if (!styleEl) {
            styleEl = document.createElement('style');
            styleEl.id = 'theme-overrides';
            document.head.appendChild(styleEl);
        }
        
        const headerColor = theme.header_color || theme.accent_color;
        const buttonColor = theme.button_color || theme.cta_color;
        const lightBg = this.lightenColor(theme.background_color, 3);
        const cardBg = this.adjustColorBrightness(theme.background_color, theme.text_color);
        
        // Override Tailwind classes with theme colors
        styleEl.textContent = `
            /* ============================================
               BACKGROUND COLORS
               ============================================ */
            
            /* Main backgrounds */
            .bg-gray-50 { background-color: ${lightBg} !important; }
            .bg-white { background-color: ${cardBg} !important; }
            .bg-gray-100 { background-color: ${lightBg} !important; }
            
            /* Card backgrounds */
            .menu-item-card { background-color: ${cardBg} !important; }
            
            /* Navigation bars - sticky headers */
            .sticky.bg-white { background-color: ${cardBg} !important; }
            
            /* Modal backgrounds */
            #item-detail-modal > div { background-color: ${cardBg} !important; }
            
            /* Cart sidebar */
            #cart-sidebar { background-color: ${cardBg} !important; }
            
            /* ============================================
               TEXT COLORS
               ============================================ */
            
            /* Primary text */
            .text-gray-900, .text-gray-800, .text-gray-700, .text-gray-600 { 
                color: ${theme.text_color} !important; 
            }
            
            /* Accent text */
            .text-orange-600, .text-orange-500, .text-orange-900 { 
                color: ${theme.accent_color} !important; 
            }
            
            /* Lighter text for secondary info */
            .text-gray-500 { 
                color: ${this.adjustOpacity(theme.text_color, 0.7)} !important; 
            }
            .text-gray-400 { 
                color: ${this.adjustOpacity(theme.text_color, 0.5)} !important; 
            }
            
            /* ============================================
               HEADER & BANNER STYLES
               ============================================ */
            
            /* Restaurant info header gradient */
            .bg-gradient-to-r.from-brand-orange.to-brand-red { 
                background: linear-gradient(to right, ${headerColor}, ${this.darkenColor(headerColor, 15)}) !important; 
            }
            
            /* ============================================
               BUTTON & INTERACTIVE ELEMENTS
               ============================================ */
            
            /* Primary buttons */
            .bg-brand-orange,
            .bg-orange-600, 
            .bg-orange-500 { 
                background-color: ${buttonColor} !important; 
            }
            
            /* Button hover states */
            .hover\\:bg-orange-700:hover,
            .hover\\:bg-brand-red:hover { 
                background-color: ${this.darkenColor(buttonColor, 10)} !important; 
            }
            
            /* Category buttons - Active state */
            .category-btn.bg-brand-orange {
                background-color: ${buttonColor} !important;
                color: white !important;
            }
            
            /* Category buttons - Inactive state */
            .category-btn.bg-gray-200 {
                background-color: ${this.lightenColor(theme.text_color, 85)} !important;
                color: ${theme.text_color} !important;
            }
            
            .category-btn.bg-gray-200:hover {
                background-color: ${this.lightenColor(theme.text_color, 75)} !important;
            }
            
            /* ============================================
               BORDERS
               ============================================ */
            
            /* Border colors */
            .border-orange-300, 
            .border-orange-200,
            .border-orange-500,
            .border-orange-100 { 
                border-color: ${this.lightenColor(buttonColor, 30)} !important; 
            }
            
            .border-gray-200,
            .border-gray-100 {
                border-color: ${this.lightenColor(theme.text_color, 85)} !important;
            }
            
            /* ============================================
               TABS & NAVIGATION
               ============================================ */
            
            /* Tab active states */
            .border-orange-500 { 
                border-color: ${buttonColor} !important; 
            }
            .text-orange-500 { 
                color: ${buttonColor} !important; 
            }
            
            /* Sale tab */
            .border-red-500 {
                border-color: ${this.darkenColor(buttonColor, 20)} !important;
            }
            .text-red-500 {
                color: ${this.darkenColor(buttonColor, 20)} !important;
            }
            
            /* ============================================
               PROMOTION CARDS
               ============================================ */
            
            /* Promotion card gradient backgrounds */
            .bg-gradient-to-br.from-orange-50 { 
                background: linear-gradient(to bottom right, 
                    ${this.lightenColor(buttonColor, 45)}, 
                    ${this.lightenColor(buttonColor, 50)}) !important; 
            }
            
            /* Promotion card borders */
            .border-2.border-orange-300 {
                border-color: ${this.lightenColor(buttonColor, 35)} !important;
            }
            
            /* Promotion icons and badges */
            .bg-orange-600.text-white {
                background-color: ${buttonColor} !important;
            }
            
            .text-orange-600 {
                color: ${buttonColor} !important;
            }
            
            .bg-orange-100 {
                background-color: ${this.lightenColor(buttonColor, 45)} !important;
            }
            
            /* ============================================
               SALE & DISCOUNT ELEMENTS
               ============================================ */
            
            /* Red sale elements */
            .bg-red-500, .bg-red-600 {
                background-color: ${this.darkenColor(buttonColor, 15)} !important;
            }
            
            .text-red-600 {
                color: ${this.darkenColor(buttonColor, 15)} !important;
            }
            
            .bg-red-100 {
                background-color: ${this.lightenColor(this.darkenColor(buttonColor, 15), 40)} !important;
            }
            
            /* ============================================
               HOVER & FOCUS STATES
               ============================================ */
            
            /* Ring colors for focus states */
            .ring-brand-orange { 
                --tw-ring-color: ${buttonColor} !important; 
            }
            
            /* Hover opacity for buttons */
            .hover\\:bg-gray-300:hover {
                background-color: ${this.lightenColor(theme.text_color, 70)} !important;
            }
            
            /* ============================================
               ICONS & BADGES
               ============================================ */
            
            /* Cart icon and accent icons */
            .text-brand-orange {
                color: ${buttonColor} !important;
            }
            
            /* Green success elements */
            .bg-green-50 {
                background-color: ${this.lightenColor(buttonColor, 50)} !important;
            }
            
            .text-green-600 {
                color: ${this.darkenColor(buttonColor, 5)} !important;
            }
            
            /* ============================================
               SECONDARY ELEMENTS
               ============================================ */
            
            /* Gray backgrounds for inactive elements */
            .bg-gray-200 {
                background-color: ${this.lightenColor(theme.text_color, 85)} !important;
            }
            
            /* Status indicators and info boxes */
            .bg-gray-50.rounded-lg {
                background-color: ${this.lightenColor(theme.background_color, 5)} !important;
            }
            
            /* ============================================
               LOADING & ANIMATIONS
               ============================================ */
            
            /* Loading spinner */
            .border-brand-orange {
                border-color: ${buttonColor} !important;
            }
            
            /* ============================================
               RESPONSIVE & MOBILE
               ============================================ */
            
            /* Ensure consistent theming on all screen sizes */
            @media (max-width: 640px) {
                .bg-white, .bg-gray-50 {
                    background-color: ${cardBg} !important;
                }
            }
        `;
    }
    
    // Helper to adjust color brightness based on contrast
    adjustColorBrightness(bgColor, textColor) {
        // If background is dark, lighten slightly for cards
        // If background is light, keep it or darken slightly
        const bgLightness = this.getColorLightness(bgColor);
        const textLightness = this.getColorLightness(textColor);
        
        // Dark theme detection: dark bg + light text
        if (bgLightness < 50 && textLightness > 50) {
            return this.lightenColor(bgColor, 5);
        }
        // Light theme: light bg + dark text
        return bgColor;
    }
    
    // Get perceived lightness of a color (0-100)
    getColorLightness(color) {
        const hex = color.replace('#', '');
        const r = parseInt(hex.substr(0, 2), 16);
        const g = parseInt(hex.substr(2, 2), 16);
        const b = parseInt(hex.substr(4, 2), 16);
        // Use perceived lightness formula
        return (r * 0.299 + g * 0.587 + b * 0.114) / 2.55;
    }
    
    // Adjust opacity of a color (for semi-transparent text)
    adjustOpacity(color, opacity) {
        const hex = color.replace('#', '');
        const r = parseInt(hex.substr(0, 2), 16);
        const g = parseInt(hex.substr(2, 2), 16);
        const b = parseInt(hex.substr(4, 2), 16);
        return `rgba(${r}, ${g}, ${b}, ${opacity})`;
    }
    
    // Helper function to darken a color
    darkenColor(color, percent) {
        const num = parseInt(color.replace("#",""), 16);
        const amt = Math.round(2.55 * percent);
        const R = (num >> 16) - amt;
        const G = (num >> 8 & 0x00FF) - amt;
        const B = (num & 0x0000FF) - amt;
        return "#" + (0x1000000 + (R<255?R<1?0:R:255)*0x10000 +
            (G<255?G<1?0:G:255)*0x100 +
            (B<255?B<1?0:B:255))
            .toString(16).slice(1);
    }
    
    // Helper function to lighten a color
    lightenColor(color, percent) {
        const num = parseInt(color.replace("#",""), 16);
        const amt = Math.round(2.55 * percent);
        const R = (num >> 16) + amt;
        const G = (num >> 8 & 0x00FF) + amt;
        const B = (num & 0x0000FF) + amt;
        return "#" + (0x1000000 + (R<255?R<1?0:R:255)*0x10000 +
            (G<255?G<1?0:G:255)*0x100 +
            (B<255?B<1?0:B:255))
            .toString(16).slice(1);
    }

    async loadCategoryTypes() {
        try {

            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/category-types?t=${Date.now()}`);
            if (response.data.success) {
                this.categoryTypes = response.data.data.sort((a, b) => a.display_order - b.display_order);
            }
        } catch (error) {
            console.error('Error loading category types:', error);
            this.showError('Failed to load menu sections');
        }
    }

    async loadAllCategories() {
        try {

            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/categories?t=${Date.now()}`);
            if (response.data.success) {
                this.allCategories = response.data.data.sort((a, b) => {

                    const typeA = this.categoryTypes.find(t => t.name === a.type);
                    const typeB = this.categoryTypes.find(t => t.name === b.type);
                    const typeOrderA = typeA ? typeA.display_order : 999;
                    const typeOrderB = typeB ? typeB.display_order : 999;
                    
                    if (typeOrderA !== typeOrderB) {
                        return typeOrderA - typeOrderB;
                    }
                    return a.display_order - b.display_order;
                });
            } else {
                this.allCategories = [];
            }
            await this.loadSaleItems();
            this.selectFirstAvailableCategory();
        } catch (error) {
            console.error('Error loading categories:', error);
            this.showError('Failed to load menu categories');
        }
    }

    async loadSaleItems() {
        try {

            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/sale-items?t=${Date.now()}`);
            if (response.data.success) {
                this.saleItems = response.data.data;
            } else {
                this.saleItems = [];
            }
        } catch (error) {
            console.error('Error loading sale items:', error);
            this.saleItems = [];
        }
    }

    async loadComboPromotions() {
        try {

            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/promotions?t=${Date.now()}`);
            if (response.data.success) {
                this.comboPromotions = response.data.data;
            } else {
                this.comboPromotions = [];
            }
        } catch (error) {
            console.error('Error loading promotions:', error);
            this.comboPromotions = [];
        }
    }

    async loadHotItems() {
        try {
            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/hot-items?t=${Date.now()}`);
            if (response.data.success) {
                this.hotItems = response.data.data;
            } else {
                this.hotItems = [];
            }
        } catch (error) {
            console.error('Error loading hot items:', error);
            this.hotItems = [];
        }
    }

    async loadCelebrationMenus() {
        try {
            const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}/celebration-menus?t=${Date.now()}`);
            if (response.data.success) {
                this.celebrationMenus = response.data.data;
            } else {
                this.celebrationMenus = [];
            }
        } catch (error) {
            console.error('Error loading celebration menus:', error);
            this.celebrationMenus = [];
        }
    }

    selectFirstAvailableCategory() {
        if (this.categoryTypes.length > 0 && this.allCategories.length > 0) {

            const firstType = this.categoryTypes.sort((a, b) => a.display_order - b.display_order)[0];
            this.selectedCategoryType = firstType.name;
            

            const firstCategoryOfType = this.allCategories
                .filter(cat => cat.type === firstType.name)
                .sort((a, b) => a.display_order - b.display_order)[0];
            
            if (firstCategoryOfType) {
                this.selectCategory(firstCategoryOfType);
                return;
            }
        }
        

        if (this.comboPromotions.length > 0) {
            this.selectedCategory = { id: 'combo-promotions', name: 'Promotions' };
            this.selectedCategoryType = null; // Clear type selection for special tabs
            this.renderComboPromotions();
            return;
        }
        

        if (this.saleItems.length > 0) {
            this.selectedCategory = { id: 'sale', name: 'Sale Items' };
            this.selectedCategoryType = null; // Clear type selection for special tabs
            this.renderSaleItems();
            return;
        }
        

        this.selectedCategory = null;
        this.selectedCategoryType = null;
    }

    async loadMenuItems(categoryId, forceReload = false) {
        try {

            if (forceReload || !this.menuItems[categoryId]) {
                const response = await axios.get(`/api/categories/${categoryId}/items?t=${Date.now()}`);
                if (response.data.success) {
                    this.menuItems[categoryId] = response.data.data;
                }
            }
            this.renderMenuItems();
        } catch (error) {
            console.error('Error loading menu items:', error);
            this.showError('Failed to load menu items');
        }
    }

    showError(message) {
        const app = document.getElementById('app');
        app.innerHTML = `
            <div class="max-w-4xl mx-auto p-6">
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    ${message}
                </div>
                <div class="mt-4">
                    <a href="/" class="text-blue-600 hover:text-blue-800">
                        <i class="fas fa-arrow-left mr-2"></i>Back to Home
                    </a>
                </div>
            </div>
        `;
    }

    switchToComboPromotions() {

        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        

        this.selectedCategoryType = null;
        this.selectedCategory = { id: 'combo-promotions', name: 'Promotions' };
        this.renderComboPromotions();
        this.render();
        

        setTimeout(() => {
            window.scrollTo(0, scrollPosition);
        }, 50);
    }

    switchToSale() {

        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        

        this.selectedCategoryType = null;
        this.selectedCategory = { id: 'sale', name: 'Sale Items' };
        this.renderSaleItems();
        this.render();
        

        setTimeout(() => {
            window.scrollTo(0, scrollPosition);
        }, 50);
    }

    switchToHotItems() {

        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        

        this.selectedCategoryType = null;
        this.selectedCategory = { id: 'hot-items', name: 'Hot Items' };
        this.renderHotItems();
        this.render();
        

        setTimeout(() => {
            window.scrollTo(0, scrollPosition);
        }, 50);
    }

    switchToCelebrationMenus() {

        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        

        this.selectedCategoryType = null;
        this.selectedCategory = { id: 'celebration-menus', name: 'Celebration Menus' };
        this.renderCelebrationMenus();
        this.render();
        

        setTimeout(() => {
            window.scrollTo(0, scrollPosition);
        }, 50);
    }

    switchToMenu() {

        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        

        this.selectedCategory = null;
        

        if (this.categoryTypes.length > 0 && this.allCategories.length > 0) {
            const firstType = this.categoryTypes.sort((a, b) => a.display_order - b.display_order)[0];
            this.selectedCategoryType = firstType.name;
            
            const firstCategoryOfType = this.allCategories
                .filter(cat => cat.type === firstType.name)
                .sort((a, b) => a.display_order - b.display_order)[0];
            
            if (firstCategoryOfType) {
                this.selectCategory(firstCategoryOfType);
            } else {
                this.selectedCategory = null;
                this.renderMenuItems();
            }
        } else {
            this.selectedCategory = null;
            this.selectedCategoryType = null;
            this.renderMenuItems();
        }
        
        this.render();
        

        setTimeout(() => {
            window.scrollTo(0, scrollPosition);
        }, 50);
    }

    selectCategoryType(typeName) {

        const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        
        this.selectedCategoryType = typeName;
        

        const firstCategoryOfType = this.allCategories
            .filter(cat => cat.type === typeName)
            .sort((a, b) => a.display_order - b.display_order)[0];
        
        if (firstCategoryOfType) {
            this.selectCategory(firstCategoryOfType);
        } else {
            this.selectedCategory = null;
            this.renderMenuItems();
        }
        
        this.render();
        

        setTimeout(() => {
            window.scrollTo(0, scrollPosition);
        }, 50);
    }

    async selectCategory(category) {
        this.selectedCategory = category;
        

        await this.loadMenuItems(category.id, true);
        

        document.querySelectorAll('.category-btn').forEach(btn => {
            btn.classList.remove('bg-brand-orange', 'text-white', 'hover:bg-gray-300');
            btn.classList.add('bg-gray-200', 'text-gray-700');
        });
        
        const activeBtn = document.querySelector(`[data-category-id="${category.id}"]`);
        if (activeBtn) {
            activeBtn.classList.remove('bg-gray-200', 'text-gray-700', 'hover:bg-gray-300');
            activeBtn.classList.add('bg-brand-orange', 'text-white');
        }
    }

    render() {
        if (!this.restaurant) return;

        const app = document.getElementById('app');
        const currentCategories = this.allCategories || [];

        app.innerHTML = `

            <!-- Restaurant Info -->
            <div class="bg-gradient-to-r from-brand-orange to-brand-red text-white">
                <div class="max-w-7xl mx-auto px-4 py-6 sm:py-8">
                    <div class="flex flex-col sm:flex-row items-center sm:items-start space-y-4 sm:space-y-0 sm:space-x-6 text-center sm:text-left">
                        ${this.restaurant.logo_url ? `
                            <img src="${this.restaurant.logo_url}" 
                                 alt="${this.restaurant.name}"
                                 class="w-16 h-16 sm:w-20 sm:h-20 rounded-full object-cover border-2 border-white flex-shrink-0">
                        ` : `
                            <div class="w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-white bg-opacity-20 flex items-center justify-center flex-shrink-0">
                                <i class="fas fa-utensils text-xl sm:text-2xl"></i>
                            </div>
                        `}
                        
                        <div class="flex-1 min-w-0">
                            <h1 class="text-xl sm:text-2xl md:text-3xl font-bold mb-2">${this.getLocalizedText(this.restaurant, 'name')}</h1>
                            ${this.getLocalizedText(this.restaurant, 'description') ? `
                                <p class="text-sm sm:text-base md:text-lg opacity-90 mb-3">${this.getLocalizedText(this.restaurant, 'description')}</p>
                            ` : ''}
                            
                            <div class="flex flex-col sm:flex-row flex-wrap gap-2 sm:gap-4 text-xs sm:text-sm opacity-80">
                                ${this.restaurant.address ? `
                                    <div class="flex items-center justify-center sm:justify-start">
                                        <i class="fas fa-map-marker-alt mr-1 flex-shrink-0"></i>
                                        <span class="break-words">${this.getLocalizedAddress(this.restaurant.address)}</span>
                                    </div>
                                ` : ''}
                                ${this.restaurant.phone ? `
                                    <div class="flex items-center justify-center sm:justify-start">
                                        <i class="fas fa-phone mr-1 flex-shrink-0"></i>
                                        <span>${this.restaurant.phone}</span>
                                    </div>
                                ` : ''}
                                ${this.restaurant.website ? `
                                    <div class="flex items-center justify-center sm:justify-start">
                                        <i class="fas fa-globe mr-1 flex-shrink-0"></i>
                                        <a href="${this.restaurant.website.startsWith('http') ? this.restaurant.website : 'https://' + this.restaurant.website}" 
                                           target="_blank" 
                                           rel="noopener noreferrer" 
                                           class="break-words hover:text-yellow-200 underline">${this.restaurant.website}</a>
                                    </div>
                                ` : ''}
                                ${(this.restaurant.facebook || this.restaurant.instagram) ? `
                                    <div class="flex items-center justify-center sm:justify-start gap-4">
                                        ${this.restaurant.facebook ? `
                                            <a href="${this.restaurant.facebook.startsWith('http') ? this.restaurant.facebook : 'https://' + this.restaurant.facebook}" 
                                               target="_blank" 
                                               rel="noopener noreferrer" 
                                               class="hover:text-yellow-200 transition-colors">
                                                <i class="fab fa-facebook text-2xl"></i>
                                            </a>
                                        ` : ''}
                                        ${this.restaurant.instagram ? `
                                            <a href="${this.restaurant.instagram.startsWith('http') ? this.restaurant.instagram : 'https://' + this.restaurant.instagram}" 
                                               target="_blank" 
                                               rel="noopener noreferrer" 
                                               class="hover:text-yellow-200 transition-colors">
                                                <i class="fab fa-instagram text-2xl"></i>
                                            </a>
                                        ` : ''}
                                    </div>
                                ` : ''}
                                ${this.restaurant.wifi_name ? `
                                    <div class="flex items-center justify-center sm:justify-start">
                                        <i class="fas fa-wifi mr-1 flex-shrink-0"></i>
                                        <span class="break-words">WiFi: ${this.restaurant.wifi_name}</span>
                                        ${this.restaurant.wifi_password ? `
                                            <span class="ml-2 text-yellow-200 font-mono">| ${this.restaurant.wifi_password}</span>
                                        ` : ''}
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- First Row: Promotions and Sales -->
            ${(this.comboPromotions.length > 0 || this.saleItems.length > 0 || this.hotItems.length > 0 || this.celebrationMenus.length > 0) ? `
                <div class="bg-white border-b border-gray-200 sticky top-16 z-10">
                    <div class="max-w-7xl mx-auto px-4">
                        <div class="overflow-x-auto">
                            <div class="flex space-x-4 min-w-max py-2">
                                <!-- Combo Promotions Tab -->
                                ${this.comboPromotions.length > 0 ? `
                                    <button onclick="app.switchToComboPromotions()"
                                            class="py-3 px-4 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex-shrink-0 ${
                                                this.selectedCategory && this.selectedCategory.id === 'combo-promotions'
                                                    ? 'border-orange-500 text-orange-500' 
                                                    : 'border-transparent text-gray-500 hover:text-gray-700'
                                            }">
                                        <i class="fas fa-gift mr-2"></i>
                                        <span class="font-bold">${this.getUIText('promotions').toUpperCase()}</span> (${this.comboPromotions.length})
                                    </button>
                                ` : ''}
                                
                                <!-- SALE Tab -->
                                ${this.saleItems.length > 0 ? `
                                    <button onclick="app.switchToSale()"
                                            class="py-3 px-4 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex-shrink-0 ${
                                                this.selectedCategory && this.selectedCategory.id === 'sale'
                                                    ? 'border-red-500 text-red-500' 
                                                    : 'border-transparent text-gray-500 hover:text-gray-700'
                                            }">
                                        <i class="fas fa-fire mr-2"></i>
                                        <span class="font-bold">${this.getUIText('sale').toUpperCase()}</span> (${this.saleItems.length})
                                    </button>
                                ` : ''}
                                
                                <!-- HOT ITEMS Tab -->
                                ${this.hotItems.length > 0 ? `
                                    <button onclick="app.switchToHotItems()"
                                            class="py-3 px-4 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex-shrink-0 ${
                                                this.selectedCategory && this.selectedCategory.id === 'hot-items'
                                                    ? 'border-orange-500 text-orange-500' 
                                                    : 'border-transparent text-gray-500 hover:text-gray-700'
                                            }">
                                        <i class="fas fa-fire mr-2"></i>
                                        <span class="font-bold">${this.getHotItemsLabel().toUpperCase()}</span> (${this.hotItems.length})
                                    </button>
                                ` : ''}
                                
                                <!-- CELEBRATION MENU Tab -->
                                ${this.celebrationMenus.length > 0 ? `
                                    <button onclick="app.switchToCelebrationMenus()"
                                            class="py-3 px-4 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex-shrink-0 ${
                                                this.selectedCategory && this.selectedCategory.id === 'celebration-menus'
                                                    ? 'border-orange-500 text-orange-500' 
                                                    : 'border-transparent text-gray-500 hover:text-gray-700'
                                            }">
                                        <i class="fas fa-glass-cheers mr-2"></i>
                                        <span class="font-bold">${this.getUIText('celebration_menu').toUpperCase()}</span> (${this.celebrationMenus.length})
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            ` : ''}

            <!-- Second Row: Category Types Navigation -->
            ${this.categoryTypes.length > 0 ? `
                <div class="bg-white border-b border-gray-200 sticky ${(this.comboPromotions.length > 0 || this.saleItems.length > 0 || this.hotItems.length > 0 || this.celebrationMenus.length > 0) ? 'top-28' : 'top-16'} z-10">
                    <div class="max-w-7xl mx-auto px-4 py-3">
                        <div class="overflow-x-auto">
                            <div class="flex gap-2 min-w-max">
                                ${this.renderCategoryTypeButtons()}
                            </div>
                        </div>
                    </div>
                </div>
            ` : ''}
            
            <!-- Third Row: Category Navigation (filtered by selected type) -->
            ${this.selectedCategoryType && this.allCategories.length > 0 ? `
                <div class="bg-gray-50 border-b border-gray-200 sticky ${this.calculateCategoryNavTop()} z-10">
                    <div class="max-w-7xl mx-auto px-4 py-3 sm:py-4">
                        <div class="overflow-x-auto">
                            <div class="flex gap-2 min-w-max">
                                ${this.renderFilteredCategoryButtons()}
                            </div>
                        </div>
                    </div>
                </div>
            ` : ''}

            <!-- Menu Items Container -->
            <div id="menu-items-container" class="max-w-7xl mx-auto px-4 py-6 sm:py-8">
                ${this.renderMenuItemsHTML()}
            </div>

            <!-- Footer - Powered by Dinerra -->
            <div class="max-w-7xl mx-auto px-4 py-6 text-center">
                <p class="text-sm text-gray-500">
                    Powered by <a href="https://dinerra.com" target="_blank" rel="noopener noreferrer" class="text-brand-orange hover:text-orange-700 font-medium transition-colors">Dinerra</a>
                </p>
            </div>

            <!-- Cart Sidebar -->
            <div id="cart-sidebar" class="fixed inset-y-0 right-0 w-full sm:w-96 bg-white shadow-xl transform ${this.cartVisible ? 'translate-x-0' : 'translate-x-full'} transition-transform duration-300 ease-in-out z-50">
                <div class="flex flex-col h-full">
                    <div class="flex items-center justify-between p-4 border-b border-gray-200">
                        <h2 class="text-lg font-semibold text-gray-900">
                            <i class="fas fa-shopping-cart mr-2 text-brand-orange"></i>
                            ${this.getUIText('order')}
                        </h2>
                        <button onclick="app.toggleCart()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <div class="flex-1 overflow-y-auto p-4">
                        ${this.renderCartItems()}
                    </div>
                    
                    ${this.cart.length > 0 ? `
                        <div class="border-t border-gray-200 p-4">
                            <div class="flex justify-between items-center mb-4">
                                <span class="text-lg font-semibold">${this.getUIText('total')}:</span>
                                <span class="text-xl font-bold text-brand-orange">${this.getCartTotal()} ${this.getUIText('currency')}</span>
                            </div>
                            <button onclick="app.clearCart()" class="w-full bg-red-600 text-white py-3 rounded-lg font-semibold hover:bg-red-700 transition-colors">
                                <i class="fas fa-trash mr-2"></i>${this.getUIText('clearAll')}
                            </button>
                        </div>
                    ` : ''}
                </div>
            </div>

            <!-- Cart Overlay -->
            ${this.cartVisible ? `
                <div class="fixed inset-0 bg-black bg-opacity-50 z-40 sm:hidden" onclick="app.toggleCart()"></div>
            ` : ''}
        `;
        window.app = this;
    }

    renderCategoryButtons(categories) {

        const categoriesByType = {};
        categories.forEach(category => {
            if (!categoriesByType[category.type]) {
                categoriesByType[category.type] = [];
            }
            categoriesByType[category.type].push(category);
        });
        
        let html = '';
        

        const orderedTypes = this.categoryTypes.sort((a, b) => a.display_order - b.display_order);
        
        orderedTypes.forEach((typeInfo, typeIndex) => {
            const typeName = typeInfo.name;
            const categoriesOfType = categoriesByType[typeName] || [];
            
            if (categoriesOfType.length === 0) return;
            

            if (typeIndex > 0 && html !== '') {
                html += `<div class="h-6 w-px bg-gray-300 flex-shrink-0 mx-1"></div>`;
            }
            

            const sortedCategories = categoriesOfType.sort((a, b) => a.display_order - b.display_order);
            

            sortedCategories.forEach(category => {
                const isSelected = this.selectedCategory && this.selectedCategory.id === category.id;
                html += `
                    <button onclick="app.selectCategory(${JSON.stringify(category).replace(/"/g, '&quot;')})"
                            data-category-id="${category.id}"
                            class="category-btn px-3 py-2 sm:px-4 rounded-full text-xs sm:text-sm font-medium transition-colors whitespace-nowrap flex-shrink-0 ${
                                isSelected
                                    ? 'bg-brand-orange text-white'
                                    : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                            }"
                            title="${category.type}: ${this.getLocalizedText(category, 'name')}">
                        ${this.getLocalizedText(category, 'name')}
                    </button>
                `;
            });
        });
        
        return html;
    }

    calculateCategoryNavTop() {
        let top = 16; // Base header height
        if (this.comboPromotions.length > 0 || this.saleItems.length > 0 || this.hotItems.length > 0 || this.celebrationMenus.length > 0) {
            top += 12; // Add promotion/sales/hot items/celebration row height
        }
        if (this.categoryTypes.length > 0) {
            top += 12; // Add category types row height
        }
        return `top-${top}`;
    }

    renderCategoryTypeButtons() {
        if (this.categoryTypes.length === 0) return '';
        
        const orderedTypes = this.categoryTypes.sort((a, b) => a.display_order - b.display_order);
        
        return orderedTypes.map(type => {
            const categoriesOfType = this.allCategories.filter(cat => cat.type === type.name);
            if (categoriesOfType.length === 0) return '';
            
            const isSelected = this.selectedCategoryType === type.name;
            
            return `
                <button onclick="app.selectCategoryType('${type.name}')"
                        class="px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap flex-shrink-0 ${
                            isSelected
                                ? 'bg-brand-orange text-white'
                                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                        }">
                    ${this.getLocalizedText(type, 'name')} (${categoriesOfType.length})
                </button>
            `;
        }).join('');
    }

    renderFilteredCategoryButtons() {
        if (!this.selectedCategoryType) return '';
        
        const categoriesOfType = this.allCategories
            .filter(cat => cat.type === this.selectedCategoryType)
            .sort((a, b) => a.display_order - b.display_order);
        
        return categoriesOfType.map(category => {
            const isSelected = this.selectedCategory && this.selectedCategory.id === category.id;
            
            return `
                <button onclick="app.selectCategory(${JSON.stringify(category).replace(/"/g, '&quot;')})"
                        data-category-id="${category.id}"
                        class="category-btn px-3 py-2 sm:px-4 rounded-full text-xs sm:text-sm font-medium transition-colors whitespace-nowrap flex-shrink-0 ${
                            isSelected
                                ? 'bg-brand-orange text-white'
                                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                        }">
                    ${this.getLocalizedText(category, 'name')}
                </button>
            `;
        }).join('');
    }

    renderMenuItems() {
        const container = document.getElementById('menu-items-container');
        if (container) {
            container.innerHTML = this.renderMenuItemsHTML();
        }
    }

    renderSaleItems() {
        const container = document.getElementById('menu-items-container');
        if (container) {
            container.innerHTML = this.renderSaleItemsHTML();
        }
    }

    renderSaleItemsHTML() {
        if (this.saleItems.length === 0) {
            return `
                <div class="text-center py-12">
                    <i class="fas fa-fire text-6xl text-red-300 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-600 mb-2">No Sale Items</h3>
                    <p class="text-gray-500">No items are currently on sale.</p>
                </div>
            `;
        }

        return `
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-red-600 mb-2">
                    <i class="fas fa-fire mr-2"></i>
                    Sale Items
                </h2>
                <p class="text-gray-600 mb-6">Special offers and discounted items</p>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
                ${this.saleItems.map(item => this.renderMenuItem(item)).join('')}
            </div>
        `;
    }

    renderHotItems() {
        const container = document.getElementById('menu-items-container');
        if (container) {
            container.innerHTML = this.renderHotItemsHTML();
        }
    }

    renderCelebrationMenus() {
        const container = document.getElementById('menu-items-container');
        if (container) {
            container.innerHTML = this.renderCelebrationMenusHTML();
        }
    }

    renderHotItemsHTML() {
        if (this.hotItems.length === 0) {
            return `
                <div class="text-center py-12">
                    <i class="fas fa-fire-alt text-6xl text-orange-300 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-600 mb-2">No Hot Items</h3>
                    <p class="text-gray-500">No hot items are currently available.</p>
                </div>
            `;
        }

        // Get hot items label from restaurant data
        const hotItemsLabel = this.getLocalizedText(this.restaurant, 'hot_items_label') || this.getUIText('hot_items');
        
        return `
            <div class="mb-8">
                <p class="text-gray-600 mb-6">${hotItemsLabel}</p>
            </div>

            <div class="grid grid-cols-1 gap-6">
                ${this.hotItems.map(item => this.renderHotMenuItem(item)).join('')}
            </div>
        `;
    }

    renderHotMenuItem(item) {
        const name = this.getLocalizedText(item, 'name');
        const description = this.getLocalizedText(item, 'description');
        const allergens = this.getLocalizedText(item, 'allergens');
        
        const finalPrice = item.is_on_sale && item.sale_type === 'sale_price' 
            ? parseFloat(item.sale_value)
            : parseFloat(item.price);

        return `
            <div class="bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow duration-300">
                <div class="flex flex-col md:flex-row">
                    <!-- Large Image Section -->
                    <div class="md:w-2/5 relative">
                        ${item.image_url ? `
                            <img src="${item.image_url}" 
                                 alt="${name}"
                                 class="w-full h-64 md:h-full object-cover"
                                 onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">
                        ` : `
                            <div class="w-full h-64 md:h-full bg-gradient-to-br from-orange-100 to-orange-200 flex items-center justify-center">
                                <i class="fas fa-utensils text-6xl text-orange-400"></i>
                            </div>
                        `}
                        ${item.is_on_sale ? `
                            <div class="absolute top-4 left-4 bg-red-600 text-white px-3 py-1 rounded-full text-sm font-bold shadow-lg">
                                <i class="fas fa-fire mr-1"></i>SALE
                            </div>
                        ` : ''}
                        <div class="absolute top-4 right-4 bg-orange-600 text-white px-3 py-1 rounded-full text-sm font-bold shadow-lg">
                            <i class="fas fa-fire-alt mr-1"></i>HOT
                        </div>
                    </div>
                    
                    <!-- Details Section -->
                    <div class="md:w-3/5 p-6 flex flex-col justify-between">
                        <div>
                            <h3 class="text-2xl font-bold mb-3" style="color: var(--text-color);">${name}</h3>
                            
                            ${description ? `
                                <p class="text-gray-700 text-lg leading-relaxed">${description}</p>
                            ` : ''}
                            
                            ${item.size_info ? `
                                <div class="flex items-center text-sm text-gray-500 mt-4">
                                    <i class="fas fa-ruler mr-2"></i>
                                    <span>${this.getUIText('size')}: ${item.size_info}</span>
                                </div>
                            ` : ''}
                            
                            ${allergens ? `
                                <div class="flex items-start text-sm text-gray-500 mt-4">
                                    <i class="fas fa-exclamation-triangle mr-2 mt-1"></i>
                                    <div>
                                        <span class="font-medium">${this.getUIText('allergens')}:</span>
                                        <span class="ml-1">${allergens}</span>
                                    </div>
                                </div>
                            ` : ''}
                        </div>
                        
                        <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-200">
                            <div class="text-2xl md:text-3xl font-bold text-orange-600">
                                ${finalPrice.toFixed(0)} ${this.getUIText('currency')}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    renderCelebrationMenusHTML() {
        if (this.celebrationMenus.length === 0) {
            return `
                <div class="text-center py-12">
                    <i class="fas fa-glass-cheers text-6xl mb-4" style="color: var(--accent-color); opacity: 0.3;"></i>
                    <h3 class="text-xl font-bold text-gray-600 mb-2">No Celebration Menus</h3>
                    <p class="text-gray-500">No celebration menus are currently available.</p>
                </div>
            `;
        }

        return `
            <div class="grid grid-cols-1 gap-6">
                ${this.celebrationMenus.map(menu => this.renderCelebrationMenuItem(menu)).join('')}
            </div>
        `;
    }

    renderCelebrationMenuItem(menu) {
        const name = this.getLocalizedText(menu, 'name');
        const description = this.getLocalizedText(menu, 'description');
        const pricePerPerson = parseFloat(menu.price_per_person || menu.price || 0);
        const minPeople = menu.min_people || 1;

        return `
            <div class="rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition-shadow duration-300" style="background: linear-gradient(to bottom right, color-mix(in srgb, var(--accent-color) 10%, white), color-mix(in srgb, var(--accent-color) 5%, white)); border: 2px solid color-mix(in srgb, var(--accent-color) 30%, white);">
                <!-- Details Section -->
                <div class="p-6 flex flex-col justify-between">
                    <div>
                        <h3 class="text-2xl font-bold mb-3" style="color: var(--text-color);">${name}</h3>
                            
                            ${description ? `
                                <p class="text-gray-700 mb-4 leading-relaxed">${description}</p>
                            ` : ''}
                            
                            ${menu.sections && menu.sections.length > 0 ? `
                                <div class="bg-white bg-opacity-80 rounded-lg p-4 mb-4" style="border: 1px solid color-mix(in srgb, var(--accent-color) 20%, white);">
                                    <h4 class="font-semibold text-gray-800 mb-3 flex items-center">
                                        <i class="fas fa-utensils mr-2" style="color: var(--accent-color);"></i>
                                        ${this.getUIText('includes')}:
                                    </h4>
                                    <div class="space-y-3">
                                        ${menu.sections.map(section => `
                                            <div class="border-l-2 pl-3" style="border-color: var(--accent-color);">
                                                <div class="font-medium text-gray-800 mb-1">${this.getLocalizedText(section, 'title')}</div>
                                                ${section.description || section.description_mk || section.description_en ? `
                                                    <div class="text-sm text-gray-600">${this.getLocalizedText(section, 'description')}</div>
                                                ` : ''}
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            ` : ''}
                            
                            ${menu.disclaimer ? `
                                <div class="bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200">
                                    <p class="text-sm text-gray-700 italic"><span class="font-bold text-amber-700">* </span>${menu.disclaimer}</p>
                                </div>
                            ` : ''}
                        </div>
                        
                    <div class="flex items-center justify-between mt-4 pt-4 gap-3" style="border-top: 1px solid color-mix(in srgb, var(--accent-color) 30%, white);">
                        <div>
                            <div class="text-xs sm:text-sm text-gray-600 mb-1">${this.getUIText('pricePerPerson')}</div>
                            <div class="text-xl sm:text-2xl md:text-3xl font-bold" style="color: var(--accent-color);">${pricePerPerson.toFixed(0)} ${this.getUIText('currency')}</div>
                        </div>
                        <button onclick="app.showCelebrationMenuContact(${JSON.stringify(menu).replace(/"/g, '&quot;')})"
                                class="text-white px-4 sm:px-6 md:px-8 py-2 sm:py-2.5 md:py-3 rounded-lg text-sm sm:text-base font-semibold shadow-md hover:shadow-lg transition-all duration-200 flex items-center space-x-1 sm:space-x-2" style="background-color: var(--theme-button);" onmouseover="this.style.opacity='0.9'" onmouseout="this.style.opacity='1'">
                            <i class="fas fa-phone text-sm sm:text-base"></i>
                            <span class="hidden sm:inline">${this.currentLanguage === 'mk' ? 'Контактирајте' : this.currentLanguage === 'al' ? 'Na kontaktoni' : 'Contact Us'}</span>
                            <span class="inline sm:hidden">${this.currentLanguage === 'mk' ? 'Контакт' : this.currentLanguage === 'al' ? 'Kontakt' : 'Contact'}</span>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    showCelebrationMenuContact(menu) {
        const name = this.getLocalizedText(menu, 'name');
        const pricePerPerson = parseFloat(menu.price_per_person || menu.price || 0);
        const minPeople = menu.min_people || 1;

        const modalHtml = `
            <div id="celebration-contact-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" onclick="app.closeCelebrationContactModal(event)">
                <div class="bg-white rounded-lg shadow-xl max-w-md w-full" onclick="event.stopPropagation()">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-4">
                            <h2 class="text-2xl font-bold" style="color: var(--accent-color);">${name}</h2>
                            <button onclick="app.closeCelebrationContactModal(event)" class="text-gray-400 hover:text-gray-600">
                                <i class="fas fa-times text-xl"></i>
                            </button>
                        </div>
                        
                        <div class="mb-6">
                            <div class="rounded-lg p-4 mb-4" style="background-color: color-mix(in srgb, var(--accent-color) 10%, white);">
                                <div class="flex items-center justify-between mb-2">
                                    <span class="text-gray-700">${this.getUIText('pricePerPerson')}:</span>
                                    <span class="text-xl font-bold" style="color: var(--accent-color);">${pricePerPerson.toFixed(0)} ${this.getUIText('currency')}</span>
                                </div>
                                ${minPeople > 1 ? `
                                    <div class="flex items-center text-sm text-gray-600">
                                        <i class="fas fa-users mr-2"></i>
                                        <span>${this.currentLanguage === 'mk' ? 'Минимум' : 'Minimum'} ${minPeople} ${this.currentLanguage === 'mk' ? 'луѓе' : 'people'}</span>
                                    </div>
                                ` : ''}
                            </div>
                            
                            ${menu.sections && menu.sections.length > 0 ? `
                                <div class="bg-white rounded-lg p-4 mb-4" style="border: 1px solid color-mix(in srgb, var(--accent-color) 20%, white);">
                                    <h4 class="font-semibold text-gray-800 mb-2 flex items-center">
                                        <i class="fas fa-utensils mr-2" style="color: var(--accent-color);"></i>
                                        ${this.getUIText('includes')}:
                                    </h4>
                                    <div class="space-y-2 max-h-40 overflow-y-auto">
                                        ${menu.sections.map(section => `
                                            <div class="border-l-2 pl-3" style="border-color: var(--accent-color);">
                                                <div class="font-medium text-gray-800 text-sm">${this.getLocalizedText(section, 'title')}</div>
                                                ${section.description || section.description_mk || section.description_en ? `
                                                    <div class="text-xs text-gray-600">${this.getLocalizedText(section, 'description')}</div>
                                                ` : ''}
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            ` : ''}
                            
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex items-start">
                                    <i class="fas fa-info-circle text-yellow-600 mt-0.5 mr-2"></i>
                                    <div class="text-sm">
                                        <p class="font-medium text-yellow-800 mb-1">
                                            ${this.currentLanguage === 'mk' ? 'Информација' : 'Information'}
                                        </p>
                                        <p class="text-yellow-700">
                                            ${this.currentLanguage === 'mk' 
                                                ? 'Ве молиме контактирајте го ресторанот за да нарачате меню за прослава. Потребна е резервација однапред.'
                                                : 'Please contact the restaurant to order a celebration menu. Advance reservation is required.'}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="space-y-3">
                            ${this.restaurant.phone ? `
                                <a href="tel:${this.restaurant.phone}" 
                                   class="block w-full text-white py-3 rounded-lg font-semibold transition-all text-center" style="background-color: var(--theme-button);" onmouseover="this.style.opacity='0.9'" onmouseout="this.style.opacity='1'">
                                    <i class="fas fa-phone mr-2"></i>${this.restaurant.phone}
                                </a>
                            ` : ''}
                            ${(menu.show_website !== false && this.restaurant.website) ? `
                                <a href="${this.restaurant.website.startsWith('http') ? this.restaurant.website : 'https://' + this.restaurant.website}" 
                                   target="_blank" 
                                   rel="noopener noreferrer"
                                   class="block w-full bg-gray-200 text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-300 transition-colors text-center">
                                    <i class="fas fa-globe mr-2"></i>${this.currentLanguage === 'mk' ? 'Посети вебсајт' : 'Visit Website'}
                                </a>
                            ` : ''}
                            ${this.restaurant.facebook && this.restaurant.instagram ? `
                                <div class="grid grid-cols-2 gap-3">
                                    <a href="${this.restaurant.facebook.startsWith('http') ? this.restaurant.facebook : 'https://' + this.restaurant.facebook}" 
                                       target="_blank" 
                                       rel="noopener noreferrer"
                                       class="block w-full bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors text-center flex items-center justify-center">
                                        <i class="fab fa-facebook text-2xl"></i>
                                    </a>
                                    <a href="${this.restaurant.instagram.startsWith('http') ? this.restaurant.instagram : 'https://' + this.restaurant.instagram}" 
                                       target="_blank" 
                                       rel="noopener noreferrer"
                                       class="block w-full bg-gradient-to-r from-purple-600 to-pink-600 text-white py-3 rounded-lg font-semibold hover:from-purple-700 hover:to-pink-700 transition-colors text-center flex items-center justify-center">
                                        <i class="fab fa-instagram text-2xl"></i>
                                    </a>
                                </div>
                            ` : ''}
                            ${this.restaurant.facebook && !this.restaurant.instagram ? `
                                <a href="${this.restaurant.facebook.startsWith('http') ? this.restaurant.facebook : 'https://' + this.restaurant.facebook}" 
                                   target="_blank" 
                                   rel="noopener noreferrer"
                                   class="block w-full bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors text-center flex items-center justify-center">
                                    <i class="fab fa-facebook text-2xl"></i>
                                </a>
                            ` : ''}
                            ${!this.restaurant.facebook && this.restaurant.instagram ? `
                                <a href="${this.restaurant.instagram.startsWith('http') ? this.restaurant.instagram : 'https://' + this.restaurant.instagram}" 
                                   target="_blank" 
                                   rel="noopener noreferrer"
                                   class="block w-full bg-gradient-to-r from-purple-600 to-pink-600 text-white py-3 rounded-lg font-semibold hover:from-purple-700 hover:to-pink-700 transition-colors text-center flex items-center justify-center">
                                    <i class="fab fa-instagram text-2xl"></i>
                                </a>
                            ` : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = modalHtml;
        document.body.appendChild(modalContainer.firstElementChild);
        
        document.body.style.overflow = 'hidden';
    }
    
    closeCelebrationContactModal(event) {
        const modal = document.getElementById('celebration-contact-modal');
        if (modal) {
            modal.remove();
            document.body.style.overflow = '';
        }
    }

    renderComboPromotions() {
        const container = document.getElementById('menu-items-container');
        if (container) {
            container.innerHTML = this.renderComboPromotionsHTML();

        }
    }

    renderComboPromotionsHTML() {
        if (this.comboPromotions.length === 0) {
            return `
                <div class="text-center py-12">
                    <i class="fas fa-gift text-6xl text-orange-300 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-600 mb-2">No Promotions</h3>
                    <p class="text-gray-500">No promotions are currently available.</p>
                </div>
            `;
        }

        return `
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-orange-600 mb-2">
                    <i class="fas fa-gift mr-2"></i>
                    Promotions
                </h2>
                <p class="text-gray-600 mb-6">Special combo deals - save more when you buy together!</p>
            </div>

            <!-- Promotions displayed as menu items (same style as regular menu items) -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
                ${this.comboPromotions.map(promotion => this.renderPromotionAsMenuItem(promotion)).join('')}
            </div>
        `;
    }

    renderComboPromotion(promotion) {

        const originalTotalPrice = promotion.menu_items && promotion.menu_items.length > 0
            ? promotion.menu_items.reduce((total, item) => total + parseFloat(item.price), 0)
            : 0;
        
        return `
            <div class="bg-gradient-to-br from-orange-50 via-orange-25 to-yellow-50 border-2 border-orange-300 rounded-2xl p-6 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                <!-- Decorative corner accent -->
                <div class="absolute top-0 right-0 w-20 h-20 bg-gradient-to-bl from-orange-200 to-transparent opacity-50 rounded-bl-2xl"></div>
                
                <div class="flex items-start justify-between mb-5 relative z-10">
                    <div class="flex-1">
                        <div class="flex items-center mb-3">
                            <div class="bg-orange-600 text-white p-2 rounded-full mr-3">
                                <i class="fas fa-percentage text-lg"></i>
                            </div>
                            <div>
                                <h3 class="text-xl font-bold text-orange-900 leading-tight">
                                    ${promotion.name}
                                </h3>
                                <div class="flex items-center text-xs text-orange-600 mt-1">
                                    <i class="fas fa-star mr-1"></i>
                                    <span class="font-semibold">SPECIAL OFFER</span>
                                </div>
                            </div>
                        </div>
                        ${promotion.description ? `
                            <p class="text-gray-700 text-sm leading-relaxed">${promotion.description}</p>
                        ` : ''}
                    </div>
                    <div class="text-right ml-4">
                        ${originalTotalPrice > parseFloat(promotion.price) ? `
                            <div class="bg-red-100 text-red-600 px-2 py-1 rounded-full text-xs font-bold mb-2">
                                SAVE ${(originalTotalPrice - parseFloat(promotion.price)).toFixed(0)} ${this.getUIText('currency')}
                            </div>
                            <div class="text-sm text-gray-500 line-through">${originalTotalPrice.toFixed(0)} ${this.getUIText('currency')}</div>
                            <div class="text-2xl font-bold text-orange-600">${parseFloat(promotion.price).toFixed(0)} ${this.getUIText('currency')}</div>
                        ` : `
                            <div class="bg-orange-100 text-orange-600 px-2 py-1 rounded-full text-xs font-bold mb-2">
                                PROMO PRICE
                            </div>
                            <div class="text-2xl font-bold text-orange-600">${parseFloat(promotion.price).toFixed(0)} ${this.getUIText('currency')}</div>
                        `}
                    </div>
                </div>
                
                ${promotion.menu_items && promotion.menu_items.length > 0 ? `
                    <div class="bg-white bg-opacity-80 backdrop-blur-sm rounded-xl p-4 mb-5 border border-orange-100">
                        <h4 class="font-semibold text-gray-800 mb-2 flex items-center">
                            <i class="fas fa-utensils text-orange-600 mr-2"></i>
                            What's Included:
                        </h4>
                        <div class="space-y-1">
                            ${promotion.menu_items.map(item => `
                                <div class="flex justify-between items-center text-sm">
                                    <span class="text-gray-700">${item.quantity > 1 ? `${item.quantity}x ` : ''}${this.getLocalizedText(item, 'name')}</span>
                                    <span class="text-gray-500">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}
                
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-3">
                        <div class="flex items-center text-sm text-green-600 bg-green-50 px-3 py-1 rounded-full">
                            <i class="fas fa-check-circle mr-1"></i>
                            <span class="font-medium">Best Value</span>
                        </div>
                    </div>
                    <div class="flex items-center space-x-2">
                        ${this.getPromotionQuantityInCart(promotion.id) > 0 ? `
                            <button onclick="app.removePromotionFromCart('${promotion.id}')" 
                                    class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors">
                                <i class="fas fa-minus text-sm"></i>
                            </button>
                            <span class="min-w-8 text-center font-semibold text-lg">${this.getPromotionQuantityInCart(promotion.id)}</span>
                        ` : ''}
                        <button onclick="app.addPromotionToCart(${promotion.id})" 
                                class="w-10 h-10 rounded-full bg-orange-600 text-white flex items-center justify-center hover:bg-orange-700 transition-colors shadow-lg">
                            <i class="fas fa-plus text-sm"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    renderComboPromotionMobile(promotion, index) {

        const originalTotalPrice = promotion.menu_items && promotion.menu_items.length > 0
            ? promotion.menu_items.reduce((total, item) => total + parseFloat(item.price), 0)
            : 0;
            
        return `
            <div class="bg-gradient-to-br from-orange-50 via-orange-25 to-yellow-50 border-2 border-orange-300 rounded-lg p-3 mx-2 shadow-lg flex-shrink-0 carousel-item relative overflow-hidden" data-index="${index}" style="width: calc(100vw - 2rem); min-width: calc(100vw - 2rem); height: 180px;">
                <!-- Decorative corner accent -->
                <div class="absolute top-0 right-0 w-8 h-8 bg-gradient-to-bl from-orange-200 to-transparent opacity-50 rounded-bl-lg"></div>
                
                <div class="flex h-full flex-col relative z-10">
                    <!-- Header Section -->
                    <div class="flex items-start justify-between mb-1">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center">
                                <div class="bg-orange-600 text-white p-1 rounded-full mr-2 flex-shrink-0">
                                    <i class="fas fa-percentage text-xs"></i>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <h3 class="text-sm font-bold text-orange-900 leading-tight truncate">
                                        ${promotion.name}
                                    </h3>
                                    <div class="flex items-center text-xs text-orange-600">
                                        <i class="fas fa-star mr-1"></i>
                                        <span class="font-medium">OFFER</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="text-right ml-2 flex-shrink-0">
                            ${originalTotalPrice > parseFloat(promotion.price) ? `
                                <div class="bg-red-100 text-red-600 px-1 py-0.5 rounded text-xs font-bold mb-0.5">
                                    SAVE ${(originalTotalPrice - parseFloat(promotion.price)).toFixed(0)} ${this.getUIText('currency')}
                                </div>
                                <div class="text-xs text-gray-500 line-through">${originalTotalPrice.toFixed(0)} ${this.getUIText('currency')}</div>
                                <div class="text-base font-bold text-orange-600">${parseFloat(promotion.price).toFixed(0)} ${this.getUIText('currency')}</div>
                            ` : `
                                <div class="bg-orange-100 text-orange-600 px-1 py-0.5 rounded text-xs font-bold mb-0.5">
                                    PROMO
                                </div>
                                <div class="text-base font-bold text-orange-600">${parseFloat(promotion.price).toFixed(0)} ${this.getUIText('currency')}</div>
                            `}
                        </div>
                    </div>
                    
                    <!-- Description Section (Compact) -->
                    ${promotion.description ? `
                        <div class="mb-1">
                            <p class="text-gray-600 text-xs leading-tight line-clamp-1">${promotion.description}</p>
                        </div>
                    ` : ''}
                    
                    <!-- Items Section (More Compact) -->
                    ${promotion.menu_items && promotion.menu_items.length > 0 ? `
                        <div class="bg-white bg-opacity-60 rounded p-1.5 mb-2 flex-1 min-h-0">
                            <h4 class="font-medium text-gray-800 text-xs flex items-center mb-0.5">
                                <i class="fas fa-utensils text-orange-600 mr-1 text-xs"></i>
                                Includes:
                            </h4>
                            <div class="space-y-0.5 text-xs leading-tight overflow-hidden max-h-8">
                                ${promotion.menu_items.slice(0, 3).map(item => `
                                    <div class="text-gray-700 truncate">${item.quantity > 1 ? `${item.quantity}x ` : ''}${this.getLocalizedText(item, 'name')}</div>
                                `).join('')}
                                ${promotion.menu_items.length > 3 ? `
                                    <div class="text-gray-500">+${promotion.menu_items.length - 3} more...</div>
                                ` : ''}
                            </div>
                        </div>
                    ` : ''}
                    
                    <!-- Bottom Action -->
                    <div class="flex items-center justify-between mt-auto">
                        <div class="flex items-center text-xs text-green-600 bg-green-50 px-1.5 py-0.5 rounded-full">
                            <i class="fas fa-check-circle mr-1"></i>
                            <span class="font-medium">Best Value</span>
                        </div>
                        <div class="flex items-center space-x-1">
                            ${this.getPromotionQuantityInCart(promotion.id) > 0 ? `
                                <button onclick="app.removePromotionFromCart('${promotion.id}')" 
                                        class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors">
                                    <i class="fas fa-minus text-xs"></i>
                                </button>
                                <span class="min-w-6 text-center font-semibold text-xs">${this.getPromotionQuantityInCart(promotion.id)}</span>
                            ` : ''}
                            <button onclick="app.addPromotionToCart(${promotion.id})" 
                                    class="w-6 h-6 rounded-full bg-orange-600 text-white flex items-center justify-center hover:bg-orange-700 transition-colors">
                                <i class="fas fa-plus text-xs"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    renderMenuItemsHTML() {
        if (this.selectedCategory && this.selectedCategory.id === 'sale') {
            return this.renderSaleItemsHTML();
        }

        if (this.selectedCategory && this.selectedCategory.id === 'combo-promotions') {
            return this.renderComboPromotionsHTML();
        }

        if (this.selectedCategory && this.selectedCategory.id === 'hot-items') {
            return this.renderHotItemsHTML();
        }

        if (this.selectedCategory && this.selectedCategory.id === 'celebration-menus') {
            return this.renderCelebrationMenusHTML();
        }

        if (!this.selectedCategory) {
            return `
                <div class="text-center py-12">
                    <i class="fas fa-utensils text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-600 mb-2">No Categories Available</h3>
                    <p class="text-gray-500">This restaurant hasn't added any menu categories yet.</p>
                </div>
            `;
        }

        const items = this.menuItems[this.selectedCategory.id] || [];

        if (items.length === 0) {
            return `
                <div class="text-center py-12">
                    <i class="fas fa-utensils text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-600 mb-2">${this.getLocalizedText(this.selectedCategory, 'name')}</h3>
                    <p class="text-gray-500">No items available in this category.</p>
                </div>
            `;
        }

        const layout = this.selectedCategory.layout || 'grid';
        
        return `
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-gray-900 mb-2">${this.getLocalizedText(this.selectedCategory, 'name')}</h2>
                ${this.getLocalizedText(this.selectedCategory, 'description') ? `
                    <p class="text-gray-600 mb-6">${this.getLocalizedText(this.selectedCategory, 'description')}</p>
                ` : ''}
            </div>

            <div class="${layout === 'horizontal' ? 'flex flex-col gap-4' : 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6'}">
                ${items.map(item => this.renderMenuItem(item, layout)).join('')}
            </div>
        `;
    }
    calculateSalePrice(item) {
        if (!item.is_on_sale || !item.sale_type || !item.sale_value) {
            return {
                hasValidSale: false,
                originalPrice: parseFloat(item.price),
                salePrice: parseFloat(item.price),
                savings: 0
            };
        }

        const originalPrice = parseFloat(item.original_price || item.price);
        let salePrice = parseFloat(item.price);

        switch (item.sale_type) {
            case 'percentage':

                salePrice = originalPrice - (originalPrice * parseFloat(item.sale_value) / 100);
                break;
            case 'fixed_discount':

                salePrice = originalPrice - parseFloat(item.sale_value);
                break;
            case 'sale_price':

                salePrice = parseFloat(item.sale_value);
                break;
            default:
                return {
                    hasValidSale: false,
                    originalPrice: originalPrice,
                    salePrice: originalPrice,
                    savings: 0
                };
        }
        salePrice = Math.max(0, salePrice);
        const savings = originalPrice - salePrice;

        return {
            hasValidSale: true,
            originalPrice: originalPrice,
            salePrice: salePrice,
            savings: savings,
            saleType: item.sale_type,
            saleValue: parseFloat(item.sale_value)
        };
    }

    renderMenuItem(item, layout = 'grid') {
        const cartItem = this.cart.find(cartItem => cartItem.id === item.id);
        const quantity = cartItem ? cartItem.quantity : 0;
        

        const saleInfo = this.calculateSalePrice(item);
        
        // Generate unique ID for this item's image
        const imageId = `menu-img-${item.id}`;
        
        // Horizontal layout - mobile optimized with thumbnail on left
        if (layout === 'horizontal') {
            return `
                <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow overflow-hidden menu-item-card horizontal-item" data-item-id="${item.id}">
                    <div class="flex items-center gap-3 p-3">
                        ${item.image_url ? `
                            <div class="relative overflow-hidden menu-item-thumbnail flex-shrink-0 cursor-pointer" onclick="app.showItemModal(${JSON.stringify(item).replace(/"/g, '&quot;')})">
                                <img id="${imageId}" 
                                     src="${item.image_url}" 
                                     alt="${this.getLocalizedText(item, 'name')}"
                                     class="w-20 h-20 object-cover rounded-lg"
                                     style="display: none;"
                                     onload="app.handleImageLoad('${imageId}', ${item.id})"
                                     onerror="this.src='https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=400&h=300&fit=crop'; this.onerror=null; app.handleImageLoad('${imageId}', ${item.id});">
                                <div class="absolute inset-0 flex items-center justify-center bg-gray-100 rounded-lg">
                                    <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-brand-orange"></div>
                                </div>
                                ${saleInfo.hasValidSale ? `
                                    <div class="absolute top-0 left-0 z-10">
                                        ${saleInfo.saleType === 'percentage' ? `
                                            <span class="bg-red-500 text-white px-1 py-0.5 rounded-br-lg text-xs font-bold">-${saleInfo.saleValue}%</span>
                                        ` : saleInfo.saleType === 'fixed_discount' ? `
                                            <span class="bg-red-500 text-white px-1 py-0.5 rounded-br-lg text-xs font-bold">-${saleInfo.saleValue}</span>
                                        ` : `
                                            <span class="bg-red-500 text-white px-1 py-0.5 rounded-br-lg text-xs font-bold">SALE</span>
                                        `}
                                    </div>
                                ` : ''}
                            </div>
                        ` : `
                            <div class="w-20 h-20 bg-gray-200 rounded-lg flex items-center justify-center flex-shrink-0 cursor-pointer" onclick="app.showItemModal(${JSON.stringify(item).replace(/"/g, '&quot;')})">
                                <i class="fas fa-utensils text-gray-400 text-2xl"></i>
                            </div>
                        `}
                        
                        <div class="flex-1 min-w-0 flex flex-col justify-between cursor-pointer" onclick="app.showItemModal(${JSON.stringify(item).replace(/"/g, '&quot;')})">
                            <div>
                                <h3 class="text-base font-bold text-gray-900 mb-1 line-clamp-2">${this.getLocalizedText(item, 'name')}</h3>
                            </div>
                            <div class="whitespace-nowrap price-container">
                                ${saleInfo.hasValidSale ? `
                                    <div class="flex items-center gap-2">
                                        <span class="text-xs text-gray-500 line-through">${saleInfo.originalPrice.toFixed(0)}</span>
                                        <span class="text-lg font-bold text-red-600">${saleInfo.salePrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                    </div>
                                ` : `
                                    <span class="text-lg font-bold text-brand-orange">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</span>
                                `}
                            </div>
                        </div>
                        
                        <div class="flex items-center justify-end ml-2 flex-shrink-0">
                            <div class="flex items-center space-x-2">
                                ${quantity > 0 ? `
                                    <button onclick="event.stopPropagation(); app.removeFromCart(${item.id})" 
                                            class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors relative z-40">
                                        <i class="fas fa-minus text-xs"></i>
                                    </button>
                                    <span class="min-w-6 text-center font-semibold text-sm">${quantity}</span>
                                ` : ''}
                                <button onclick="event.stopPropagation(); app.addToCart(${JSON.stringify(item).replace(/"/g, '&quot;')})" 
                                        class="w-8 h-8 rounded-full bg-brand-orange text-white flex items-center justify-center hover:bg-brand-red transition-colors relative z-40">
                                    <i class="fas fa-plus text-xs"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // Default grid layout - image on top, text below
        return `
            <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow overflow-hidden menu-item-card" data-item-id="${item.id}">
                ${item.image_url ? `
                    <div class="relative overflow-hidden menu-item-image-container" style="min-height: 200px;">
                        <img id="${imageId}" 
                             src="${item.image_url}" 
                             alt="${this.getLocalizedText(item, 'name')}"
                             class="w-full h-full object-cover"
                             style="display: none;"
                             onload="app.handleImageLoad('${imageId}', ${item.id})"
                             onerror="this.src='https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=400&h=300&fit=crop'; this.onerror=null; app.handleImageLoad('${imageId}', ${item.id});">
                        <div class="absolute inset-0 flex items-center justify-center bg-gray-100">
                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-orange"></div>
                        </div>
                        ${saleInfo.hasValidSale ? `
                            <div class="absolute top-2 right-2 z-10">
                                ${saleInfo.saleType === 'percentage' ? `
                                    <span class="bg-red-500 text-white px-2 py-1 rounded-full text-xs font-bold">-${saleInfo.saleValue}%</span>
                                ` : saleInfo.saleType === 'fixed_discount' ? `
                                    <span class="bg-red-500 text-white px-2 py-1 rounded-full text-xs font-bold">-${saleInfo.saleValue} ${this.getUIText('currency')}</span>
                                ` : `
                                    <span class="bg-red-500 text-white px-2 py-1 rounded-full text-xs font-bold">SALE</span>
                                `}
                            </div>
                        ` : ''}
                    </div>
                ` : ''}
                <div class="p-4 sm:p-6">
                    <div class="flex justify-between items-start mb-2 sm:mb-3">
                        <h3 class="text-base sm:text-lg font-bold text-gray-900 flex-1 pr-2">${this.getLocalizedText(item, 'name')}</h3>
                        <div class="text-right whitespace-nowrap price-container">
                            ${saleInfo.hasValidSale ? `
                                <div class="flex flex-col items-end space-y-1">
                                    <span class="text-sm text-gray-500 line-through">${saleInfo.originalPrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                    <span class="text-lg sm:text-xl font-bold text-red-600">${saleInfo.salePrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                </div>
                            ` : `
                                <span class="text-lg sm:text-xl font-bold text-brand-orange">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</span>
                            `}
                        </div>
                    </div>
                    
                    ${this.getLocalizedText(item, 'description') ? `
                        <p class="text-gray-600 text-xs sm:text-sm mb-3">${this.getLocalizedText(item, 'description')}</p>
                    ` : ''}
                    
                    ${item.size_info || item.allergens ? `
                        <div class="text-xs text-gray-500 mb-3 space-y-1">
                            ${item.size_info ? `
                                <div><i class="fas fa-ruler text-indigo-500 mr-1"></i>${this.getUIText('size')}: ${item.size_info}</div>
                            ` : ''}
                            ${this.getLocalizedText(item, 'allergens') ? `
                                <div><i class="fas fa-exclamation-triangle text-orange-500 mr-1"></i>${this.getUIText('allergens')}: ${this.getLocalizedText(item, 'allergens')}</div>
                            ` : ''}
                        </div>
                    ` : ''}
                    
                    <div class="flex items-center justify-end">
                        <div class="flex items-center space-x-2">
                            ${quantity > 0 ? `
                                <button onclick="app.removeFromCart(${item.id})" 
                                        class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors relative z-40">
                                    <i class="fas fa-minus text-xs"></i>
                                </button>
                                <span class="min-w-8 text-center font-semibold">${quantity}</span>
                            ` : ''}
                            <button onclick="app.addToCart(${JSON.stringify(item).replace(/"/g, '&quot;')})" 
                                    class="w-8 h-8 rounded-full bg-brand-orange text-white flex items-center justify-center hover:bg-brand-red transition-colors relative z-40">
                                <i class="fas fa-plus text-xs"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    handleImageLoad(imageId, itemId) {
        const img = document.getElementById(imageId);
        if (!img) return;
        
        const container = img.closest('.menu-item-image-container, .menu-item-thumbnail');
        if (!container) return;
        
        // Show the image
        img.style.display = 'block';
        
        // Remove loading spinner
        const spinner = container.querySelector('.absolute.inset-0');
        if (spinner && spinner.querySelector('.animate-spin')) {
            spinner.remove();
        }
        
        // Only apply advanced layout for grid items, not thumbnails
        if (container.classList.contains('menu-item-image-container')) {
            // Detect image orientation
            const isVertical = img.naturalHeight > img.naturalWidth;
            const aspectRatio = img.naturalHeight / img.naturalWidth;
            
            // Apply appropriate layout based on orientation
            if (isVertical && aspectRatio > 1.3) {
                // Vertical image (like bottles) - use taller container
                container.style.height = 'auto';
                container.style.maxHeight = '400px';
                img.style.objectFit = 'contain';
                img.style.backgroundColor = '#f9fafb'; // Light gray background
                
                // Add visual indicator for vertical layout
                const card = container.closest('.menu-item-card');
                if (card) {
                    card.classList.add('vertical-photo-layout');
                }
            } else {
                // Horizontal or square image - use standard layout
                container.style.height = '200px';
                img.style.objectFit = 'cover';
            }
        }
    }

    showItemModal(item) {
        // Detect image orientation
        const isPortrait = item.image_url && item.image_url !== '' ? null : false; // Will be detected on image load
        
        const saleInfo = this.calculateSalePrice(item);
        
        const modalHtml = `
            <div id="item-detail-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" onclick="app.closeItemModal(event)">
                <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto" onclick="event.stopPropagation()">
                    ${item.image_url ? `
                        <div class="relative">
                            <img id="modal-image" 
                                 src="${item.image_url}" 
                                 alt="${this.getLocalizedText(item, 'name')}"
                                 class="w-full max-h-96 object-contain bg-gray-100"
                                 onload="app.handleModalImageLoad()">
                            ${saleInfo.hasValidSale ? `
                                <div class="absolute top-4 right-4 z-10">
                                    ${saleInfo.saleType === 'percentage' ? `
                                        <span class="bg-red-500 text-white px-3 py-2 rounded-full text-sm font-bold shadow-lg">-${saleInfo.saleValue}%</span>
                                    ` : saleInfo.saleType === 'fixed_discount' ? `
                                        <span class="bg-red-500 text-white px-3 py-2 rounded-full text-sm font-bold shadow-lg">-${saleInfo.saleValue} ${this.getUIText('currency')}</span>
                                    ` : `
                                        <span class="bg-red-500 text-white px-3 py-2 rounded-full text-sm font-bold shadow-lg">SALE</span>
                                    `}
                                </div>
                            ` : ''}
                            <button onclick="app.closeItemModal(event)" 
                                    class="absolute top-4 left-4 bg-white bg-opacity-90 hover:bg-opacity-100 text-gray-800 rounded-full w-10 h-10 flex items-center justify-center shadow-lg transition-all">
                                <i class="fas fa-times text-xl"></i>
                            </button>
                        </div>
                    ` : ''}
                    
                    <div class="p-6">
                        <div class="flex justify-between items-start mb-4">
                            <h2 class="text-2xl font-bold text-gray-900 flex-1 pr-4">${this.getLocalizedText(item, 'name')}</h2>
                            <div class="text-right">
                                ${saleInfo.hasValidSale ? `
                                    <div class="flex flex-col items-end space-y-1">
                                        <span class="text-lg text-gray-500 line-through">${saleInfo.originalPrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                        <span class="text-3xl font-bold text-red-600">${saleInfo.salePrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                        <span class="text-sm bg-red-100 text-red-600 px-2 py-1 rounded-full font-medium">
                                            ${this.getUIText('save')} ${(saleInfo.originalPrice - saleInfo.salePrice).toFixed(0)} ${this.getUIText('currency')}
                                        </span>
                                    </div>
                                ` : `
                                    <span class="text-3xl font-bold text-brand-orange">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</span>
                                `}
                            </div>
                        </div>
                        
                        ${this.getLocalizedText(item, 'description') ? `
                            <p class="text-gray-600 text-base mb-4 leading-relaxed">${this.getLocalizedText(item, 'description')}</p>
                        ` : ''}
                        
                        ${item.size_info || item.allergens ? `
                            <div class="bg-gray-50 rounded-lg p-4 mb-4 space-y-2">
                                ${item.size_info ? `
                                    <div class="flex items-center text-sm text-gray-700">
                                        <i class="fas fa-ruler text-indigo-500 mr-2 w-5"></i>
                                        <span class="font-medium mr-2">${this.getUIText('size')}:</span>
                                        <span>${item.size_info}</span>
                                    </div>
                                ` : ''}
                                ${this.getLocalizedText(item, 'allergens') ? `
                                    <div class="flex items-start text-sm text-gray-700">
                                        <i class="fas fa-exclamation-triangle text-orange-500 mr-2 w-5 mt-0.5"></i>
                                        <div>
                                            <span class="font-medium">${this.getUIText('allergens')}:</span>
                                            <span class="ml-1">${this.getLocalizedText(item, 'allergens')}</span>
                                        </div>
                                    </div>
                                ` : ''}
                            </div>
                        ` : ''}
                        
                        <div class="flex items-center justify-center gap-4 pt-4 border-t border-gray-200">
                            ${this.getQuantityInCart(item.id) > 0 ? `
                                <button onclick="app.removeFromCart(${item.id})" 
                                        class="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <span class="text-2xl font-bold min-w-12 text-center">${this.getQuantityInCart(item.id)}</span>
                            ` : ''}
                            <button onclick="app.addToCart(${JSON.stringify(item).replace(/"/g, '&quot;')})" 
                                    class="flex-1 max-w-xs bg-brand-orange text-white px-8 py-4 rounded-lg hover:bg-brand-red transition-colors font-semibold text-lg flex items-center justify-center gap-2">
                                <i class="fas fa-shopping-cart"></i>
                                <span>${this.getUIText('cart')}</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal to body
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = modalHtml;
        document.body.appendChild(modalContainer.firstElementChild);
        
        // Prevent body scroll when modal is open
        document.body.style.overflow = 'hidden';
    }
    
    handleModalImageLoad() {
        const img = document.getElementById('modal-image');
        if (!img) return;
        
        // Detect orientation and adjust layout
        const isPortrait = img.naturalHeight > img.naturalWidth;
        const aspectRatio = img.naturalHeight / img.naturalWidth;
        
        if (isPortrait && aspectRatio > 1.3) {
            // Portrait orientation - use contain to show full image
            img.style.maxHeight = '500px';
            img.style.objectFit = 'contain';
        } else {
            // Landscape or square - use cover
            img.style.maxHeight = '384px'; // max-h-96
            img.style.objectFit = 'cover';
        }
    }
    
    closeItemModal(event) {
        const modal = document.getElementById('item-detail-modal');
        if (modal) {
            modal.remove();
            // Restore body scroll
            document.body.style.overflow = '';
        }
    }
    
    getQuantityInCart(itemId) {
        const cartItem = this.cart.find(item => item.id === itemId);
        return cartItem ? cartItem.quantity : 0;
    }

    renderPromotionAsMenuItem(promotion) {

        const cartItem = this.cart.find(cartItem => cartItem.id === `promotion_${promotion.id}`);
        const quantity = cartItem ? cartItem.quantity : 0;
        

        const originalTotalPrice = promotion.menu_items && promotion.menu_items.length > 0
            ? promotion.menu_items.reduce((total, item) => {
                const quantity = item.quantity || 1;
                return total + (parseFloat(item.price) * quantity);
            }, 0)
            : 0;
            
        const promotionPrice = parseFloat(promotion.price);
        const savings = originalTotalPrice > promotionPrice ? originalTotalPrice - promotionPrice : 0;
        
        // Get theme accent color for border
        const borderColor = getComputedStyle(document.documentElement).getPropertyValue('--theme-accent-color').trim() || '#f97316';
        
        return `
            <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow overflow-hidden menu-item-card" style="border: 2px solid ${borderColor};">
                <div class="p-4 sm:p-6">
                    <!-- Promotion Badge -->
                    <div class="flex items-center mb-2">
                        <div class="p-1 rounded-full mr-2 flex-shrink-0" style="background-color: ${borderColor}; color: white;">
                            <i class="fas fa-percentage text-xs"></i>
                        </div>
                        <span class="text-xs font-semibold uppercase tracking-wide" style="color: ${borderColor};">${this.getUIText('comboPromotion').toUpperCase()}</span>
                    </div>
                    
                    <div class="flex justify-between items-start mb-2 sm:mb-3">
                        <h3 class="text-base sm:text-lg font-bold text-gray-900 flex-1 pr-2">${this.getLocalizedText(promotion, 'name')}</h3>
                        <div class="text-right whitespace-nowrap price-container">
                            ${savings > 0 ? `
                                <div class="flex flex-col items-end space-y-1">
                                    <span class="text-sm text-gray-500 line-through">${originalTotalPrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                    <span class="text-lg sm:text-xl font-bold" style="color: ${borderColor};">${promotionPrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                    <span class="sale-badge text-xs px-2 py-1 rounded-full font-medium" style="background-color: ${borderColor}20; color: ${borderColor};">${this.getUIText('save')} ${savings.toFixed(0)} ${this.getUIText('currency')}</span>
                                </div>
                            ` : `
                                <span class="text-lg sm:text-xl font-bold" style="color: ${borderColor};">${promotionPrice.toFixed(0)} ${this.getUIText('currency')}</span>
                            `}
                        </div>
                    </div>
                    
                    ${this.getLocalizedText(promotion, 'description') ? `
                        <p class="text-gray-600 text-xs sm:text-sm mb-3">${this.getLocalizedText(promotion, 'description')}</p>
                    ` : ''}
                    
                    <!-- Menu Items Included -->
                    ${promotion.menu_items && promotion.menu_items.length > 0 ? `
                        <div class="text-xs text-gray-600 mb-3">
                            <div class="flex items-center mb-1">
                                <i class="fas fa-utensils mr-1" style="color: ${borderColor};"></i>
                                <span class="font-medium">${this.getUIText('includes')}:</span>
                            </div>
                            <div class="ml-4 space-y-1">
                                ${promotion.menu_items.map(item => `
                                    <div class="flex justify-between">
                                        <span>${this.getLocalizedText(item, 'name')}${item.quantity && item.quantity > 1 ? ` (${item.quantity}x)` : ''}</span>
                                        <span class="text-gray-500">${(parseFloat(item.price) * (item.quantity || 1)).toFixed(0)} ${this.getUIText('currency')}</span>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    ` : ''}
                    
                    <div class="flex items-center justify-end">
                        <div class="flex items-center space-x-2">
                            ${quantity > 0 ? `
                                <button onclick="app.removePromotionFromCart('${promotion.id}')" 
                                        class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors relative z-40">
                                    <i class="fas fa-minus text-xs"></i>
                                </button>
                                <span class="min-w-8 text-center font-semibold">${quantity}</span>
                            ` : ''}
                            <button onclick="app.addPromotionToCart(${promotion.id})" 
                                    class="w-8 h-8 rounded-full text-white flex items-center justify-center transition-colors relative z-40" 
                                    style="background-color: ${borderColor};"
                                    onmouseover="this.style.opacity='0.8'" 
                                    onmouseout="this.style.opacity='1'">
                                <i class="fas fa-plus text-xs"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    addToCart(item) {
        const existingItem = this.cart.find(cartItem => cartItem.id === item.id);
        

        const saleInfo = this.calculateSalePrice(item);
        const actualPrice = saleInfo.hasValidSale ? saleInfo.salePrice : parseFloat(item.price);
        
        if (existingItem) {
            existingItem.quantity += 1;

            existingItem.price = actualPrice;
        } else {
            this.cart.push({
                id: item.id,
                name: item.name,
                name_mk: item.name_mk || item.name,
                name_en: item.name_en || item.name,
                price: actualPrice,
                quantity: 1,
                image_url: item.image_url,
                is_on_sale: item.is_on_sale || false,
                original_price: saleInfo.hasValidSale ? saleInfo.originalPrice : actualPrice
            });
        }
        
        this.saveCart();
        this.updateCartCount();
        this.renderMenuItems(); // Re-render to update button states
        
        if (this.cartVisible) {
            this.updateCartSidebar(); // Update only the cart sidebar content
        }
    }

    addPromotionToCart(promotionId) {

        const promotion = this.comboPromotions.find(p => p.id === promotionId);
        if (!promotion) {
            console.error('Promotion not found:', promotionId);
            return;
        }
        const cartItemId = `promotion_${promotion.id}`;
        
        const existingItem = this.cart.find(cartItem => cartItem.id === cartItemId);
        
        if (existingItem) {
            existingItem.quantity += 1;
        } else {
            this.cart.push({
                id: cartItemId,
                name: promotion.name,
                name_mk: promotion.name_mk || promotion.name,
                name_en: promotion.name_en || promotion.name,
                description: promotion.description,
                description_mk: promotion.description_mk || promotion.description,
                description_en: promotion.description_en || promotion.description,
                price: parseFloat(promotion.price),
                quantity: 1,
                image_url: null, // Promotions don't have images
                is_promotion: true,
                promotion_items: promotion.menu_items || []
            });
        }
        
        this.saveCart();
        this.updateCartCount();
        this.showAddToCartFeedback(this.getLocalizedText(promotion, 'name'));
        
        if (this.cartVisible) {
            this.updateCartSidebar();
        }
        if (this.selectedCategory && this.selectedCategory.id === 'combo-promotions') {
            this.renderComboPromotions();
        }
    }

    removePromotionFromCart(promotionId) {
        const cartItemId = `promotion_${promotionId}`;
        const existingItemIndex = this.cart.findIndex(cartItem => cartItem.id === cartItemId);
        
        if (existingItemIndex !== -1) {
            const existingItem = this.cart[existingItemIndex];
            
            if (existingItem.quantity > 1) {
                existingItem.quantity -= 1;
            } else {
                this.cart.splice(existingItemIndex, 1);
            }
            
            this.saveCart();
            this.updateCartCount();
            
            if (this.cartVisible) {
                this.updateCartSidebar();
            }
            if (this.selectedCategory && this.selectedCategory.id === 'combo-promotions') {
                this.renderComboPromotions();
            }
        }
    }

    getPromotionQuantityInCart(promotionId) {
        const cartItemId = `promotion_${promotionId}`;
        const cartItem = this.cart.find(item => item.id === cartItemId);
        return cartItem ? cartItem.quantity : 0;
    }

    showAddToCartFeedback(itemName) {

        const notification = document.createElement('div');
        notification.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50 transform translate-x-full transition-transform duration-300';
        notification.innerHTML = `
            <i class="fas fa-check mr-2"></i>
            Added "${itemName}" to cart!
        `;
        
        document.body.appendChild(notification);
        

        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 100);
        

        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 2000);
    }
    
    removeFromCart(itemId) {

        const stringItemId = String(itemId);
        const existingItem = this.cart.find(cartItem => String(cartItem.id) === stringItemId);
        
        if (existingItem) {
            existingItem.quantity -= 1;
            
            if (existingItem.quantity <= 0) {
                this.cart = this.cart.filter(cartItem => String(cartItem.id) !== stringItemId);
            }
        }
        
        this.saveCart();
        this.updateCartCount();
        this.renderMenuItems(); // Re-render to update button states
        
        if (this.cartVisible) {
            this.updateCartSidebar(); // Update only the cart sidebar content
        }
    }
    
    clearCart() {
        this.cart = [];
        this.saveCart();
        this.updateCartCount();
        this.renderMenuItems();
        if (this.cartVisible) {
            this.updateCartSidebar();
        }
    }
    
    loadCart() {
        if (!this.restaurant) return;
        
        // Get all carts from localStorage
        const allCarts = JSON.parse(localStorage.getItem('restaurant_carts') || '{}');
        
        // Load cart specific to this restaurant
        this.cart = allCarts[this.restaurant.id] || [];
    }
    
    saveCart() {
        if (!this.restaurant) return;
        
        // Get all carts from localStorage
        const allCarts = JSON.parse(localStorage.getItem('restaurant_carts') || '{}');
        
        // Save cart for this specific restaurant
        allCarts[this.restaurant.id] = this.cart;
        
        localStorage.setItem('restaurant_carts', JSON.stringify(allCarts));
    }
    
    toggleCart() {
        this.cartVisible = !this.cartVisible;
        this.render();
    }
    
    updateCartSidebar() {
        const cartItemsContainer = document.querySelector('#cart-sidebar .flex-1.overflow-y-auto.p-4');
        const cartFooter = document.querySelector('#cart-sidebar .border-t.border-gray-200.p-4');
        
        if (cartItemsContainer) {
            cartItemsContainer.innerHTML = this.renderCartItems();
        }
        
        if (cartFooter) {
            if (this.cart.length > 0) {
                cartFooter.innerHTML = `
                    <div class="flex justify-between items-center mb-4">
                        <span class="text-lg font-semibold">Вкупно (Total):</span>
                        <span class="text-xl font-bold text-brand-orange">${this.getCartTotal()} ${this.getUIText('currency')}</span>
                    </div>
                    <button onclick="app.clearCart()" class="w-full bg-red-600 text-white py-3 rounded-lg font-semibold hover:bg-red-700 transition-colors">
                        <i class="fas fa-trash mr-2"></i>Исчисти се (Clear All)
                    </button>
                `;
            } else {
                cartFooter.innerHTML = '';
            }
        }
    }
    
    updateCartCount() {
        const count = this.cart.reduce((total, item) => total + item.quantity, 0);
        
        // Update cart count badge in fixed header
        const cartCountElement = document.getElementById('cart-count');
        if (cartCountElement) {
            if (count > 0) {
                cartCountElement.textContent = count;
                cartCountElement.style.display = 'flex';
            } else {
                cartCountElement.style.display = 'none';
            }
        }

        this.updateNavbarCart();
    }
    
    updateNavbarCart() {
        // This method may still be called from existing code, but we now use the fixed header cart button
        // Keep for compatibility but the main cart display is handled in updateCartCount
        const navbarCartButton = document.querySelector('.navbar-cart-button');
        if (navbarCartButton) {
            const count = this.cart.reduce((total, item) => total + item.quantity, 0);
            const total = this.getCartTotal();
            
            navbarCartButton.innerHTML = `
                <i class="fas fa-shopping-cart"></i>
                <span class="font-medium">${count}</span>
                <span class="hidden sm:inline-block">|</span>
                <span class="hidden sm:inline-block font-semibold">${total} ${this.getUIText('currency')}</span>
            `;
        }
    }
    
    getCartTotal() {
        return this.cart.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(0);
    }
    
    renderCartItems() {
        if (this.cart.length === 0) {
            return `
                <div class="text-center py-8">
                    <i class="fas fa-shopping-cart text-4xl text-gray-300 mb-4"></i>
                    <p class="text-gray-500">Корпата е празна</p>
                    <p class="text-gray-400 text-sm">Cart is empty</p>
                </div>
            `;
        }
        
        return this.cart.map(item => `
            <div class="flex items-center space-x-3 py-3 border-b border-gray-100 last:border-b-0">
                ${item.is_promotion ? `
                    <div class="w-12 h-12 rounded-lg bg-orange-100 flex items-center justify-center text-orange-600">
                        <i class="fas fa-percentage text-lg"></i>
                    </div>
                ` : `
                    <img src="${item.image_url || 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=60&h=60&fit=crop'}" 
                         alt="${item.name}" 
                         class="w-12 h-12 rounded-lg object-cover">
                `}
                
                <div class="flex-1 min-w-0">
                    <h4 class="text-sm font-medium text-gray-900 truncate">
                        ${item.is_promotion ? `
                            <i class="fas fa-percentage text-orange-600 mr-1"></i>
                        ` : ''}
                        ${this.getLocalizedText(item, 'name')}
                    </h4>
                    ${item.is_promotion && item.promotion_items && item.promotion_items.length > 0 ? `
                        <p class="text-xs text-gray-500 mb-1">
                            ${this.getUIText('includes')}: ${item.promotion_items.map(pi => this.getLocalizedText(pi, 'name')).slice(0, 2).join(', ')}${item.promotion_items.length > 2 ? ` +${item.promotion_items.length - 2} more` : ''}
                        </p>
                    ` : ''}
                    <div class="flex items-center space-x-2">
                        ${item.is_on_sale && item.original_price ? `
                            <span class="text-xs text-gray-400 line-through">${parseFloat(item.original_price).toFixed(0)} ${this.getUIText('currency')}</span>
                            <span class="text-sm text-red-600 font-semibold">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</span>
                        ` : `
                            <p class="text-sm ${item.is_promotion ? 'text-orange-600' : 'text-brand-orange'} font-semibold">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</p>
                        `}
                    </div>
                </div>
                
                <div class="flex items-center space-x-2">
                    <button onclick="app.removeFromCart('${item.id}')" 
                            class="w-7 h-7 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                        <i class="fas fa-minus text-xs"></i>
                    </button>
                    <span class="min-w-6 text-center font-semibold">${item.quantity}</span>
                    ${item.is_promotion ? `
                        <button onclick="app.addPromotionToCart(${item.id.replace('promotion_', '')})" 
                                class="w-7 h-7 rounded-full bg-orange-600 text-white flex items-center justify-center hover:bg-orange-700">
                            <i class="fas fa-plus text-xs"></i>
                        </button>
                    ` : `
                        <button onclick="app.addToCart(${JSON.stringify(item).replace(/"/g, '&quot;')})" 
                                class="w-7 h-7 rounded-full bg-brand-orange text-white flex items-center justify-center hover:bg-brand-red">
                            <i class="fas fa-plus text-xs"></i>
                        </button>
                    `}
                </div>
            </div>
        `).join('');
    }
    
    showOrderSummary() {
        const total = this.getCartTotal();
        const itemCount = this.cart.reduce((total, item) => total + item.quantity, 0);
        
        const summary = `
            <div class="bg-white p-6 rounded-lg">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fas fa-receipt mr-2 text-brand-orange"></i>
                    Преглед нарачка (Order Summary)
                </h3>
                
                <div class="space-y-3 mb-6">
                    ${this.cart.map(item => `
                        <div class="flex justify-between items-center">
                            <div>
                                <span class="font-medium">${item.name}</span>
                                <span class="text-gray-500 text-sm ml-2">x${item.quantity}</span>
                            </div>
                            <span class="font-semibold">${(item.price * item.quantity).toFixed(0)} ${this.getUIText('currency')}</span>
                        </div>
                    `).join('')}
                </div>
                
                <div class="border-t pt-4 mb-6">
                    <div class="flex justify-between items-center text-lg font-bold">
                        <span>Вкупно (Total):</span>
                        <span class="text-brand-orange">${total} ${this.getUIText('currency')}</span>
                    </div>
                    <p class="text-sm text-gray-500 mt-1">${itemCount} ставки (items)</p>
                </div>
                
                <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
                    <div class="flex items-start">
                        <i class="fas fa-info-circle text-yellow-600 mt-0.5 mr-2"></i>
                        <div class="text-sm">
                            <p class="font-medium text-yellow-800 mb-1">Инструкции за нарачка (Order Instructions):</p>
                            <p class="text-yellow-700">Покажете го овој преглед на келнерот за да ја направите вашата нарачка.</p>
                            <p class="text-yellow-600 text-xs mt-1">Show this summary to your waiter to place your order.</p>
                        </div>
                    </div>
                </div>
                
                <div class="flex space-x-3">
                    <button onclick="app.clearCart(); app.closeOrderSummary();" 
                            class="flex-1 bg-gray-200 text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-300 transition-colors">
                        <i class="fas fa-trash mr-2"></i>Исчисти (Clear)
                    </button>
                    <button onclick="app.closeOrderSummary();" 
                            class="flex-1 bg-brand-orange text-white py-3 rounded-lg font-semibold hover:bg-brand-red transition-colors">
                        <i class="fas fa-check mr-2"></i>Готово (Done)
                    </button>
                </div>
            </div>
        `;
        

        const modal = document.createElement('div');
        modal.id = 'order-summary-modal';
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
        modal.innerHTML = `
            <div class="bg-white rounded-lg max-w-md w-full max-h-screen overflow-y-auto">
                ${summary}
            </div>
        `;
        
        document.body.appendChild(modal);
    }
    
    closeOrderSummary() {
        const modal = document.getElementById('order-summary-modal');
        if (modal) {
            modal.remove();
        }
    }
    
    showItemModal(item) {
        const saleInfo = this.calculateSalePrice(item);
        const cartItem = this.cart.find(cartItem => cartItem.id === item.id);
        const quantity = cartItem ? cartItem.quantity : 0;
        
        const modal = document.createElement('div');
        modal.id = 'item-detail-modal';
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
        modal.onclick = (e) => {
            if (e.target === modal) {
                this.closeItemModal();
            }
        };
        
        modal.innerHTML = `
            <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto" onclick="event.stopPropagation()">
                <div class="sticky top-0 bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between z-10">
                    <h2 class="text-xl font-bold text-gray-900">${this.getLocalizedText(item, 'name')}</h2>
                    <button onclick="app.closeItemModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div class="p-4">
                    ${item.image_url ? `
                        <div class="relative mb-4 rounded-lg overflow-hidden">
                            <img src="${item.image_url}" 
                                 alt="${this.getLocalizedText(item, 'name')}"
                                 class="w-full h-auto max-h-96 object-contain bg-gray-50"
                                 onerror="this.src='https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=800&h=600&fit=crop'">
                            ${saleInfo.hasValidSale ? `
                                <div class="absolute top-4 right-4">
                                    ${saleInfo.saleType === 'percentage' ? `
                                        <span class="bg-red-500 text-white px-3 py-2 rounded-full text-sm font-bold shadow-lg">-${saleInfo.saleValue}%</span>
                                    ` : saleInfo.saleType === 'fixed_discount' ? `
                                        <span class="bg-red-500 text-white px-3 py-2 rounded-full text-sm font-bold shadow-lg">-${saleInfo.saleValue} ${this.getUIText('currency')}</span>
                                    ` : `
                                        <span class="bg-red-500 text-white px-3 py-2 rounded-full text-sm font-bold shadow-lg">SALE</span>
                                    `}
                                </div>
                            ` : ''}
                        </div>
                    ` : ''}
                    
                    <div class="mb-4">
                        <div class="flex items-center justify-between mb-3">
                            <div>
                                ${saleInfo.hasValidSale ? `
                                    <div class="flex items-center gap-3">
                                        <span class="text-lg text-gray-500 line-through">${saleInfo.originalPrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                        <span class="text-2xl font-bold text-red-600">${saleInfo.salePrice.toFixed(0)} ${this.getUIText('currency')}</span>
                                    </div>
                                    <p class="text-sm text-green-600 font-medium mt-1">
                                        <i class="fas fa-tag mr-1"></i>${this.getUIText('save')} ${(saleInfo.originalPrice - saleInfo.salePrice).toFixed(0)} ${this.getUIText('currency')}
                                    </p>
                                ` : `
                                    <span class="text-2xl font-bold text-brand-orange">${parseFloat(item.price).toFixed(0)} ${this.getUIText('currency')}</span>
                                `}
                            </div>
                        </div>
                    </div>
                    
                    ${this.getLocalizedText(item, 'description') ? `
                        <div class="mb-4">
                            <h3 class="text-sm font-semibold text-gray-700 mb-2 flex items-center">
                                <i class="fas fa-info-circle text-brand-orange mr-2"></i>
                                ${this.currentLanguage === 'mk' ? 'Опис' : 'Description'}
                            </h3>
                            <p class="text-gray-600 text-sm leading-relaxed">${this.getLocalizedText(item, 'description')}</p>
                        </div>
                    ` : ''}
                    
                    ${item.size_info ? `
                        <div class="mb-4">
                            <h3 class="text-sm font-semibold text-gray-700 mb-2 flex items-center">
                                <i class="fas fa-ruler text-indigo-500 mr-2"></i>
                                ${this.getUIText('size')}
                            </h3>
                            <p class="text-gray-600 text-sm">${item.size_info}</p>
                        </div>
                    ` : ''}
                    
                    ${this.getLocalizedText(item, 'allergens') ? `
                        <div class="mb-4 bg-orange-50 border border-orange-200 rounded-lg p-3">
                            <h3 class="text-sm font-semibold text-orange-800 mb-2 flex items-center">
                                <i class="fas fa-exclamation-triangle text-orange-500 mr-2"></i>
                                ${this.getUIText('allergens')}
                            </h3>
                            <p class="text-orange-700 text-sm leading-relaxed">${this.getLocalizedText(item, 'allergens')}</p>
                        </div>
                    ` : ''}
                    
                    <div class="flex items-center justify-between mt-6 pt-4 border-t border-gray-200">
                        <div class="text-sm text-gray-500">
                            ${quantity > 0 ? `
                                <span class="font-medium">${this.currentLanguage === 'mk' ? 'Во кошничка' : 'In cart'}: ${quantity}</span>
                            ` : ''}
                        </div>
                        <div class="flex items-center space-x-3">
                            ${quantity > 0 ? `
                                <button onclick="app.removeFromCart(${item.id}); app.updateModalQuantity(${item.id})" 
                                        class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300 transition-colors">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <span id="modal-quantity-${item.id}" class="min-w-8 text-center font-bold text-lg">${quantity}</span>
                            ` : ''}
                            <button onclick="app.addToCart(${JSON.stringify(item).replace(/"/g, '&quot;')}); app.updateModalQuantity(${item.id})" 
                                    class="px-6 py-3 rounded-full bg-brand-orange text-white flex items-center justify-center hover:bg-brand-red transition-colors font-semibold">
                                <i class="fas fa-plus mr-2"></i>
                                ${this.currentLanguage === 'mk' ? 'Додади' : 'Add to Cart'}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
    }
    
    closeItemModal() {
        const modal = document.getElementById('item-detail-modal');
        if (modal) {
            modal.remove();
        }
    }
    
    updateModalQuantity(itemId) {
        const cartItem = this.cart.find(item => item.id === itemId);
        const quantity = cartItem ? cartItem.quantity : 0;
        const quantityElement = document.getElementById(`modal-quantity-${itemId}`);
        if (quantityElement) {
            quantityElement.textContent = quantity;
        }
        // If quantity becomes 0, we might want to refresh the modal buttons
        if (quantity === 0) {
            this.closeItemModal();
        }
        // Update the horizontal item card too
        this.renderMenuItems();
    }
    testSaleDisplay() {

        const sampleItems = [
            {
                id: 1,
                name: "Margherita Pizza",
                description: "Classic tomato sauce, mozzarella, and fresh basil",
                price: "350.00",
                is_on_sale: true,
                sale_type: "percentage",
                sale_value: "20.00",
                original_price: "350.00"
            },
            {
                id: 2,
                name: "Caesar Salad",
                description: "Crisp romaine lettuce, parmesan, croutons, caesar dressing",
                price: "280.00",
                is_on_sale: true,
                sale_type: "fixed_discount",
                sale_value: "50.00",
                original_price: "280.00"
            },
            {
                id: 3,
                name: "Grilled Chicken",
                description: "Tender grilled chicken breast with herbs",
                price: "450.00",
                is_on_sale: true,
                sale_type: "sale_price",
                sale_value: "350.00",
                original_price: "450.00"
            },
            {
                id: 4,
                name: "Pasta Carbonara",
                description: "Traditional pasta with eggs, cheese, pancetta",
                price: "320.00",
                is_on_sale: false
            }
        ];
        const container = document.getElementById('menu-items-container');
        if (container) {
            container.innerHTML = `
                <div class="mb-8">
                    <h2 class="text-2xl font-bold text-gray-900 mb-2">Test Sale Display</h2>
                    <p class="text-gray-600 mb-6">Sample menu items demonstrating sale functionality</p>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
                    ${sampleItems.map(item => this.renderMenuItem(item)).join('')}
                </div>
                <div class="mt-8 p-4 bg-blue-50 rounded-lg">
                    <h3 class="font-bold text-blue-800 mb-2">Sale Types Demonstrated:</h3>
                    <ul class="text-sm text-blue-700 space-y-1">
                        <li><strong>Percentage Discount:</strong> Margherita Pizza (20% off original price)</li>
                        <li><strong>Fixed Discount:</strong> Caesar Salad (50 ${this.getUIText('currency')} off original price)</li>
                        <li><strong>Sale Price:</strong> Grilled Chicken (direct sale price 350 ${this.getUIText('currency')})</li>
                        <li><strong>No Sale:</strong> Pasta Carbonara (regular price)</li>
                    </ul>
                </div>
            `;
        }
    }

    initPromotionCarousel() {

        if (window.innerWidth >= 1024) return;
        
        const carouselContainer = document.querySelector('.carousel-container');
        const dots = document.querySelectorAll('.carousel-dot');
        const items = document.querySelectorAll('.carousel-item');
        
        if (!carouselContainer || !dots.length || !items.length) return;
        
        let currentIndex = 0;
        

        const updateCarousel = (index) => {

            if (index >= items.length) {
                index = 0; // Go to first item when reaching the end
            } else if (index < 0) {
                index = items.length - 1; // Go to last item when going back from first
            }
            

            const transformX = -index * 100;
            carouselContainer.style.transform = `translateX(${transformX}vw)`;
            

            dots.forEach((dot, dotIndex) => {
                if (dotIndex === index) {
                    dot.classList.remove('bg-gray-300');
                    dot.classList.add('bg-orange-600');
                } else {
                    dot.classList.remove('bg-orange-600');
                    dot.classList.add('bg-gray-300');
                }
            });
            
            currentIndex = index;
        };
        

        dots.forEach((dot, index) => {
            dot.addEventListener('click', () => {
                updateCarousel(index);
            });
        });
        

        let startX = 0;
        let startY = 0;
        let isDragging = false;
        let hasMovedHorizontally = false;
        
        carouselContainer.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
            isDragging = true;
            hasMovedHorizontally = false;

            carouselContainer.style.transition = 'none';
        }, { passive: true });
        
        carouselContainer.addEventListener('touchmove', (e) => {
            if (!isDragging) return;
            
            const currentX = e.touches[0].clientX;
            const currentY = e.touches[0].clientY;
            const diffX = startX - currentX;
            const diffY = startY - currentY;
            

            if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 10) {
                hasMovedHorizontally = true;
                e.preventDefault(); // Prevent vertical scrolling when swiping horizontally
                

                const containerWidth = window.innerWidth;
                const dragOffset = -diffX;
                const baseTransform = -currentIndex * 100;
                const dragPercentage = (dragOffset / containerWidth) * 100;
                
                carouselContainer.style.transform = `translateX(${baseTransform + dragPercentage}vw)`;
            }
        }, { passive: false });
        
        carouselContainer.addEventListener('touchend', (e) => {
            if (!isDragging) return;
            isDragging = false;
            

            carouselContainer.style.transition = 'transform 0.3s ease-in-out';
            
            const endX = e.changedTouches[0].clientX;
            const diffX = startX - endX;
            

            if (hasMovedHorizontally && Math.abs(diffX) > 50) {
                if (diffX > 0) {

                    updateCarousel(currentIndex + 1);
                } else if (diffX < 0) {

                    updateCarousel(currentIndex - 1);
                } else {

                    updateCarousel(currentIndex);
                }
            } else {

                updateCarousel(currentIndex);
            }
        }, { passive: true });
        

        if (dots.length > 0) {
            dots[0].classList.remove('bg-gray-300');
            dots[0].classList.add('bg-orange-600');
        }
        

        carouselContainer.style.transform = 'translateX(0vw)';
        carouselContainer.style.transition = 'transform 0.3s ease-in-out';
        

        const handleResize = () => {
            if (window.innerWidth >= 1024) {

                carouselContainer.style.transform = 'translateX(0vw)';
                currentIndex = 0;
                if (dots.length > 0) {
                    dots.forEach(dot => {
                        dot.classList.remove('bg-orange-600');
                        dot.classList.add('bg-gray-300');
                    });
                    dots[0].classList.remove('bg-gray-300');
                    dots[0].classList.add('bg-orange-600');
                }
            }
        };
        
        window.addEventListener('resize', handleResize);
    }
}
document.addEventListener('DOMContentLoaded', () => {
    new MenuApp();
});
window.testSales = function() {
    if (window.app) {
        window.app.testSaleDisplay();
    }
};