// Menu Data
const menuItems = [];

function addItem(id, name, desc, price, category, img) {
    menuItems.push({ id, name, desc, price, category, img });
}

// Burgers (b1 to b10)
const burgerNames = ["Neon Smash", "Cyber Chicken", "Classic Beef", "Spicy Jalapeno", "Double Decker", "BBQ Bacon", "Mushroom Swiss", "Crispy Fish", "Veggie Delight", "Ultimate Monster"];
for (let i = 1; i <= 10; i++) {
    addItem(`b-${i}`, `${burgerNames[i-1]} Burger`, 'Delicious premium burger crafted with the finest ingredients.', 800 + (i * 50), 'burgers', `assets/burger/b${i}.png`);
}

// Pizzas
const pizzaFiles = ['p1.jpg', 'p2.jpg', 'p3.jpg', 'p4.jpg', 'p6.jpg', 'p7.jpg', 'p8.jpg', 'p9.png', 'p10.png', 'p11.png'];
const pizzaNames = ["Truffle Mushroom", "Spicy Pepperoni", "Margherita", "BBQ Chicken", "Hawaiian", "Meat Lovers", "Four Cheese", "Buffalo Chicken", "Veggie Supreme", "Garlic Ranch"];
pizzaFiles.forEach((file, index) => {
    addItem(`p-${index}`, `${pizzaNames[index]} Pizza`, 'Freshly baked pizza with premium toppings and gooey mozzarella.', 1200 + (index * 100), 'pizza', `assets/pizza/${file}`);
});

// Shwarma (s1 to s7)
const shwarmaNames = ["Spicy Chicken", "Beef Classic", "Mixed Grill", "Garlic Mayo", "Mexican", "Arabic Style", "Overloaded"];
for (let i = 1; i <= 7; i++) {
    addItem(`s-${i}`, `${shwarmaNames[i-1]} Shwarma`, 'Authentic Middle Eastern flavors wrapped in fresh pita.', 400 + (i * 30), 'shwarma', `assets/shwarma/s${i}.png`);
}

// Sides/Fries (f1 to f5)
const friesNames = ["Loaded Loaded", "Masala Spicy", "Cheese Garlic", "Curly Combo", "Classic Salted"];
for (let i = 1; i <= 5; i++) {
    addItem(`f-${i}`, `${friesNames[i-1]} Fries`, 'Crispy golden fries served hot and fresh.', 300 + (i * 50), 'sides', `assets/fries/f${i}.png`);
}

// Family Deals (fa1 to fa4)
const familyNames = ["Mega Feast", "Family Fiesta", "Jumbo Combo", "Weekend Special"];
for (let i = 1; i <= 4; i++) {
    addItem(`fa-${i}`, `${familyNames[i-1]} Pack`, 'Perfect sizing for the whole family with assorted sides and drinks.', 2500 + (i * 500), 'family', `assets/family/fa${i}.png`);
}

// WhatsApp Number
const WA_NUMBER = '923096795286';

// State
let cart = [];
let discountMultiplier = 1;
let showingAllMenu = false;
let currentCategory = 'all';

// DOM Elements
const navbar = document.getElementById('navbar');
const menuGrid = document.getElementById('menu-grid');
const categoryBtns = document.querySelectorAll('.category-btn');

// Cart DOM
const openCartBtn = document.getElementById('open-cart-btn');
const closeCartBtn = document.getElementById('close-cart-btn');
const cartPanel = document.getElementById('cart-panel');
const cartOverlay = document.getElementById('cart-overlay');
const cartItemsContainer = document.getElementById('cart-items-container');
const cartCount = document.getElementById('cart-count');
const cartTotalPrice = document.getElementById('cart-total-price');
const openCheckoutBtn = document.getElementById('open-checkout-btn');
const cartDeliveryFee = document.getElementById('cart-delivery-fee');
const promoInput = document.getElementById('promo-input');
const applyPromoBtn = document.getElementById('apply-promo-btn');

// Checkout DOM
const checkoutModal = document.getElementById('checkout-modal');
const checkoutModalOverlay = document.getElementById('checkout-modal-overlay');
const closeModalBtn = document.getElementById('close-modal-btn');
const checkoutForm = document.getElementById('checkout-form');
const orderSummaryPreview = document.getElementById('order-summary-preview');
const storeClosedMsg = document.getElementById('store-closed-msg');

// Auth DOM
const openAuthBtn = document.getElementById('open-auth-btn');
const closeAuthBtn = document.getElementById('close-auth-btn');
const authModal = document.getElementById('auth-modal');
const authModalOverlay = document.getElementById('auth-modal-overlay');
const tabLogin = document.getElementById('tab-login');
const tabRegister = document.getElementById('tab-register');
const authNameGroup = document.getElementById('auth-name-group');
const authNameInput = document.getElementById('auth-name');
const authTitle = document.getElementById('auth-modal-title');
const authSubmitBtn = document.getElementById('auth-submit-btn');
const authForm = document.getElementById('auth-form');
let isLoginMode = true;

// See More DOM
const seeMoreContainer = document.getElementById('see-more-container');
const seeMoreBtn = document.getElementById('see-more-btn');

// Toast DOM & Search
const toastContainer = document.getElementById('toast-container');
const menuSearchInput = document.getElementById('menu-search-input');

// --- TOAST NOTIFICATIONS ---
function showToast(message, icon = 'fa-check') {
    const toast = document.createElement('div');
    toast.className = 'toast show';
    toast.innerHTML = `<i class="fas ${icon}"></i> <span>${message}</span>`;
    
    toastContainer.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.replace('show', 'hide');
        setTimeout(() => toast.remove(), 400); // Wait for transition
    }, 3000);
}

// --- TYPEWRITER EFFECT ---
const typewriterElement = document.getElementById('typewriter-text');
const phrases = [
    "Order your favorite meals instantly via WhatsApp.",
    "Fresh, hot, and right to your door."
];
let phraseIndex = 0;
let charIndex = 0;
let isDeleting = false;

function typeWriter() {
    if (!typewriterElement) return;
    const currentPhrase = phrases[phraseIndex];
    
    if (isDeleting) {
        typewriterElement.textContent = currentPhrase.substring(0, charIndex - 1);
        charIndex--;
    } else {
        typewriterElement.textContent = currentPhrase.substring(0, charIndex + 1);
        charIndex++;
    }

    let typeSpeed = isDeleting ? 30 : 60;

    if (!isDeleting && charIndex === currentPhrase.length) {
        typeSpeed = 1300; // 1.3s delay as requested
        isDeleting = true;
    } else if (isDeleting && charIndex === 0) {
        isDeleting = false;
        phraseIndex = (phraseIndex + 1) % phrases.length;
        typeSpeed = 400;
    }

    setTimeout(typeWriter, typeSpeed);
}


// --- PRICE TYPEWRITER EFFECT ---
const priceElements = document.querySelectorAll('.new-price[data-type-price]');
let priceCharIndex = 0;
let isPriceDeleting = false;

function typeWriterPrices() {
    if (priceElements.length === 0) return;
    
    const sampleText = priceElements[0].getAttribute('data-type-price');
    
    priceElements.forEach(el => {
        const text = el.getAttribute('data-type-price');
        if (isPriceDeleting) {
            el.textContent = text.substring(0, priceCharIndex - 1);
        } else {
            el.textContent = text.substring(0, priceCharIndex + 1);
        }
    });

    if (isPriceDeleting) {
        priceCharIndex--;
    } else {
        priceCharIndex++;
    }

    let typeSpeed = isPriceDeleting ? 50 : 100;

    if (!isPriceDeleting && priceCharIndex === sampleText.length) {
        typeSpeed = 3000; // 3 seconds wait time when fully typed
        isPriceDeleting = true;
    } else if (isPriceDeleting && priceCharIndex === 0) {
        isPriceDeleting = false;
        typeSpeed = 500;
    }

    setTimeout(typeWriterPrices, typeSpeed);
}

// --- INITIALIZATION ---
function init() {
    // Service Worker Registration for PWA
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register('./sw.js').catch(err => console.log('SW registration failed: ', err));
        });
    }

    // Load persistent cart
    const savedCart = localStorage.getItem('fastbite_cart');
    if (savedCart) {
        cart = JSON.parse(savedCart);
    }
    
    typeWriter(); // Start typing effect
    typeWriterPrices(); // Start prices typing effect
    renderMenu('all');
    setupEventListeners();
    updateCartUI();
}

// --- NAVBAR SCROLL EFFECT ---
window.addEventListener('scroll', () => {
    if (window.scrollY > 50) {
        navbar.classList.add('scrolled');
    } else {
        navbar.classList.remove('scrolled');
    }
});

// --- MENU RENDER & FILTER ---
function renderMenu(category) {
    currentCategory = category;
    menuGrid.innerHTML = '';
    
    let filteredItems = category === 'all' 
        ? menuItems 
        : menuItems.filter(item => item.category === category);

    if (!showingAllMenu && filteredItems.length > 3) {
        seeMoreContainer.style.display = 'block';
        filteredItems = filteredItems.slice(0, 3);
    } else {
        seeMoreContainer.style.display = 'none';
    }

    renderItems(filteredItems);
}

function renderItems(items) {
    items.forEach(item => {
        const card = document.createElement('div');
        card.className = 'menu-item-card';
        card.innerHTML = `
            <img src="${item.img}" alt="${item.name}" class="menu-item-img">
            <div class="menu-item-details">
                <h3 class="menu-item-title">${item.name}</h3>
                <p class="menu-item-desc">${item.desc}</p>
                <div class="menu-item-bottom">
                    <span class="menu-item-price">Rs ${item.price}</span>
                    <button class="btn btn-primary btn-sm add-to-cart-btn" 
                        data-id="${item.id}" 
                        data-name="${item.name}" 
                        data-price="${item.price}"
                        data-img="${item.img}">
                        <i class="fas fa-plus"></i> Add
                    </button>
                </div>
            </div>
        `;
        menuGrid.appendChild(card);
    });
    attachAddToCartListeners();
}

function attachAddToCartListeners() {
    document.querySelectorAll('.add-to-cart-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = e.currentTarget.dataset.id;
            const name = e.currentTarget.dataset.name;
            const price = parseInt(e.currentTarget.dataset.price);
            const img = e.currentTarget.dataset.img || 'https://via.placeholder.com/60';
            
            addToCart({ id, name, price, img });
        });
    });
}

// --- CART LOGIC ---
function saveCart() {
    localStorage.setItem('fastbite_cart', JSON.stringify(cart));
}

function addToCart(item) {
    const existingItem = cart.find(cartItem => cartItem.id === item.id);
    if (existingItem) {
        existingItem.qty += 1;
    } else {
        cart.push({ ...item, qty: 1 });
    }
    
    showToast(`Added ${item.name} to cart!`);
    updateCartUI();
    
    // Automatically open cart on first add
    if (cart.length === 1 && existingItem === undefined) {
        toggleCart(true);
    }
}

function updateQuantity(id, change) {
    const itemIndex = cart.findIndex(item => item.id === id);
    if (itemIndex > -1) {
        if (change === -999) {
            cart.splice(itemIndex, 1);
            showToast('Item removed', 'fa-trash');
        } else {
            cart[itemIndex].qty += change;
            if (cart[itemIndex].qty <= 0) {
                cart.splice(itemIndex, 1);
                showToast('Item removed', 'fa-trash');
            }
        }
        updateCartUI();
    }
}

function updateCartUI() {
    // Update count
    const totalItems = cart.reduce((sum, item) => sum + item.qty, 0);
    cartCount.textContent = totalItems;
    
    // Update Items display
    if (cart.length === 0) {
        cartItemsContainer.innerHTML = '<div class="empty-cart-msg">Your cart is empty</div>';
        openCheckoutBtn.disabled = true;
        openCheckoutBtn.style.opacity = '0.5';
        openCheckoutBtn.style.cursor = 'not-allowed';
    } else {
        cartItemsContainer.innerHTML = '';
        openCheckoutBtn.disabled = false;
        openCheckoutBtn.style.opacity = '1';
        openCheckoutBtn.style.cursor = 'pointer';
        
        cart.forEach(item => {
            const cartItemEl = document.createElement('div');
            cartItemEl.className = 'cart-item';
            cartItemEl.innerHTML = `
                <img src="${item.img}" alt="${item.name}" class="cart-item-img">
                <div class="cart-item-info">
                    <div class="cart-item-title">${item.name}</div>
                    <div class="cart-item-price">Rs ${item.price * item.qty}</div>
                    <div class="cart-item-controls">
                        <button class="qty-btn" onclick="updateQuantity('${item.id}', -1)">-</button>
                        <span>${item.qty}</span>
                        <button class="qty-btn" onclick="updateQuantity('${item.id}', 1)">+</button>
                    </div>
                </div>
                <button class="remove-item-btn" onclick="updateQuantity('${item.id}', -999)">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            cartItemsContainer.appendChild(cartItemEl);
        });
    }
    
    // Calculate Subtotal & Fees
    let subtotal = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    let deliveryFee = subtotal >= 2000 || subtotal === 0 ? 0 : 150;
    
    let total = (subtotal + deliveryFee) * discountMultiplier;
    
    cartDeliveryFee.textContent = deliveryFee === 0 ? (subtotal === 0 ? 'Rs 0' : 'Free') : `Rs ${deliveryFee}`;
    cartTotalPrice.textContent = `Rs ${Math.floor(total)}`;
    
    saveCart();
}

window.updateQuantity = updateQuantity;

// --- PROMO CODE LOGIC ---
applyPromoBtn.addEventListener('click', () => {
    const code = promoInput.value.trim().toUpperCase();
    if (code === 'FASTBITE10') {
        discountMultiplier = 0.9;
        showToast('Promo applied! 10% off.', 'fa-tags');
    } else {
        discountMultiplier = 1;
        showToast('Invalid promo code.', 'fa-times');
    }
    updateCartUI();
});

// --- UI TOGGLES (Cart & Modal) ---
function toggleCart(show) {
    if (show) {
        cartPanel.classList.add('active');
        cartOverlay.classList.add('active');
        document.body.style.overflow = 'hidden';
    } else {
        cartPanel.classList.remove('active');
        cartOverlay.classList.remove('active');
        document.body.style.overflow = 'auto';
    }
}

function toggleCheckoutModal(show) {
    if (show) {
        if (cart.length === 0) return;
        // 24 Hours Open Flag
        const confirmBtn = document.querySelector('.confirm-order-btn');
        
        storeClosedMsg.style.display = 'none';
        confirmBtn.disabled = false;
        confirmBtn.style.opacity = '1';
        
        let subtotal = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
        let deliveryFee = subtotal >= 2000 ? 0 : 150;
        let total = (subtotal + deliveryFee) * discountMultiplier;
        
        const itemNames = cart.map(i => `${i.qty}x ${i.name}`).join('<br>');
        orderSummaryPreview.innerHTML = `
            <strong>Summary:</strong><br>${itemNames}<br><br>
            Delivery: ${deliveryFee === 0 ? 'Free' : 'Rs ' + deliveryFee}<br>
            <strong>Total: Rs ${Math.floor(total)}</strong>
        `;
        
        checkoutModal.classList.add('active');
        checkoutModalOverlay.classList.add('active');
        toggleCart(false);
        document.body.style.overflow = 'hidden';
    } else {
        checkoutModal.classList.remove('active');
        checkoutModalOverlay.classList.remove('active');
        document.body.style.overflow = 'auto';
    }
}

function setupEventListeners() {
    // Cart & Modal
    openCartBtn.addEventListener('click', () => toggleCart(true));
    closeCartBtn.addEventListener('click', () => toggleCart(false));
    cartOverlay.addEventListener('click', () => toggleCart(false));
    
    openCheckoutBtn.addEventListener('click', () => toggleCheckoutModal(true));
    closeModalBtn.addEventListener('click', () => toggleCheckoutModal(false));
    checkoutModalOverlay.addEventListener('click', () => toggleCheckoutModal(false));
    
    // Category Buttons
    categoryBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            categoryBtns.forEach(b => b.classList.remove('active'));
            e.target.classList.add('active');
            showingAllMenu = false;
            renderMenu(e.target.dataset.category);
        });
    });

    if (seeMoreBtn) {
        seeMoreBtn.addEventListener('click', () => {
            showingAllMenu = true;
            renderMenu(currentCategory);
        });
    }

    // Auth Modal Links & Tabs
    function toggleAuthModal(show) {
        if (show) {
            authModal.classList.add('active');
            authModalOverlay.classList.add('active');
            document.body.style.overflow = 'hidden';
        } else {
            authModal.classList.remove('active');
            authModalOverlay.classList.remove('active');
            document.body.style.overflow = 'auto';
        }
    }

    openAuthBtn.addEventListener('click', () => toggleAuthModal(true));
    closeAuthBtn.addEventListener('click', () => toggleAuthModal(false));
    authModalOverlay.addEventListener('click', () => toggleAuthModal(false));

    function setAuthMode(login) {
        isLoginMode = login;
        if (login) {
            tabLogin.classList.add('active');
            tabLogin.style.background = 'rgba(255, 94, 0, 0.1)';
            tabLogin.style.borderColor = 'var(--accent-orange)';
            tabLogin.style.color = 'var(--accent-orange)';
            
            tabRegister.classList.remove('active');
            tabRegister.style.background = 'transparent';
            tabRegister.style.borderColor = 'var(--glass-border)';
            tabRegister.style.color = 'var(--text-main)';
            
            authNameGroup.style.display = 'none';
            authNameInput.required = false;
            authTitle.innerHTML = 'Sign <span class="accent">In</span>';
            authSubmitBtn.textContent = 'Sign In';
        } else {
            tabRegister.classList.add('active');
            tabRegister.style.background = 'rgba(255, 94, 0, 0.1)';
            tabRegister.style.borderColor = 'var(--accent-orange)';
            tabRegister.style.color = 'var(--accent-orange)';
            
            tabLogin.classList.remove('active');
            tabLogin.style.background = 'transparent';
            tabLogin.style.borderColor = 'var(--glass-border)';
            tabLogin.style.color = 'var(--text-main)';
            
            authNameGroup.style.display = 'block';
            authNameInput.required = true;
            authTitle.innerHTML = 'Create <span class="accent">Account</span>';
            authSubmitBtn.textContent = 'Register';
        }
    }

    tabLogin.addEventListener('click', () => setAuthMode(true));
    tabRegister.addEventListener('click', () => setAuthMode(false));

    authForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const action = isLoginMode ? 'Logged in' : 'Registered';
        showToast(`${action} successfully!`);
        openAuthBtn.innerHTML = '<i class="fas fa-user"></i> Profile';
        toggleAuthModal(false);
    });

    // Live menu search
    menuSearchInput.addEventListener('input', (e) => {
        const term = e.target.value.toLowerCase();
        menuGrid.innerHTML = '';
        const filtered = menuItems.filter(item => 
            item.name.toLowerCase().includes(term) || 
            item.desc.toLowerCase().includes(term)
        );
        
        // Reset categories visual state
        categoryBtns.forEach(b => b.classList.remove('active'));
        document.querySelector('[data-category="all"]').classList.add('active');
        showingAllMenu = true; // Show all results when searching
        
        renderItems(filtered);
        seeMoreContainer.style.display = 'none';
    });
    
    // Deals Add To Cart
    attachAddToCartListeners();
    
    // --- WHATSAPP CHECKOUT LOGIC ---
    checkoutForm.addEventListener('submit', (e) => {
        e.preventDefault();
        if(cart.length === 0) return;
        
        const name = document.getElementById('name').value;
        const phone = document.getElementById('phone').value;
        const address = document.getElementById('address').value;
        
        let orderText = `New Order 🍔\n\n`;
        orderText += `Name: ${name}\n`;
        orderText += `Phone: ${phone}\n`;
        orderText += `Address: ${address}\n\n`;
        orderText += `Order:\n`;
        
        let subtotal = 0;
        cart.forEach(item => {
            orderText += `- ${item.name} x${item.qty}\n`;
            subtotal += (item.price * item.qty);
        });
        
        let deliveryFee = subtotal >= 2000 ? 0 : 150;
        let finalTotal = Math.floor((subtotal + deliveryFee) * discountMultiplier);
        
        orderText += `\nSubtotal: Rs ${subtotal}`;
        orderText += `\nDelivery: ${deliveryFee === 0 ? 'Free' : 'Rs ' + deliveryFee}`;
        if (discountMultiplier < 1) {
            orderText += `\nDiscount: 10%`;
        }
        orderText += `\n*Total: Rs ${finalTotal}*`;
        
        const encodedMessage = encodeURIComponent(orderText);
        const waUrl = `https://wa.me/${WA_NUMBER}?text=${encodedMessage}`;
        
        window.open(waUrl, '_blank');
        
        // Reset form, cart, and state after sending
        checkoutForm.reset();
        cart = [];
        discountMultiplier = 1;
        promoInput.value = '';
        saveCart();
        updateCartUI();
        toggleCheckoutModal(false);
        showToast('Processing order...', 'fa-paper-plane');
    });
}

// Bootstrap
document.addEventListener('DOMContentLoaded', init);
