/**
 * Tap2Order – Customer Menu JavaScript
 * Cart management, menu interactions, checkout
 * Pure vanilla JS – no jQuery required
 */

(function () {
  'use strict';

  /* ===========================================================
     1. State & Configuration
     =========================================================== */
  const CONFIG = {
    currency: 'USD',
    currencySymbol: '$',
    restaurantId: null,
    tableNumber: null,
    orderType: 'dine-in',
    promoCode: null,
    promoDiscount: 0,
    minOrderAmount: 0,
    taxRate: 0,
    deliveryFee: 0,
    advertisementShown: false
  };

  let cart = [];
  let menuData = [];

  /* ===========================================================
     2. DOM Ready
     =========================================================== */
  document.addEventListener('DOMContentLoaded', () => {
    initConfig();
    loadCart();
    renderCartUI();
    initCategoryNav();
    initSearch();
    initOrderType();
    initAdvertisement();
    initSkeletonLoader();
    initLazyLoading();
    initStickyHeader();
    detectTableFromURL();
    bindGlobalEvents();
  });

  /* ===========================================================
     3. Configuration & URL Params
     =========================================================== */
  function initConfig() {
    const el = document.querySelector('[data-config]');
    if (el) {
      try {
        const cfg = JSON.parse(el.dataset.config);
        Object.assign(CONFIG, cfg);
      } catch (e) { /* ignore */ }
    }

    const metaCurrency = document.querySelector('meta[name="currency"]');
    if (metaCurrency) CONFIG.currency = metaCurrency.content;

    const metaSymbol = document.querySelector('meta[name="currency-symbol"]');
    if (metaSymbol) CONFIG.currencySymbol = metaSymbol.content;
  }

  function detectTableFromURL() {
    const params = new URLSearchParams(window.location.search);
    const table = params.get('table') || params.get('t');
    if (table) {
      CONFIG.tableNumber = parseInt(table, 10);
      const tableDisplay = document.querySelector('.table-number-display');
      if (tableDisplay) tableDisplay.textContent = `Table ${CONFIG.tableNumber}`;
    }

    const rid = params.get('restaurant') || params.get('rid');
    if (rid) CONFIG.restaurantId = rid;
  }

  /* ===========================================================
     4. Currency Formatting
     =========================================================== */
  function formatCurrency(amount) {
    const num = parseFloat(amount) || 0;
    const symbols = { USD: '$', EUR: '€', GBP: '£', LKR: 'Rs ', INR: '₹', AED: 'د.إ ', SAR: '﷼ ' };
    const sym = symbols[CONFIG.currency] || CONFIG.currencySymbol;
    return sym + num.toFixed(2);
  }

  /* ===========================================================
     5. Cart Management (localStorage)
     =========================================================== */
  function loadCart() {
    try {
      const stored = localStorage.getItem(`tap2order_cart_${CONFIG.restaurantId || 'default'}`);
      cart = stored ? JSON.parse(stored) : [];
    } catch (e) {
      cart = [];
    }
  }

  function saveCart() {
    try {
      localStorage.setItem(`tap2order_cart_${CONFIG.restaurantId || 'default'}`, JSON.stringify(cart));
    } catch (e) { /* storage full or unavailable */ }
  }

  function clearCart() {
    cart = [];
    saveCart();
    renderCartUI();
    updateFloatingCart();
  }

  function addToCart(item) {
    const existing = cart.find(c =>
      c.id === item.id &&
      c.variation === (item.variation || null) &&
      JSON.stringify(c.addons || []) === JSON.stringify(item.addons || [])
    );

    if (existing) {
      existing.quantity += (item.quantity || 1);
    } else {
      cart.push({
        id: item.id,
        name: item.name,
        image: item.image || '',
        price: item.unitPrice || item.price,
        unitPrice: item.unitPrice || item.price,
        quantity: item.quantity || 1,
        variation: item.variation || null,
        variationLabel: item.variationLabel || '',
        addons: item.addons || [],
        addonTotal: item.addonTotal || 0,
        notes: item.notes || ''
      });
    }

    saveCart();
    renderCartUI();
    updateFloatingCart();
    animateCartButton();
  }

  function removeFromCart(index) {
    cart.splice(index, 1);
    saveCart();
    renderCartUI();
    updateFloatingCart();
  }

  function updateCartItemQty(index, delta) {
    if (!cart[index]) return;
    cart[index].quantity += delta;
    if (cart[index].quantity <= 0) {
      removeFromCart(index);
      return;
    }
    saveCart();
    renderCartUI();
    updateFloatingCart();
  }

  function setCartItemQty(index, qty) {
    if (!cart[index]) return;
    qty = parseInt(qty, 10);
    if (qty <= 0) {
      removeFromCart(index);
      return;
    }
    cart[index].quantity = qty;
    saveCart();
    renderCartUI();
    updateFloatingCart();
  }

  function updateCartItemNotes(index, notes) {
    if (!cart[index]) return;
    cart[index].notes = notes;
    saveCart();
  }

  function getCartTotal() {
    return cart.reduce((sum, item) => {
      const addons = (item.addons || []).reduce((a, ad) => a + (parseFloat(ad.price) || 0), 0);
      return sum + (item.unitPrice + addons) * item.quantity;
    }, 0);
  }

  function getCartItemCount() {
    return cart.reduce((sum, item) => sum + item.quantity, 0);
  }

  function getCartSubtotal() {
    return getCartTotal();
  }

  function getDiscount() {
    return CONFIG.promoDiscount || 0;
  }

  function getTax() {
    return (getCartSubtotal() - getDiscount()) * (CONFIG.taxRate / 100);
  }

  function getDeliveryFee() {
    return CONFIG.orderType === 'delivery' ? CONFIG.deliveryFee : 0;
  }

  function getGrandTotal() {
    return Math.max(0, getCartSubtotal() - getDiscount() + getTax() + getDeliveryFee());
  }

  /* ===========================================================
     6. Cart UI Rendering
     =========================================================== */
  function renderCartUI() {
    const cartItems = document.getElementById('cart-items');
    const cartFooter = document.getElementById('cart-footer');
    const cartCount = document.getElementById('cart-count');
    const cartTotalEl = document.getElementById('cart-total');

    if (cartItems) {
      if (cart.length === 0) {
        cartItems.innerHTML = `
          <div class="cart-empty">
            <i class="fas fa-shopping-cart"></i>
            <p>Your cart is empty</p>
          </div>
        `;
        if (cartFooter) cartFooter.style.display = 'none';
      } else {
        cartItems.innerHTML = cart.map((item, index) => `
          <div class="cart-item" data-index="${index}">
            <img class="cart-item-image" src="${item.image || '/assets/img/placeholder-food.png'}" alt="${item.name}" loading="lazy">
            <div class="cart-item-details">
              <div class="cart-item-name">${escapeHtml(item.name)}</div>
              ${item.variationLabel ? `<div class="cart-item-variation">${escapeHtml(item.variationLabel)}</div>` : ''}
              ${(item.addons && item.addons.length > 0) ? `<div class="cart-item-addons">${item.addons.map(a => escapeHtml(a.name)).join(', ')}</div>` : ''}
              <div class="cart-item-bottom">
                <div class="cart-qty-control">
                  <button class="cart-qty-btn" onclick="MenuApp.updateQty(${index}, -1)">−</button>
                  <span class="cart-qty-value">${item.quantity}</span>
                  <button class="cart-qty-btn" onclick="MenuApp.updateQty(${index}, 1)">+</button>
                </div>
                <span class="cart-item-price">${formatCurrency((item.unitPrice + (item.addonTotal || 0)) * item.quantity)}</span>
                <button class="remove-item" onclick="MenuApp.removeItem(${index})">
                  <i class="fas fa-trash-alt"></i>
                </button>
              </div>
              <div class="cart-item-notes">
                <input type="text" placeholder="Add notes..." value="${escapeHtml(item.notes || '')}"
                  onchange="MenuApp.setItemNotes(${index}, this.value)">
              </div>
            </div>
          </div>
        `).join('');

        if (cartFooter) cartFooter.style.display = 'block';

        // Update summary
        const subtotal = getCartSubtotal();
        const discount = getDiscount();
        const tax = getTax();
        const delivery = getDeliveryFee();
        const total = getGrandTotal();

        updateSummaryRow('subtotal', formatCurrency(subtotal));
        updateSummaryRow('discount', discount > 0 ? '-' + formatCurrency(discount) : null, discount > 0);
        updateSummaryRow('tax', formatCurrency(tax));
        updateSummaryRow('delivery', delivery > 0 ? formatCurrency(delivery) : null, delivery > 0);
        updateSummaryRow('grand-total', formatCurrency(total));
      }
    }

    if (cartCount) {
      const count = getCartItemCount();
      cartCount.textContent = count;
    }

    if (cartTotalEl) {
      cartTotalEl.textContent = formatCurrency(getGrandTotal());
    }
  }

  function updateSummaryRow(id, value, show) {
    const el = document.querySelector(`[data-summary="${id}"]`);
    if (el) {
      if (show === false || value === null) {
        el.style.display = 'none';
      } else {
        el.style.display = 'flex';
        const valueEl = el.querySelector('.summary-value') || el.querySelector('span:last-child');
        if (valueEl) valueEl.textContent = value;
      }
    }
  }

  /* ===========================================================
     7. Floating Cart Button
     =========================================================== */
  function updateFloatingCart() {
    const btn = document.querySelector('.floating-cart-btn');
    if (!btn) return;

    const count = getCartItemCount();
    const total = getGrandTotal();

    if (count > 0) {
      btn.classList.add('show');
      const countEl = btn.querySelector('.cart-count');
      const totalEl = btn.querySelector('.cart-total');
      if (countEl) countEl.textContent = count;
      if (totalEl) totalEl.textContent = formatCurrency(total);
    } else {
      btn.classList.remove('show');
    }
  }

  function animateCartButton() {
    const btn = document.querySelector('.floating-cart-btn');
    if (btn) {
      btn.classList.add('animate-cart-bounce');
      setTimeout(() => btn.classList.remove('animate-cart-bounce'), 300);
    }

    // Flash the add button on the card
    document.querySelectorAll('.food-item-card.added-flash').forEach(el => el.classList.remove('added-flash'));
    setTimeout(() => {
      document.querySelectorAll('.food-item-card:last-child').forEach(el => el.classList.add('added-flash'));
    }, 10);
  }

  /* ===========================================================
     8. Cart Sidebar
     =========================================================== */
  function openCart() {
    document.querySelector('.cart-overlay')?.classList.add('show');
    document.querySelector('.cart-sidebar')?.classList.add('show');
    document.body.style.overflow = 'hidden';
  }

  function closeCart() {
    document.querySelector('.cart-overlay')?.classList.remove('show');
    document.querySelector('.cart-sidebar')?.classList.remove('show');
    document.body.style.overflow = '';
  }

  /* ===========================================================
     9. Item Detail Modal
     =========================================================== */
  function openItemModal(itemId) {
    const item = findMenuItem(itemId);
    if (!item) return;

    const modal = document.getElementById('item-modal');
    if (!modal) return;

    // Populate basic info
    const imageEl = modal.querySelector('.modal-image, .modal-image-placeholder');
    if (imageEl) {
      if (item.image) {
        if (imageEl.tagName === 'IMG') {
          imageEl.src = item.image;
          imageEl.alt = item.name;
        } else {
          imageEl.outerHTML = `<img class="modal-image" src="${item.image}" alt="${item.name}">`;
        }
      }
    }

    setTextSafe(modal.querySelector('.modal-item-name'), item.name);
    setTextSafe(modal.querySelector('.modal-item-desc'), item.description || '');
    setTextSafe(modal.querySelector('.modal-item-price'), formatCurrency(item.price));

    // Variations
    const variationContainer = modal.querySelector('.variation-options');
    if (variationContainer) {
      if (item.variations && item.variations.length > 0) {
        variationContainer.innerHTML = item.variations.map((v, i) => `
          <label class="variation-option">
            <input type="radio" name="variation" value="${v.id}" ${i === 0 ? 'checked' : ''}
              data-price="${v.price || 0}" data-label="${escapeHtml(v.name)}">
            <span class="variation-name">${escapeHtml(v.name)}</span>
            <span class="variation-price">${v.price ? '+' + formatCurrency(v.price) : ''}</span>
          </label>
        `).join('');
      } else {
        const section = variationContainer.closest('.modal-section');
        if (section) section.style.display = 'none';
      }
    }

    // Add-ons
    const addonContainer = modal.querySelector('.addon-options');
    if (addonContainer) {
      if (item.addons && item.addons.length > 0) {
        addonContainer.innerHTML = item.addons.map(a => `
          <label class="addon-option">
            <input type="checkbox" name="addons" value="${a.id}"
              data-price="${a.price || 0}" data-name="${escapeHtml(a.name)}">
            <span class="addon-name">${escapeHtml(a.name)}</span>
            <span class="addon-price">${a.price ? '+' + formatCurrency(a.price) : ''}</span>
          </label>
        `).join('');
      } else {
        const section = addonContainer.closest('.modal-section');
        if (section) section.style.display = 'none';
      }
    }

    // Reset quantity
    const qtyEl = modal.querySelector('.modal-qty-value');
    if (qtyEl) qtyEl.textContent = '1';

    // Reset notes
    const notesEl = modal.querySelector('.modal-notes textarea');
    if (notesEl) notesEl.value = '';

    // Set item id
    modal.dataset.itemId = item.id;
    modal.dataset.basePrice = item.price;

    // Show
    modal.classList.add('show');

    // Re-show hidden sections
    modal.querySelectorAll('.modal-section').forEach(s => s.style.display = '');
  }

  function closeItemModal() {
    const modal = document.getElementById('item-modal');
    if (modal) modal.classList.remove('show');
  }

  function addItemFromModal() {
    const modal = document.getElementById('item-modal');
    if (!modal) return;

    const itemId = modal.dataset.itemId;
    const basePrice = parseFloat(modal.dataset.basePrice) || 0;

    // Get variation
    const variationRadio = modal.querySelector('input[name="variation"]:checked');
    const variationPrice = variationRadio ? parseFloat(variationRadio.dataset.price) || 0 : 0;
    const variationId = variationRadio ? variationRadio.value : null;
    const variationLabel = variationRadio ? variationRadio.dataset.label : '';

    // Get add-ons
    const addonCheckboxes = modal.querySelectorAll('input[name="addons"]:checked');
    const addons = [];
    let addonTotal = 0;
    addonCheckboxes.forEach(cb => {
      const price = parseFloat(cb.dataset.price) || 0;
      addonTotal += price;
      addons.push({ id: cb.value, name: cb.dataset.name, price: price });
    });

    // Get quantity
    const qtyEl = modal.querySelector('.modal-qty-value');
    const quantity = qtyEl ? parseInt(qtyEl.textContent, 10) || 1 : 1;

    // Get notes
    const notesEl = modal.querySelector('.modal-notes textarea');
    const notes = notesEl ? notesEl.value.trim() : '';

    // Find item details
    const item = findMenuItem(itemId);
    const unitPrice = basePrice + variationPrice;

    addToCart({
      id: itemId,
      name: item ? item.name : 'Item',
      image: item ? item.image : '',
      price: unitPrice,
      unitPrice: unitPrice,
      quantity: quantity,
      variation: variationId,
      variationLabel: variationLabel,
      addons: addons,
      addonTotal: addonTotal,
      notes: notes
    });

    closeItemModal();
  }

  /* ===========================================================
     10. Quantity Controls
     =========================================================== */
  function modalQtyChange(delta) {
    const modal = document.getElementById('item-modal');
    if (!modal) return;
    const qtyEl = modal.querySelector('.modal-qty-value');
    if (!qtyEl) return;

    let qty = parseInt(qtyEl.textContent, 10) || 1;
    qty = Math.max(1, qty + delta);
    qtyEl.textContent = qty;
  }

  /* ===========================================================
     11. Quick Add to Cart (no modal)
     =========================================================== */
  function quickAdd(itemId) {
    const item = findMenuItem(itemId);
    if (!item) return;

    // If item has variations or addons, open modal instead
    if ((item.variations && item.variations.length > 0) || (item.addons && item.addons.length > 0)) {
      openItemModal(itemId);
      return;
    }

    addToCart({
      id: item.id,
      name: item.name,
      image: item.image || '',
      price: item.price,
      unitPrice: item.price,
      quantity: 1,
      variation: null,
      variationLabel: '',
      addons: [],
      addonTotal: 0,
      notes: ''
    });
  }

  /* ===========================================================
     12. Menu Item Lookup
     =========================================================== */
  function findMenuItem(id) {
    // Try from embedded menu data
    const idStr = String(id);
    for (const item of menuData) {
      if (String(item.id) === idStr) return item;
    }

    // Try from DOM
    const el = document.querySelector(`[data-item-id="${id}"]`);
    if (el) {
      return {
        id: el.dataset.itemId,
        name: el.dataset.itemName || el.querySelector('.item-name')?.textContent || 'Item',
        price: parseFloat(el.dataset.itemPrice) || 0,
        image: el.dataset.itemImage || '',
        description: el.dataset.itemDesc || '',
        variations: parseJSON(el.dataset.variations),
        addons: parseJSON(el.dataset.addons)
      };
    }

    return null;
  }

  function parseJSON(str) {
    try { return JSON.parse(str || '[]'); }
    catch (e) { return []; }
  }

  /* ===========================================================
     13. Category Navigation (Sticky)
     =========================================================== */
  function initCategoryNav() {
    const nav = document.querySelector('.category-nav');
    if (!nav) return;

    nav.querySelectorAll('.category-pill').forEach(pill => {
      pill.addEventListener('click', (e) => {
        e.preventDefault();
        const targetId = pill.dataset.category;
        const section = document.getElementById(`category-${targetId}`);
        if (section) {
          const offset = document.querySelector('.menu-header')?.offsetHeight || 56;
          const catBarHeight = nav.offsetHeight || 50;
          const top = section.getBoundingClientRect().top + window.pageYOffset - offset - catBarHeight;
          window.scrollTo({ top, behavior: 'smooth' });
        }

        nav.querySelectorAll('.category-pill').forEach(p => p.classList.remove('active'));
        pill.classList.add('active');
      });
    });

    // Scroll spy
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const catId = entry.target.id.replace('category-', '');
          nav.querySelectorAll('.category-pill').forEach(p => {
            p.classList.toggle('active', p.dataset.category === catId);
          });
        }
      });
    }, { rootMargin: '-100px 0px -60% 0px' });

    document.querySelectorAll('.menu-category-section[id]').forEach(section => {
      observer.observe(section);
    });
  }

  /* ===========================================================
     14. Search Functionality
     =========================================================== */
  function initSearch() {
    const input = document.querySelector('.search-bar input');
    const clearBtn = document.querySelector('.clear-search');
    const resultsInfo = document.querySelector('.search-results-info');
    if (!input) return;

    let debounceTimer;

    input.addEventListener('input', function () {
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => {
        const query = this.value.toLowerCase().trim();

        if (clearBtn) clearBtn.classList.toggle('show', query.length > 0);

        const items = document.querySelectorAll('.food-item-card');
        let visibleCount = 0;

        items.forEach(card => {
          const name = (card.dataset.itemName || card.querySelector('.item-name')?.textContent || '').toLowerCase();
          const desc = (card.dataset.itemDesc || card.querySelector('.item-description')?.textContent || '').toLowerCase();
          const match = !query || name.includes(query) || desc.includes(query);
          card.style.display = match ? '' : 'none';
          if (match) visibleCount++;
        });

        // Show/hide empty categories
        document.querySelectorAll('.menu-category-section').forEach(section => {
          const visibleItems = section.querySelectorAll('.food-item-card:not([style*="display: none"])');
          section.style.display = visibleItems.length > 0 ? '' : 'none';
        });

        if (resultsInfo) {
          if (query) {
            resultsInfo.textContent = `Found ${visibleCount} item${visibleCount !== 1 ? 's' : ''} for "${input.value}"`;
            resultsInfo.classList.add('show');
          } else {
            resultsInfo.classList.remove('show');
          }
        }
      }, 250);
    });

    if (clearBtn) {
      clearBtn.addEventListener('click', () => {
        input.value = '';
        input.dispatchEvent(new Event('input'));
        input.focus();
      });
    }
  }

  /* ===========================================================
     15. Order Type Selection
     =========================================================== */
  function initOrderType() {
    document.querySelectorAll('.order-type-btn').forEach(btn => {
      btn.addEventListener('click', function () {
        document.querySelectorAll('.order-type-btn').forEach(b => b.classList.remove('active'));
        this.classList.add('active');
        CONFIG.orderType = this.dataset.type || 'dine-in';
        updateFloatingCart();
      });
    });
  }

  /* ===========================================================
     16. Checkout Handling
     =========================================================== */
  function openCheckout() {
    if (cart.length === 0) {
      showToast('Your cart is empty', 'warning');
      return;
    }

    if (CONFIG.minOrderAmount > 0 && getCartSubtotal() < CONFIG.minOrderAmount) {
      showToast(`Minimum order amount is ${formatCurrency(CONFIG.minOrderAmount)}`, 'warning');
      return;
    }

    const overlay = document.getElementById('checkout-overlay');
    if (overlay) {
      // Fill summary
      const totalEl = overlay.querySelector('.checkout-total');
      if (totalEl) totalEl.textContent = formatCurrency(getGrandTotal());

      const countEl = overlay.querySelector('.checkout-item-count');
      if (countEl) countEl.textContent = `${getCartItemCount()} item(s)`;

      if (CONFIG.tableNumber) {
        const tableInput = overlay.querySelector('input[name="table_number"]');
        if (tableInput) tableInput.value = CONFIG.tableNumber;
      }

      overlay.classList.add('show');
      document.body.style.overflow = 'hidden';
    }
  }

  function closeCheckout() {
    const overlay = document.getElementById('checkout-overlay');
    if (overlay) {
      overlay.classList.remove('show');
      document.body.style.overflow = '';
    }
  }

  function placeOrder() {
    const form = document.querySelector('#checkout-form');
    if (!form) return;

    const customerName = form.querySelector('input[name="customer_name"]')?.value.trim();
    const phone = form.querySelector('input[name="customer_phone"]')?.value.trim();
    const notes = form.querySelector('textarea[name="order_notes"]')?.value.trim();

    if (!customerName) {
      showToast('Please enter your name', 'warning');
      return;
    }

    if (!phone) {
      showToast('Please enter your phone number', 'warning');
      return;
    }

    const orderData = {
      restaurant_id: CONFIG.restaurantId,
      table_id: CONFIG.tableNumber,
      order_type: CONFIG.orderType,
      customer_name: customerName,
      customer_phone: phone,
      order_notes: notes,
      promo_code: CONFIG.promoCode,
      csrf_token: getCsrfToken(),
      items: cart.map(item => ({
        menu_item_id: item.id,
        name: item.name,
        quantity: item.quantity,
        unit_price: item.unitPrice,
        variation_id: item.variation?.id || 0,
        addon_ids: (item.addons || []).map(a => a.id || a),
        item_notes: item.notes || ''
      }))
    };

    const btn = form.querySelector('.place-order-btn');
    if (btn) {
      btn.disabled = true;
      btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Placing Order...';
    }

    fetch(CONFIG.baseUrl + '/ajax/place_order.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      credentials: 'same-origin',
      body: JSON.stringify(orderData)
    })
      .then(response => response.json())
      .then(data => {
        if (data.success || data.order_id) {
          clearCart();
          closeCheckout();
          showOrderConfirmation(data);
        } else {
          showToast(data.message || 'Failed to place order', 'error');
          if (btn) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check"></i> Place Order';
          }
        }
      })
      .catch(error => {
        showToast('Network error. Please try again.', 'error');
        if (btn) {
          btn.disabled = false;
          btn.innerHTML = '<i class="fas fa-check"></i> Place Order';
        }
      });
  }

  /* ===========================================================
     17. Order Confirmation
     =========================================================== */
  function showOrderConfirmation(data) {
    const confirmEl = document.getElementById('order-confirmation');
    if (!confirmEl) return;

    const orderIdEl = confirmEl.querySelector('.confirmation-order-id');
    if (orderIdEl) orderIdEl.textContent = `Order #${data.order_id || data.order?.id || ''}`;

    confirmEl.classList.add('show');
    document.body.style.overflow = 'hidden';

    // Start polling for order status
    if (data.order_id || data.order?.id) {
      startOrderStatusTracker(data.order_id || data.order.id);
    }
  }

  function closeConfirmation() {
    const el = document.getElementById('order-confirmation');
    if (el) {
      el.classList.remove('show');
      document.body.style.overflow = '';
    }
  }

  function newOrder() {
    closeConfirmation();
    window.location.reload();
  }

  /* ===========================================================
     18. Order Status Tracker
     =========================================================== */
  function startOrderStatusTracker(orderId) {
    const tracker = document.querySelector('.order-status-bar');
    if (!tracker) return;

    const pollInterval = setInterval(() => {
      fetch(`/api/orders/${orderId}/status`, {
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        credentials: 'same-origin'
      })
        .then(r => r.json())
        .then(data => {
          if (data.status) {
            updateStatusUI(data.status);
            if (['served', 'completed', 'cancelled'].includes(data.status)) {
              clearInterval(pollInterval);
            }
          }
        })
        .catch(() => {});
    }, 10000);

    // Cleanup after 30 minutes
    setTimeout(() => clearInterval(pollInterval), 1800000);
  }

  function updateStatusUI(status) {
    const steps = document.querySelectorAll('.status-step');
    const statusOrder = ['pending', 'confirmed', 'preparing', 'ready', 'served'];
    const currentIndex = statusOrder.indexOf(status);

    steps.forEach((step, i) => {
      step.classList.remove('active', 'completed');
      if (i < currentIndex) step.classList.add('completed');
      else if (i === currentIndex) step.classList.add('active');
    });
  }

  /* ===========================================================
     19. Promo Code Application
     =========================================================== */
  function applyPromoCode() {
    const input = document.querySelector('.promo-input-group input');
    if (!input || !input.value.trim()) {
      showToast('Please enter a promo code', 'warning');
      return;
    }

    const code = input.value.trim();
    const btn = input.nextElementSibling;
    if (btn) {
      btn.disabled = true;
      btn.textContent = '...';
    }

    fetch('/api/promo/validate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-CSRF-TOKEN': getCsrfToken(),
        'X-Requested-With': 'XMLHttpRequest'
      },
      credentials: 'same-origin',
      body: JSON.stringify({
        code: code,
        subtotal: getCartSubtotal(),
        restaurant_id: CONFIG.restaurantId
      })
    })
      .then(r => r.json())
      .then(data => {
        if (data.valid) {
          CONFIG.promoCode = code;
          CONFIG.promoDiscount = parseFloat(data.discount) || 0;
          showToast(`Promo applied! You save ${formatCurrency(CONFIG.promoDiscount)}`, 'success');
          renderCartUI();
          input.disabled = true;
        } else {
          showToast(data.message || 'Invalid promo code', 'error');
          CONFIG.promoCode = null;
          CONFIG.promoDiscount = 0;
        }
      })
      .catch(() => {
        showToast('Failed to validate promo code', 'error');
      })
      .finally(() => {
        if (btn) {
          btn.disabled = false;
          btn.textContent = 'Apply';
        }
      });
  }

  /* ===========================================================
     20. Advertisement Handling
     =========================================================== */
  function initAdvertisement() {
    // Check if already shown this session
    if (sessionStorage.getItem('tap2order_ad_shown')) return;

    const popup = document.getElementById('offer-popup');
    if (!popup) return;

    // Show after 3 seconds
    setTimeout(() => {
      popup.classList.add('show');
      sessionStorage.setItem('tap2order_ad_shown', '1');
    }, 3000);

    // Close button
    popup.querySelector('.close-popup')?.addEventListener('click', () => {
      popup.classList.remove('show');
    });

    popup.addEventListener('click', (e) => {
      if (e.target === popup) popup.classList.remove('show');
    });

    // Bottom sticky banner
    const bottomBanner = document.querySelector('.offer-banner-bottom');
    if (bottomBanner) {
      setTimeout(() => {
        bottomBanner.classList.add('show');
      }, 5000);
    }
  }

  /* ===========================================================
     21. Advertisement Slider
     =========================================================== */
  function initAdSlider() {
    const slider = document.querySelector('.ad-slider');
    if (!slider) return;

    const track = slider.querySelector('.ad-slider-track');
    const dots = slider.querySelectorAll('.ad-dot');
    const slides = slider.querySelectorAll('.ad-slide');
    if (!track || slides.length === 0) return;

    let currentSlide = 0;
    let autoSlideTimer;

    function goToSlide(index) {
      currentSlide = index;
      track.style.transform = `translateX(-${index * 100}%)`;
      dots.forEach((dot, i) => dot.classList.toggle('active', i === index));
    }

    function nextSlide() {
      goToSlide((currentSlide + 1) % slides.length);
    }

    dots.forEach((dot, i) => {
      dot.addEventListener('click', () => {
        clearInterval(autoSlideTimer);
        goToSlide(i);
        autoSlideTimer = setInterval(nextSlide, 5000);
      });
    });

    autoSlideTimer = setInterval(nextSlide, 5000);
  }

  /* ===========================================================
     22. Skeleton Loader
     =========================================================== */
  function initSkeletonLoader() {
    const skeletons = document.querySelectorAll('.skeleton-card');
    if (skeletons.length === 0) return;

    // Hide skeletons when content is loaded
    window.addEventListener('load', () => {
      setTimeout(() => {
        skeletons.forEach(skeleton => {
          skeleton.style.opacity = '0';
          skeleton.style.transition = 'opacity 0.3s ease';
          setTimeout(() => skeleton.remove(), 300);
        });
      }, 500);
    });
  }

  /* ===========================================================
     23. Lazy Loading Images
     =========================================================== */
  function initLazyLoading() {
    if ('loading' in HTMLImageElement.prototype) return;

    const images = document.querySelectorAll('img[loading="lazy"]');
    if ('IntersectionObserver' in window) {
      const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            const img = entry.target;
            if (img.dataset.src) {
              img.src = img.dataset.src;
              img.removeAttribute('data-src');
            }
            imageObserver.unobserve(img);
          }
        });
      });

      images.forEach(img => imageObserver.observe(img));
    }
  }

  /* ===========================================================
     24. Sticky Header Behavior
     =========================================================== */
  function initStickyHeader() {
    const header = document.querySelector('.menu-header');
    if (!header) return;

    let lastScroll = 0;
    window.addEventListener('scroll', () => {
      const currentScroll = window.pageYOffset;
      header.classList.toggle('scrolled', currentScroll > 20);
      lastScroll = currentScroll;
    }, { passive: true });
  }

  /* ===========================================================
     25. WhatsApp Redirect
     =========================================================== */
  function openWhatsApp() {
    const phone = document.querySelector('[data-whatsapp-phone]')?.dataset.whatsappPhone || '';
    const text = encodeURIComponent(`Hi! I'd like to place an order.`);
    window.open(`https://wa.me/${phone}?text=${text}`, '_blank');
  }

  /* ===========================================================
     26. Get Directions Link
     =========================================================== */
  function getDirections() {
    const lat = document.querySelector('[data-lat]')?.dataset.lat;
    const lng = document.querySelector('[data-lng]')?.dataset.lng;
    if (lat && lng) {
      window.open(`https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`, '_blank');
    } else {
      const address = document.querySelector('[data-address]')?.dataset.address || '';
      if (address) {
        window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(address)}`, '_blank');
      }
    }
  }

  /* ===========================================================
     27. Session Analytics Tracking
     =========================================================== */
  function trackEvent(category, action, label) {
    if (typeof gtag === 'function') {
      gtag('event', action, { event_category: category, event_label: label });
    }

    // Send to internal analytics
    try {
      navigator.sendBeacon('/api/analytics', JSON.stringify({
        category, action, label,
        page: window.location.pathname,
        timestamp: Date.now(),
        session_id: getSessionId()
      }));
    } catch (e) { /* ignore */ }
  }

  function getSessionId() {
    let id = sessionStorage.getItem('tap2order_session');
    if (!id) {
      id = 'sess_' + Math.random().toString(36).substr(2, 12);
      sessionStorage.setItem('tap2order_session', id);
    }
    return id;
  }

  /* ===========================================================
     28. Responsive Menu Toggle
     =========================================================== */
  function toggleMobileMenu() {
    const nav = document.querySelector('.category-nav');
    if (nav) nav.classList.toggle('expanded');
  }

  /* ===========================================================
     29. Utility Functions
     =========================================================== */
  function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }

  function setTextSafe(el, text) {
    if (el) el.textContent = text;
  }

  function getCsrfToken() {
    const meta = document.querySelector('meta[name="csrf-token"]');
    return meta ? meta.getAttribute('content') : '';
  }

  function showToast(message, type = 'info') {
    const container = document.getElementById('toast-container') || createToastContainer();

    const icons = { success: 'fas fa-check-circle', error: 'fas fa-times-circle', warning: 'fas fa-exclamation-triangle', info: 'fas fa-info-circle' };

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.style.cssText = 'min-width:280px;max-width:400px;padding:12px 16px;background:#fff;border-radius:10px;box-shadow:0 4px 20px rgba(0,0,0,0.15);border-left:4px solid ' + getTypeColor(type) + ';display:flex;align-items:center;gap:10px;margin-bottom:8px;animation:toastSlideIn 0.3s ease;font-size:0.85rem;font-family:var(--rest-font);pointer-events:auto;';
    toast.innerHTML = `<i class="${icons[type] || icons.info}" style="color:${getTypeColor(type)};font-size:1rem;"></i><span style="flex:1;color:#333;">${escapeHtml(message)}</span><button style="background:none;border:none;color:#aaa;cursor:pointer;font-size:1rem;padding:0;" onclick="this.parentElement.remove()">&times;</button>`;

    container.appendChild(toast);
    setTimeout(() => {
      if (toast.parentElement) {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(40px)';
        toast.style.transition = 'all 0.3s ease';
        setTimeout(() => toast.remove(), 300);
      }
    }, 3500);
  }

  function createToastContainer() {
    const c = document.createElement('div');
    c.id = 'toast-container';
    c.style.cssText = 'position:fixed;top:72px;right:16px;z-index:9999;display:flex;flex-direction:column;gap:4px;pointer-events:none;';
    document.body.appendChild(c);
    return c;
  }

  function getTypeColor(type) {
    const colors = { success: '#27ae60', error: '#e74c3c', warning: '#f39c12', info: '#3498db' };
    return colors[type] || colors.info;
  }

  /* ===========================================================
     30. Global Event Bindings
     =========================================================== */
  function bindGlobalEvents() {
    // Floating cart button click
    document.querySelector('.floating-cart-btn')?.addEventListener('click', openCart);

    // Close cart
    document.querySelector('.cart-overlay')?.addEventListener('click', closeCart);
    document.querySelector('.close-cart')?.addEventListener('click', closeCart);

    // Item modal close
    document.querySelector('#item-modal .modal-close')?.addEventListener('click', closeItemModal);
    document.getElementById('item-modal')?.addEventListener('click', (e) => {
      if (e.target.id === 'item-modal') closeItemModal();
    });

    // Checkout
    document.querySelector('.checkout-btn')?.addEventListener('click', openCheckout);
    document.querySelector('#checkout-overlay')?.addEventListener('click', (e) => {
      if (e.target.id === 'checkout-overlay') closeCheckout();
    });

    // Place order
    document.querySelector('.place-order-btn')?.addEventListener('click', placeOrder);

    // Promo code
    document.querySelector('.promo-input-group button')?.addEventListener('click', applyPromoCode);

    // Init ad slider
    initAdSlider();

    // Menu data from page
    const dataEl = document.querySelector('[data-menu-items]');
    if (dataEl) {
      try { menuData = JSON.parse(dataEl.dataset.menuItems); }
      catch (e) { menuData = []; }
    }
  }

  /* ===========================================================
     31. Public API
     =========================================================== */
  window.MenuApp = {
    addToCart: quickAdd,
    openItemModal,
    openCart,
    closeCart,
    updateQty: updateCartItemQty,
    removeItem: removeFromCart,
    setItemNotes: updateCartItemNotes,
    modalQtyChange,
    addItemFromModal,
    openCheckout,
    closeCheckout,
    placeOrder,
    applyPromoCode,
    clearCart,
    openWhatsApp,
    getDirections,
    closeConfirmation,
    newOrder,
    trackEvent,
    getCart: () => cart,
    getCartTotal: getGrandTotal,
    getCartCount: getCartItemCount,
    getConfig: () => ({ ...CONFIG })
  };

})();
