// Mobile sidebar toggle
const sidebar = document.getElementById('sidebar');
const hamburger = document.getElementById('hamburger');
if (hamburger && sidebar) {
  hamburger.addEventListener('click', () => {
    const expanded = hamburger.getAttribute('aria-expanded') === 'true';
    hamburger.setAttribute('aria-expanded', String(!expanded));
    sidebar.classList.toggle('open');
  });
}

// Simple client-side table search
const search = document.getElementById('tableSearch');
const table = document.getElementById('ordersTable');
if (search && table) {
  search.addEventListener('input', () => {
    const q = search.value.toLowerCase();
    [...table.querySelectorAll('tbody tr')].forEach(tr => {
      const text = tr.innerText.toLowerCase();
      tr.style.display = text.includes(q) ? '' : 'none';
    });
  });
}

//============================================================================================================================

// cart toggle open/close
document.querySelectorAll('#cart-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
        e.preventDefault();
        document.getElementById('cart-container').classList.add('active');
    });
});
document.getElementById('close-cart').addEventListener('click', () => {
    document.getElementById('cart-container').classList.remove('active');
});
// cart toggle open/close

let cart = JSON.parse(localStorage.getItem('cart')) || [];

function updateCartUI() {
    const badgeEls = document.querySelectorAll('#cart-count-mobile, #cart-count-desktop');
    const cartItemsContainer = document.getElementById('cart-items');
    const subtotalEl = document.getElementById('cart-subtotal');
    const taxEl = document.getElementById('cart-tax'); 
    const totalEl = document.getElementById('cart-total');

    // Defensive checks
    if (!cartItemsContainer || !subtotalEl || !taxEl || !totalEl) {
        console.error("Cart UI elements are missing from the DOM.");
        return;
    }

    // Update badge
    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
    badgeEls.forEach(b => {
        if (b) {
            b.textContent = totalItems;
            b.style.display = totalItems > 0 ? 'inline-block' : 'none';
        }
    });

    // Render cart items
    cartItemsContainer.innerHTML = '';
    let subtotal = 0;
    cart.forEach((item, index) => {
        subtotal += item.price * item.quantity;

        const div = document.createElement('div');
        div.classList.add('box');
        div.innerHTML = `
            <i class="bx bx-trash remove-item" data-index="${index}"></i>
            <img src="${item.image}" alt="${item.name}">
            <div class="content">
                <h3>${item.name}</h3>
                <span class="price">₹${item.price.toFixed(2)}</span>
                <span class="quantity">Qty: ${item.quantity}</span>
            </div>
        `;
        cartItemsContainer.appendChild(div);
    });

    // Totals
    const tax = subtotal * 0.18; // 18%
    const total = subtotal + tax;

    subtotalEl.textContent = `₹${subtotal.toFixed(2)}`;
    taxEl.textContent = `₹${tax.toFixed(2)}`;
    totalEl.textContent = `₹${total.toFixed(2)}`;

    // Save cart to localStorage
    localStorage.setItem('cart', JSON.stringify(cart));

    // Attach remove handlers
    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', () => {
            const index = parseInt(btn.dataset.index);
            if (!isNaN(index)) {
                cart.splice(index, 1);
                updateCartUI();
            }
        });
    });
}

// Handle add-to-cart and quantity change
document.querySelectorAll('.item').forEach(item => {
    const plusBtn = item.querySelector('.plus');
    const minusBtn = item.querySelector('.minus');
    const qtyDisplay = item.querySelector('.qty-number');
    const addBtn = item.querySelector('.add-to-cart');

    if (!plusBtn || !minusBtn || !qtyDisplay || !addBtn) {
        console.warn("Some required elements are missing in .item");
        return;
    }

    let quantity = 1;
    qtyDisplay.textContent = quantity;

    plusBtn.addEventListener('click', () => {
        quantity++;
        qtyDisplay.textContent = quantity;
    });

    minusBtn.addEventListener('click', () => {
        if (quantity > 1) {
            quantity--;
            qtyDisplay.textContent = quantity;
        }
    });

    addBtn.addEventListener('click', (e) => {
        e.preventDefault();

        const nameEl = item.querySelector('.menu-title');
        const priceEl = item.querySelector('h4');
        const imgEl = item.querySelector('img');

        if (!nameEl || !priceEl || !imgEl) {
            console.error("Missing item info");
            return;
        }

        const name = nameEl.textContent.trim();
        const price = parseFloat(priceEl.textContent.replace('Price : ₹', '').trim());
        const image = imgEl.getAttribute('src');

        if (!name || isNaN(price)) {
            console.error("Invalid name or price");
            return;
        }

        const existing = cart.find(p => p.name === name);
        if (existing) {
            existing.quantity += quantity;
        } else {
            cart.push({ name, price, image, quantity });
        }

        // Reset quantity
        quantity = 1;
        qtyDisplay.textContent = quantity;

        updateCartUI();
    });
});

// Initialize cart on page load
updateCartUI();













