const client = contentful.createClient({
  // This is the space ID. A space is like a project folder in Contentful terms
  space: "eekrkv55bg3z",
  // This is the access token for this space. Normally you get both ID and the token in the Contentful web app
  accessToken: "OvvlE2s4LEVGrUcYGFubs9s3-Hf81iK_g7U9fQ_UWOE"
});

//Variables
const cartBtn = document.querySelector('.cart-btn');
const closeCartBtn = document.querySelector('.close-cart');
const clearCartBtn = document.querySelector('.clear-cart');
const cartDOM = document.querySelector('.cart');
const cartOverlay = document.querySelector('.cart-overlay');
const cartItems = document.querySelector('.cart-items');
const cartTotal = document.querySelector('.cart-total');
const cartContent = document.querySelector('.cart-content');
const productsDOM = document.querySelector('.products-center');
const hero = document.querySelector('.hero');
const shopNowBtn = document.querySelector('.banner-btn');
const productsSection = document.querySelector('.products')
const navLists = document.querySelector('.navlists');
const navOpen = document.querySelector('.nav-open');
const navClose = document.querySelector('.nav-close');

//cart item
let cart = [];
//buttons
let buttonsDOM= []

//getting the products
class Products {
async getProducts(){
    try {
    let contentful = await client.getEntries({
        content_type: "chayyahsmartwebshop"
    });

//        let result = await fetch('products.json')
//        let data = await result.json()
        let products = contentful.items; 
        products = products.map(item => {
            const {title,price} = item.fields;
            const {id} = item.sys
            const image = item.fields.image.fields.file.url
            const {description} = item.fields
            return {title,price,id,image,description}
        })
        return products
    } catch (error) {
        console.log(error)
    }
}
};
//display products
class UI {
    displayProducts(products){
        let result = '';
        products.forEach(product => {
            result += `
            <article class="product">
                <div class="img-container">
                    <img src=${product.image} alt="product" class="product-img">
                    <button class="bag-btn" data-id=${product.id}>
                         <img src="./images/icons8_add_shopping_cart_100px.png" 
                         width="16px" max-width= "18px" alt="add to cart"/>
                         Add to cart
                    </button>
                </div>
                <div class="goodsinfo">
                    <span class="description"> <img src="./images/icons8_eye_100px.png" class="view" data-class=${product.id}/> 
                    </span>
                    <span class="titleprice">
                        <h3>${product.title}</h3>
                        <h4>#${product.price}</h4>
                    </span>
                </div>
            </article>
            `
        });
        productsDOM.innerHTML = result;

    }

    compileDescription(products){
        const eyeView = [...document.querySelectorAll('.view')];
        eyeView.forEach(viewBtn => {
            viewBtn.addEventListener('click', (event)=>{
            const btnId= event.target.dataset.class;
                console.log(btnId);
            let productItem = product.find(product => product.id === btnId)
            if (productItem) {
                this.displayDescription(productItem);
            };
            })
           
        })
       

    }

    displayDescription(product) {
        let description = `
        <article>

        </article>
        `
    }

    shopNow() {
        shopNowBtn.addEventListener('click', ()=>{
            hero.style.display="none";
            productsSection.classList.remove('products')
            productsSection.classList.add('productsInside');
        })
    }

    hamburgerBtn() {
        navOpen.addEventListener('click', ()=>{
            navLists.style.display = "flex";
            navOpen.style.display = "none";
            navClose.style.display = "block"
        })
        navClose.addEventListener('click', ()=>{
            navLists.style.display = "none";
            navOpen.style.display = "block";
            navClose.style.display = "none"
        })
    }

    getCartbuttons(){
        const buttons = [...document.querySelectorAll('.bag-btn')];
        buttonsDOM= buttons;
        buttons.forEach(button =>{
            let id = button.dataset.id;
            let inCart = cart.find(item => item.id === id);
            if(inCart){
                button.innerText= "In Cart";
                button.disabled= true;
            }
            button.addEventListener('click', (event)=>{
                event.target.innerText= "In Cart";
                event.target.disabled= true;
                //get product from products(local storage)
                let cartItem = {...Storage.getProduct(id), amount:1};
                //add product to cart
                cart = [...cart, cartItem];
                //save the cart in the local storage
                Storage.saveCart(cart);
                //set cart values
                this.setCartValue(cart)
                //display cart items
                this.addCartItem(cartItem);
                //show the cart
                this.showCart()

            })
        })
    }
    setCartValue(cart) {
        let tempTotal = 0;
        let itemsTotal = 0;
        cart.map(item =>{
            tempTotal += item.price * item.amount;
            itemsTotal += item.amount;
        })
        cartTotal.innerText = parseFloat(tempTotal.toFixed(2));
        cartItems.innerText = itemsTotal;
    }

    addCartItem(item) {
        const div = document.createElement('div');
        div.classList.add('cart-item');
        div.innerHTML = `<img src = ${item.image} alt="product">
                    <div class="#">
                        <h4>${item.title}</h4>
                        <h5>${item.price}</h5>
                        <span class="remove-item" data-id=${item.id}>remove</span>
                    </div>
                    <div>
                        <img src="./images/icons8_chevron_up_100px.png" class="amountcontrols increase" data-id=${item.id} alt="chevron-up"/>
                        <p class="item-amount">${item.amount}</p>
                        <img src="./images/icons8_chevron_down_100px.png" class="amountcontrols decrease" data-id=${item.id} alt="chevron-down"/>
                    </div>
        `
        cartContent.appendChild(div);
    }
    showCart(){
        cartOverlay.classList.add('transparentBcg');
        cartDOM.classList.add('showCart');
    }
    setupAPP(){
        cart = Storage.getCart();
        this.setCartValue(cart);
        this.populateCart(cart);
        cartBtn.addEventListener('click', this.showCart);
        closeCartBtn.addEventListener('click', this.hideCart)
    }
    populateCart(cart) {
        cart.forEach(item => this.addCartItem(item));
    }
    hideCart() {
        cartOverlay.classList.remove('transparentBcg');
        cartDOM.classList.remove('showCart');
    }
    cartLogic() {
        //cart button
        clearCartBtn.addEventListener('click', ()=>{ this.clearCart();
        });
        //cart functionality
        cartContent.addEventListener('click', event=>{
            if(event.target.classList.contains('remove-item')) {
                let removeItem = event.target;
                let id = removeItem.dataset.id;
                cartContent.removeChild((removeItem.parentElement.parentElement));

                this.removeItem(id);
            }
            else if(event.target.classList.contains('increase')) {
                let addAmount = event.target;
                let id = addAmount.dataset.id;
                let tempItem = cart.find(item=> item.id===id);
                tempItem.amount = tempItem.amount + 1;
                Storage.saveCart(cart);
                this.setCartValue(cart);
                addAmount.nextElementSibling.innerText = tempItem.amount;
            }
            else if(event.target.classList.contains('decrease')) {
                let lowerAmount = event.target;
                let id = lowerAmount.dataset.id;
                let tempItem = cart.find(item=> item.id===id);
                tempItem.amount = tempItem.amount - 1;
                if (tempItem.amount > 0) {
                Storage.saveCart(cart);
                this.setCartValue(cart);
                lowerAmount.previousElementSibling.innerText = tempItem.amount;
                }
                else {
                    cartContent.removeChild(lowerAmount.parentElement.parentElement);
                    this.removeItem(id);
                }
            }
        })
    }
    clearCart() {
        let cartItems = cart.map(item => item.id);
        cartItems.forEach(id => this.removeItem(id));
        while (cartContent.children.length>0){
            cartContent.removeChild(cartContent.children[0])
        }
        this.hideCart();
    }
    removeItem(id) {
        cart = cart.filter(item => item.id !== id);
        this.setCartValue(cart);
        Storage.saveCart(cart);
        let button = this.getSingleButton(id);
        button.disabled = false;
        button.innerHTML = `<img src="./images/icons8_add_shopping_cart_100px.png" 
                         width="16px" max-width= "18px" alt="add to cart"/>
                         Add to cart`
    }
    
    getSingleButton(id) {
        return buttonsDOM.find(button => button.dataset.id ===id);
    }
};
//local storage
class Storage {
    static saveProducts(products) {
        localStorage.setItem('products',JSON.stringify(products));
    }
    static getProduct(id) {
        let products = JSON.parse(localStorage.getItem('products'));
        return products.find(product => product.id === id);
    }
    static saveCart(cart) {
        localStorage.setItem('cart', JSON.stringify(cart));
    };
    static getCart() {
        return localStorage.getItem('cart')?JSON.parse(localStorage.getItem('cart')):[]
    }
};

document.addEventListener('DOMContentLoaded', ()=>{
const ui= new UI();
const products= new Products();
//setup app
ui.setupAPP();
//shop now button
ui.shopNow();
ui.hamburgerBtn();

//get all products
products.getProducts().then(products => {
ui.displayProducts(products);
ui.compileDescription(products);
Storage.saveProducts(products);
}).then(()=>{
    ui.getCartbuttons();
    ui.cartLogic();
});
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.