// Samanta Menu - Exact Preview.php JavaScript

(function() {
    // Initialize AOS
    if (typeof AOS !== 'undefined') {
        AOS.init({
            once: true,
            offset: 60
        });
    }

    // Get location data from template
    const menuData = window.samantaMenuData || { locationId: 0, locationName: '' };
    
    // Language Management
    let currentLang = getInitialLanguage();

    function getInitialLanguage() {
        const hash = window.location.hash.substring(1);
        if (hash === 'en' || hash === 'pl') {
            return hash;
        }
        return localStorage.getItem('menuLanguage_' + menuData.locationId) || 'pl';
    }

    window.samantaToggleLanguage = function() {
        currentLang = currentLang === 'pl' ? 'en' : 'pl';
        localStorage.setItem('menuLanguage_' + menuData.locationId, currentLang);
        history.pushState(null, '', '#' + currentLang);
        updateLanguage(true);
    };

    function updateLanguage(animate) {
        const langFlag = document.getElementById('samantaLangFlag');
        const plElements = document.querySelectorAll('.lang-pl');
        const enElements = document.querySelectorAll('.lang-en');
        const menuWrappers = document.querySelectorAll('.menu-wrapper');

        if (animate) {
            menuWrappers.forEach(wrapper => {
                wrapper.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                wrapper.style.opacity = '0';
                wrapper.style.transform = 'translateY(20px)';
            });

            setTimeout(() => {
                if (currentLang === 'pl') {
                    langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/Poland_flag_icon_round-copy.svg';
                    langFlag.alt = 'Polish flag';
                    enElements.forEach(el => el.style.display = 'none');
                    plElements.forEach(el => el.style.display = '');
                } else {
                    langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/United-kingdom_flag_icon_round.svg';
                    langFlag.alt = 'English flag';
                    plElements.forEach(el => el.style.display = 'none');
                    enElements.forEach(el => el.style.display = '');
                }

                setTimeout(() => {
                    menuWrappers.forEach((wrapper, index) => {
                        setTimeout(() => {
                            wrapper.style.opacity = '1';
                            wrapper.style.transform = 'translateY(0)';
                        }, index * 100);
                    });
                }, 50);
            }, 300);
        } else {
            if (currentLang === 'pl') {
                langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/Poland_flag_icon_round-copy.svg';
                langFlag.alt = 'Polish flag';
                plElements.forEach(el => el.style.display = '');
                enElements.forEach(el => el.style.display = 'none');
            } else {
                langFlag.src = 'https://www.cukierniasamanta.pl/sklep/wp-content/uploads/2022/08/United-kingdom_flag_icon_round.svg';
                langFlag.alt = 'English flag';
                plElements.forEach(el => el.style.display = 'none');
                enElements.forEach(el => el.style.display = '');
            }
        }
        
        localStorage.setItem('menuLanguage_' + menuData.locationId, currentLang);
    }

    window.addEventListener('hashchange', function() {
        const hash = window.location.hash.substring(1);
        if ((hash === 'en' || hash === 'pl') && hash !== currentLang) {
            currentLang = hash;
            updateLanguage(true);
        }
    });

    updateLanguage(false);
    
    if (!window.location.hash) {
        history.replaceState(null, '', '#' + currentLang);
    }

    // Smooth scroll for category links
    document.querySelectorAll('.category-nav-link, .popup-category-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                document.getElementById('samantaCategoryMenuPopup').classList.remove('visible');
            }
        });
    });

    // Floating buttons
    const scrollTopBtn = document.getElementById('samantaScrollTopBtn');
    const menuBtn = document.getElementById('samantaMenuBtn');
    const categoryMenuPopup = document.getElementById('samantaCategoryMenuPopup');

    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            scrollTopBtn.classList.add('visible');
            menuBtn.classList.add('visible');
        } else {
            scrollTopBtn.classList.remove('visible');
            menuBtn.classList.remove('visible');
        }
    });

    scrollTopBtn.addEventListener('click', function() {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });

    menuBtn.addEventListener('click', function() {
        categoryMenuPopup.classList.toggle('visible');
    });

    document.addEventListener('click', function(e) {
        if (categoryMenuPopup && !categoryMenuPopup.contains(e.target) && e.target !== menuBtn) {
            categoryMenuPopup.classList.remove('visible');
        }
    });

    // Cart Management
    let cart = JSON.parse(localStorage.getItem('menuCart_' + menuData.locationId) || '[]');

    // Load shared items from URL
    function loadSharedItems() {
        const urlParams = new URLSearchParams(window.location.search);
        const encodedItems = urlParams.get('items');
        
        if (encodedItems) {
            try {
                const decodedString = atob(encodedItems);
                const itemIds = decodedString.split(',').filter(id => id);
                if (itemIds.length > 0) {
                    cart = itemIds;
                    saveCart();
                    setTimeout(() => {
                        alert(`Załadowano ${itemIds.length} ${itemIds.length === 1 ? 'pozycję' : itemIds.length < 5 ? 'pozycje' : 'pozycji'} z udostępnionego linku!`);
                    }, 500);
                }
            } catch (e) {
                console.error('Failed to decode shared items:', e);
            }
        }
    }

    loadSharedItems();

    function updateCartUI() {
        const cartBadge = document.getElementById('samantaCartBadge');
        const cartBtn = document.getElementById('samantaCartBtn');
        
        if (cart.length > 0) {
            cartBadge.textContent = cart.length;
            cartBadge.classList.add('visible');
            cartBtn.classList.add('visible');
        } else {
            cartBadge.classList.remove('visible');
        }

        document.querySelectorAll('.menu-item').forEach(item => {
            const itemId = item.dataset.itemId;
            if (cart.includes(itemId)) {
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
        });
    }

    function saveCart() {
        localStorage.setItem('menuCart_' + menuData.locationId, JSON.stringify(cart));
        updateCartUI();
    }

    window.samantaToggleCartItem = function(element, event) {
        if (event.target.classList.contains('menu-item-img') || 
            event.target.classList.contains('remove-item-btn')) {
            return;
        }

        const itemId = element.dataset.itemId;
        const index = cart.indexOf(itemId);
        
        if (index > -1) {
            cart.splice(index, 1);
        } else {
            cart.push(itemId);
        }
        
        saveCart();
    };

    window.samantaRemoveFromCart = function(button, event) {
        event.stopPropagation();
        const menuItem = button.closest('.menu-item');
        const itemId = menuItem.dataset.itemId;
        const index = cart.indexOf(itemId);
        
        if (index > -1) {
            cart.splice(index, 1);
            saveCart();
        }
    };

    function showCart() {
        const cartView = document.getElementById('samantaCartView');
        const cartContent = document.getElementById('samantaCartContent');
        const cartCount = document.getElementById('samantaCartCount');
        
        if (cart.length === 0) {
            cartContent.innerHTML = `
                <div class="cart-empty">
                    <div class="cart-empty-icon">🛒</div>
                    <h3 style="color: var(--accent-main);">Brak wybranych pozycji</h3>
                    <p class="text-muted">Kliknij na pozycje menu, aby je dodać do wyboru</p>
                </div>
            `;
            cartCount.textContent = '0 pozycji';
        } else {
            const cartItemsData = [];
            cart.forEach(itemId => {
                const element = document.querySelector(`[data-item-id="${itemId}"]`);
                if (element) {
                    const categoryWrapper = element.closest('.menu-wrapper');
                    const categoryTitle = categoryWrapper ? categoryWrapper.querySelector('.section-title').textContent : 'Inne';
                    
                    cartItemsData.push({
                        id: itemId,
                        category: categoryTitle,
                        html: element.innerHTML
                    });
                }
            });

            const grouped = {};
            cartItemsData.forEach(item => {
                if (!grouped[item.category]) {
                    grouped[item.category] = [];
                }
                grouped[item.category].push(item);
            });

            let html = '';
            Object.keys(grouped).forEach(category => {
                html += `
                    <div class="menu-wrapper" style="animation: fadeIn 0.3s ease;">
                        <h2 class="section-title">${category}</h2>
                        <div class="menu-items">
                `;
                
                grouped[category].forEach(item => {
                    html += `
                        <div class="menu-item selected" data-item-id="${item.id}" onclick="samantaToggleCartItem(this, event)">
                            <button class="remove-item-btn" onclick="samantaRemoveFromCart(this, event)" title="Usuń z wyboru">×</button>
                            ${item.html}
                        </div>
                    `;
                });
                
                html += `
                        </div>
                    </div>
                `;
            });
            
            cartContent.innerHTML = html;
            cartCount.textContent = `${cart.length} ${cart.length === 1 ? 'pozycja' : cart.length < 5 ? 'pozycje' : 'pozycji'}`;
        }
        
        cartView.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    window.samantaCloseCartView = function() {
        const cartView = document.getElementById('samantaCartView');
        cartView.classList.remove('active');
        document.body.style.overflow = '';
    };

    window.samantaToggleShareMenu = function() {
        const shareMenu = document.getElementById('samantaShareMenu');
        shareMenu.classList.toggle('active');
    };

    function getCartShareText() {
        if (cart.length === 0) {
            return { text: 'Brak wybranych pozycji', url: window.location.href.split('?')[0].split('#')[0] };
        }

        const baseUrl = window.location.href.split('?')[0].split('#')[0];
        const itemsString = cart.join(',');
        const encodedItems = btoa(itemsString);
        const shareUrl = `${baseUrl}?items=${encodedItems}#${currentLang}`;
        
        let text = `Sprawdź moje wybrane pozycje z menu - ${menuData.locationName}!\n\n`;
        text += shareUrl;
        
        return { text, url: shareUrl };
    }

    window.samantaShareViaWhatsApp = function(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const url = `https://wa.me/?text=${encodeURIComponent(shareData.text)}`;
        window.open(url, '_blank');
        samantaToggleShareMenu();
    };

    window.samantaShareViaSMS = function(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const url = `sms:?body=${encodeURIComponent(shareData.text)}`;
        window.location.href = url;
        samantaToggleShareMenu();
    };

    window.samantaShareViaEmail = function(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const subject = `Menu - ${menuData.locationName}`;
        const url = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(shareData.text)}`;
        window.location.href = url;
        samantaToggleShareMenu();
    };

    window.samantaShareViaMessenger = function(event) {
        event.preventDefault();
        const shareData = getCartShareText();
        const url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareData.url)}`;
        window.open(url, '_blank', 'width=600,height=400');
        samantaToggleShareMenu();
    };

    document.addEventListener('click', function(e) {
        const shareMenu = document.getElementById('samantaShareMenu');
        const shareBtn = document.getElementById('samantaShareBtn');
        if (shareMenu && !shareMenu.contains(e.target) && e.target !== shareBtn && !shareBtn.contains(e.target)) {
            shareMenu.classList.remove('active');
        }
    });

    updateCartUI();
    document.getElementById('samantaCartBtn').addEventListener('click', showCart);

    // Lightbox
    window.samantaOpenLightbox = function(img, event) {
        event.stopPropagation();
        
        const lightbox = document.getElementById('samantaLightbox');
        const lightboxImage = document.getElementById('samantaLightboxImage');
        const lightboxTitle = document.getElementById('samantaLightboxTitle');
        const lightboxSubtitle = document.getElementById('samantaLightboxSubtitle');
        const lightboxDesc = document.getElementById('samantaLightboxDesc');
        const lightboxPrices = document.getElementById('samantaLightboxPrices');

        const data = JSON.parse(img.dataset.lightboxData || '{}');
        
        lightboxImage.src = img.src;
        lightboxImage.alt = img.alt;
        
        if (currentLang === 'pl') {
            lightboxTitle.textContent = data.title_pl || '';
            lightboxSubtitle.textContent = data.subtitle_pl || '';
            lightboxDesc.textContent = data.desc_pl || '';
        } else {
            lightboxTitle.textContent = data.title_en || data.title_pl || '';
            lightboxSubtitle.textContent = data.subtitle_en || data.subtitle_pl || '';
            lightboxDesc.textContent = data.desc_en || data.desc_pl || '';
        }
        
        lightboxSubtitle.style.display = lightboxSubtitle.textContent ? 'block' : 'none';
        lightboxDesc.style.display = lightboxDesc.textContent ? 'block' : 'none';

        let pricesHTML = '';
        if (data.prices && data.prices.length > 0) {
            data.prices.forEach(price => {
                pricesHTML += '<div class="lightbox-price-item">';
                const label = currentLang === 'pl' ? price.label_pl : (price.label_en || price.label_pl);
                if (label) {
                    pricesHTML += '<div class="lightbox-price-label">' + label + '</div>';
                }
                pricesHTML += '<div class="lightbox-price">' + Number(price.value).toFixed(0) + ' zł</div>';
                pricesHTML += '</div>';
            });
        }
        
        lightboxPrices.innerHTML = pricesHTML;
        lightboxPrices.style.display = pricesHTML ? 'block' : 'none';

        lightbox.classList.add('active');
        document.body.style.overflow = 'hidden';
    };

    window.samantaCloseLightbox = function(event) {
        if (event) event.stopPropagation();
        const lightbox = document.getElementById('samantaLightbox');
        lightbox.classList.add('closing');
        
        setTimeout(() => {
            lightbox.classList.remove('active');
            lightbox.classList.remove('closing');
            document.body.style.overflow = '';
        }, 300);
    };

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            samantaCloseLightbox();
        }
    });

})();
