// Smooth scrolling for anchor links document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); }); }); function addToCart(name, price, quantityId) { const quantityInput = document.getElementById(quantityId); const quantity = parseInt(quantityInput.value, 10); if (quantity < 1) { alert("Quantity must be at least 1."); return; } let cart = JSON.parse(localStorage.getItem('cart')) || {}; if (cart[name]) { cart[name].quantity += quantity; } else { cart[name] = { price: price, quantity: quantity }; } localStorage.setItem('cart', JSON.stringify(cart)); updateCartCount(); updateButtonStates(); } function updateCartCount() { let cart = JSON.parse(localStorage.getItem('cart')) || {}; let count = Object.values(cart).reduce((sum, item) => sum + item.quantity, 0); const cartCountElement = document.getElementById('cart-count'); if (cartCountElement) { cartCountElement.innerText = count; } } function updateButtonStates() { let cart = JSON.parse(localStorage.getItem('cart')) || {}; const buttons = document.querySelectorAll('.buy-button'); buttons.forEach(button => { const productName = button.getAttribute('data-product-name'); if (cart[productName]) { button.textContent = 'In the cart'; button.disabled = true; } else { button.textContent = 'Buy'; button.disabled = false; } }); } function renderCart() { const cartContainer = document.getElementById('cart-container'); if (!cartContainer) return; let cart = JSON.parse(localStorage.getItem('cart')) || {}; if (Object.keys(cart).length === 0) { cartContainer.innerHTML = `

Your cart is currently empty.

Continue Shopping
`; return; } let table = `
`; let grandTotal = 0; for (const name in cart) { const item = cart[name]; const total = item.price * item.quantity; grandTotal += total; table += ` `; } table += `
Item Price Quantity Total
${name} ${item.price.toFixed(2)} ${total.toFixed(2)}

Grand Total: ${grandTotal.toFixed(2)}

Proceed to Checkout
`; cartContainer.innerHTML = table; } function updateQuantity(name, newQuantity) { let cart = JSON.parse(localStorage.getItem('cart')) || {}; const quantity = parseInt(newQuantity, 10); if (quantity > 0) { cart[name].quantity = quantity; } else { delete cart[name]; } localStorage.setItem('cart', JSON.stringify(cart)); renderCart(); updateCartCount(); updateButtonStates(); } function removeFromCart(name) { let cart = JSON.parse(localStorage.getItem('cart')) || {}; if (cart[name]) { delete cart[name]; } localStorage.setItem('cart', JSON.stringify(cart)); renderCart(); updateCartCount(); updateButtonStates(); // This is the key change } // Update cart count on page load document.addEventListener('DOMContentLoaded', () => { updateCartCount(); updateButtonStates(); renderCart(); // To render cart on cart page });