
const AddtoCart = document.querySelectorAll(".add-to-cart-btn");
const cartContainer = document.getElementById("cart-container");
const cartQuantity=document.getElementById("card-quantity");
// Add to cart
AddtoCart.forEach(btn => {
    btn.addEventListener("click", () => {


        let cart = JSON.parse(localStorage.getItem("cart")) || [];
        cartQuantity.innerHTML=cart.length;
        let product = {
            id: btn.dataset.id,
            name: btn.dataset.name,
            price: Number(btn.dataset.price),
            quantity: 1
        };

        let exists = cart.find(item => item.id === product.id);

        if (!exists) {
            cart.push(product);
        } else {
            // Increase quantity if already in cart
            exists.quantity += 1;
        }

        localStorage.setItem("cart", JSON.stringify(cart));
        renderCart();
    });
});

// Remove item
function removeItem(btn) {
    let cart = JSON.parse(localStorage.getItem("cart")) || [];
    const itemDiv = btn.closest(".cart-item");
    const itemName = itemDiv.querySelector(".fw-semibold").textContent;
    cart = cart.filter(item => item.name !== itemName);
    localStorage.setItem("cart", JSON.stringify(cart));
    renderCart();
}

// Render cart
function renderCart() {
    let cart = JSON.parse(localStorage.getItem("cart")) || [];
    cartContainer.innerHTML = "";

    if (cart.length === 0) {
        cartContainer.innerHTML = `<div id="emptyCartMessageContainer"  class="d-flex my-5 poppins flex-column justify-content-center align-items-center text-center" style="height: 100%; display: none;">
                <div>
                    <i class="fa-solid fa-cart-shopping fa-3x mb-3 text-secondary"></i>
                    <h5 class="fw-semibold">Your Cart is Empty</h5>
                    <p class="text-muted">Fill your cart with amazing items</p>
                    <button href="#product-section" class="btn btn-danger mt-2" data-bs-dismiss="offcanvas" aria-label="Close">Shop Now</button>
                </div>
            </div>`;
        return;
    }

    // Render each cart item
    cart.forEach(item => {
        cartContainer.innerHTML += `
        <div class="cart-item d-flex poppins justify-content-between align-items-start mb-4 position-relative" data-id="${item.id}">
            <button class="btn btn-sm position-absolute top-0 start-0 translate-middle p-1 remove-btn">
                <i class="fa-solid fa-xmark text-muted"></i>
            </button>
            <div class="d-flex align-items-center gap-2 ps-4">
                <img src="./Media/azadi-deal-1.png" class="rounded-circle bg-danger" width="40" height="40">
                <div>
                    <div class="fw-semibold">${item.name}</div>
                    <div class="input-group input-group-sm mt-1 w-auto quantity-wrapper">
                        <button class="btn btn-outline-danger quantity-minus">−</button>
                        <input type="number" class="form-control text-center quantity-field" value="${item.quantity}" min="1" style="max-width: 50px;">
                        <button class="btn btn-outline-danger quantity-plus">+</button>
                    </div>
                </div>
            </div>
            <div class="fw-bold">Rs.${item.price * item.quantity}</div>
        </div>`;
    });

    // Calculate total price
    const totalPrice = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);

    // Append total at bottom
    cartContainer.innerHTML += `
        <div class="cart-total poppins fw-bold mt-3 pe-4 py-2 border-top position-absolute bottom-0 w-100 bg-light">
            <p class="cart-total">Total: Rs.${totalPrice}</p>
            <a href="./checkout.php" class="btn btn-danger w-100 poppins text-center">Checkout</a>
        </div>
        `;

    bindCartEvents();
}

// Bind quantity buttons and remove buttons after rendering
function bindCartEvents() {
    const quantityPlus = cartContainer.querySelectorAll(".quantity-plus");
    const quantityMinus = cartContainer.querySelectorAll(".quantity-minus");
    const removeBtns = cartContainer.querySelectorAll(".remove-btn");
    let cart = JSON.parse(localStorage.getItem("cart")) || [];

    // Increment
    quantityPlus.forEach(btn => {
        btn.onclick = () => {
            const itemDiv = btn.closest(".cart-item");
            const id = itemDiv.dataset.id;
            const item = cart.find(i => i.id === id);
            item.quantity += 1;
            localStorage.setItem("cart", JSON.stringify(cart));
            renderCart();
        }
    });

    // Decrement (stop at 1)
    quantityMinus.forEach(btn => {
        btn.onclick = () => {
            const itemDiv = btn.closest(".cart-item");
            const id = itemDiv.dataset.id;
            const item = cart.find(i => i.id === id);
            if (item.quantity > 1) {
                item.quantity -= 1;
            }
            localStorage.setItem("cart", JSON.stringify(cart));
            renderCart();
        }
    });

    removeBtns.forEach(btn => {
        btn.onclick = () =>{ 
            removeItem(btn)
             cartQuantity.innerHTML=cart.length};
    });
}

// Initial render
renderCart();


const menu = document.getElementById("cat-menu");
const links = menu.querySelectorAll("a");

// Scroll left/right buttons
document.getElementById("scroll-left").onclick = () => {
    menu.scrollBy({ left: -150, behavior: "smooth" });
};

document.getElementById("scroll-right").onclick = () => {
    menu.scrollBy({ left: 150, behavior: "smooth" });
};

// Smooth scroll to section on click
links.forEach(link => {
    link.addEventListener("click", e => {
        e.preventDefault();
        const targetId = link.getAttribute("href").substring(1);
        const targetSection = document.getElementById(targetId);
        if(targetSection) {
            targetSection.scrollIntoView({ behavior: "smooth", block: "start" });
        }
    });
});

// Highlight active link on scroll
const sections = Array.from(links).map(link => {
    const id = link.getAttribute("href").substring(1);
    return document.getElementById(id);
});

window.addEventListener("scroll", () => {
    let scrollPos = window.scrollY || window.pageYOffset;

    sections.forEach((section, index) => {
        if(section.offsetTop <= scrollPos + 100 && (section.offsetTop + section.offsetHeight) > scrollPos + 100) {
            links.forEach(link => link.classList.remove("active"));
            links[index].classList.add("active");
        }
    });
});
