var _token, base_url, asset, prefix, asset, formDataContainer, subtotal = 0, grandTotal = 0, currentCartId = 0, currentCartIndex = 0;
let cartTable = $('#cartTable'), cartTbody = cartTable.find('tbody'), shippingCost = 0, quickview = null;
let cartProductsElement = $('.cart-dropdown .products'), countCartElement = $('.cart-dropdown .cart-count'),
    subTotalElement = $('.cart-total .price'), total = $('.cart-total .total-price');

let checkoutPageTable = $('#checkoutTable'), checkoutTbody = checkoutPageTable.find('tbody');
let grandTotalElement = $('input[name="grandTotal"]'), subTotalValueSetElement = $('input[name="subtotal"]'), grandTotalTextElement = $('.grandTotal');

document.addEventListener("DOMContentLoaded", function () {
    _token = $('meta[name="csrf-token"]').attr('content'); // csrf token
    base_url = $('meta[name="base_url"]').attr('content');
    asset = $('meta[name="asset"]').attr('content');
    prefix = $('meta[name="prefix"]').attr('content');
    asset = asset.slice(asset.length - 1) === '/' ? asset : asset + '/';
    shippingCost = parseFloat($('input[name="shipping"]').val());
    setTimeout(() => {
        wishListSync();
    }, 50);
});
function cartManage() {
    let data = { product_id: parseInt(this.data('product-id')), _token: _token };
    if(this.data('product-variant') && this.data('variant-price') ) {
        data.variant_id = parseInt(this.data('product-variant'));
        data.variant_price = parseFloat(this.data('variant-price'));
    }
    axios.put(`${base_url}cart-catch`, data).then(cartProducts);
}
function cartItemQtyPlusMinus(data) {
    currentCartId = data.product_id;
    axios.put(`${base_url}cart-catch`, data).then(cartProducts);
}
function cartProducts(response) {
    cartItems = response.data ? Object.values(response.data) : [], cartsOutput = '';
    subtotal = 0;

    if (cartItems && cartItems.length) {
        googleAnalyticsAddToCartOrWishlist('add_to_cart', currentCartId);
        cartItems.forEach(cart => {
            subtotal += cart.price * cart.qty;
            $('[data-product-qty="' + cart.id + '"]').each(function () {
                if (this.tagName === 'INPUT') {
                    this.value = cart.qty;
                } else {
                    this.innerHTML = cart.qty;
                }
            });
            cartsOutput += `<div class="product product-cart">
                                <div class="product-detail">
                                    <a href="${base_url}product-details/${cart.id}" class="product-name">${cart.name}</a>
                                    <div class="price-box">
                                        <span data-product-qty="${cart.id}" class="product-quantity">${cart.qty}</span>
                                        <span class="product-price">৳ ${cart.price}</span>
                                    </div>
                                </div>
                                <figure class="product-media">
                                    <a href="${base_url}product-details/${cart.id}">
                                        <img src="${asset}${cart.featured_image}" alt="product" width="84" height="94">
                                    </a>
                                </figure>
                                <button class="btn btn-link btn-close remove-cart-item" aria-label="button" data-product="${cart.id}">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>`;
        });
    } else {
        $('.quantity').each(function () {
            if (this.tagName === 'INPUT') {
                this.value = 1;
            } else {
                this.innerHTML = 0;
            }
        })
    }
    cartTable[0] && cartPageCartItems();
    checkoutTbody[0] && checkoutPage();
    subTotalElement.text('৳ ' + subtotal.toFixed(2));
    countCartElement.text(cartItems.length);
    cartProductsElement.html(cartsOutput);
    subTotalValueSetElement.val(subtotal.toFixed(2));
}

function cartPageCartItems() {
    let cartItemsHtml = '';
    if (!cartItems.length) {
        cartTbody.html(`<tr><td colspan="6" class="text-center">No Product in cart</td></tr>`);
        setTimeout(() => {
            window.history.back();
        }, 900);
    }
    cartItems.length && cartItems.forEach(cart => {
        cartItemsHtml += `<tr>
            <td class="product-thumbnail">
                <div class="p-relative">
                    <a href="${base_url}product-details/${cart.id}">
                        <figure>
                            <img src="${asset}${cart.featured_image}" alt="product" width="300" height="338">
                        </figure>
                    </a>
                    <button type="button" class="btn btn-close remove-cart-item" aria-label="button" data-product="${cart.id}"><i class="fas fa-times"></i></button>
                </div>
            </td>
            <td class="product-name">
                <a href="${base_url}product-details/${cart.id}">${cart.name}</a>
            </td>
            <td class="product-price"><span class="amount">৳ ${cart.price}</span></td>
            <td class="product-quantity">
                <div class="input-group">
                    <input data-product-qty="${cart.id}" value="${cart.qty}" class="quantity form-control" type="number" min="1" max="10000000" readonly />
                    <button data-product="${cart.id}" class="quantity-plus w-icon-plus"></button>
                    <button data-product="${cart.id}" class="quantity-minus w-icon-minus"></button>
                </div>
            </td>
            <td class="product-subtotal">
                <span class="amount">৳ ${(cart.price * cart.qty).toFixed(2)}</an>
            </td>
        </tr>`;
    });

    cartTbody.html(cartItemsHtml);
    $('.cart-subtotal span').text('৳ ' + subtotal);
    $('.order-total span.ls-50').text('৳ ' + subtotal);
    grandTotalElement.val(subtotal + shippingCost);
    grandTotalTextElement.html('৳ ' + (subtotal + shippingCost).toFixed(2));
    subTotalValueSetElement.val(subtotal);
    console.log(subtotal, shippingCost);
}

function checkoutPage() {
    let output = '';

    if (cartItems.length) {
        cartItems.forEach(cart => {
            output += `<tr class="bb-no">
                        <td class="product-name">${cart.name}
                            <i class="fas fa-times"></i> <span class="product-quantity"> ${cart.qty}</span>
                        </td>
                        <td class="product-total">${(cart.price * cart.qty).toFixed(2)}</td>
                    </tr>`
        });
        output += `<tr class="cart-subtotal bb-no">
                <td>
                    <b>Subtotal</b>
                </td>
                <td>
                    <b>৳ ${subtotal.toFixed(2)}</b>
                </td>
            </tr>`;
        let shippingCost = $('input[name="shipping"]:checked').val();
        grandTotal = subtotal + parseFloat(shippingCost > 0 ? shippingCost : 0);
    } else {
        output += `<tr><td colspan="6" class="text-center">No Product in cart</td></tr>`;
        setTimeout(() => {
            // window.history.length === 1 ? location.replace(base_url) : window.history.back();
        }, 900);
    }

    checkoutTbody.html(output);
    $('.order-total td b').text('৳ ' + grandTotal.toFixed(2));
    grandTotalElement.val(grandTotal);
    subTotalValueSetElement.val(subtotal);
}






$(document).on('click', '[data-product]', function (e) {
    e.preventDefault();
    if (this.classList.contains('disabled')) {
        alert('Please select some product options before adding this product to your cart.');
        return;
    }
    if (this.classList.contains('btn-quickview')) return false;
    if (this.classList.contains('btn-wishlist')) return wishListManage(this);
    // 'btn-product-icon btn-wishlist w-icon-heart-full added'

    let incrementDecrement = this.classList.contains('quantity-plus') ? 1 : this.classList.contains('quantity-minus') ? -1 : 0;
    let data = { product_id: parseInt(this.dataset.product), incrementDecrement, _token: _token };
    if(this.dataset.productVariant && this.dataset.productVariantPrice) {
        data.variant_id = parseInt(this.dataset.productVariant);
        data.variant_price = parseFloat(this.dataset.productVariantPrice);
    }

    if (this.classList.contains('remove-cart-item')) {
        data['remove_cart_item'] = 1;
    }
    cartItemQtyPlusMinus(data);
});

//==========Start Cart============//
$(document).on('click', '[data-cart]', function (e) {
    e.preventDefault();
    if (this.classList.contains('disabled')) {
        alert('Please select some product options before adding this product to your cart.');
        return;
    }
    this.setAttribute("disabled", 'disabled');
    let isCart = this.children[0].className === 'fas fa-shopping-cart';
    $(this.children[0]).attr('class', isCart ? 'fas fa-shopping-cart card-added' : 'fas fa-shopping-cart');
    cartCounter(isCart);
    let data = { product_id: this.dataset.cart };
    if(this.dataset.productVariant && this.dataset.productVariantPrice) {
        data.variant_id = parseInt(this.dataset.productVariant);
        data.variant_price = parseFloat(this.dataset.productVariantPrice);
    }
    axios.get(`${base_url}cart-catch`, { params: data }).then(r => this.removeAttribute('disabled'));

});
function cartCounter(isCart) {
    let cartCount = $('#cartCount'), cartAmount = parseInt(cartCount.text());
    if (isCart !== 0) {
        cartAmount = isCart ? cartAmount + 1 : cartAmount - 1;
    }
    cartCount.text(cartAmount > 0 ? cartAmount : 0);
    cartAmount > 0 ? cartCount.parent().show() : cartCount.parent().hide();
}
cartCounter(0);
//=======End========//

function wishListManage(el) {
    axios.get(`${base_url}wish-catch`, { params: { product_id: el.dataset.product } }).then(r => {
        if (r.data == 'Login required.') {
            toastr.error('Please login first!', 'Error');
            $('.login-popup .mfp-close').trigger('click');
            return false;
        }
        if (r.data.length > wishList.length) {
            toastr.success('Wish List Added Successfully!', 'Added');
            googleAnalyticsAddToCartOrWishlist('add_to_wishlist', el.dataset.product);
        } else {
            toastr.success('Wish List Removed Successfully!', 'Removed');
        }
        wishList = r.data;
        wishListSync();
    });
    return true;
}
function wishListSync() {
    let productIds = wishList.map(item => item.product_id);
    $('.btn-wishlist').each(function () {
        if (productIds.includes(parseInt(this.dataset.product))) {
            this.classList.add('added', 'w-icon-heart-full');
            this.classList.remove('w-icon-heart');
        } else {
            this.classList.add('w-icon-heart');
            this.classList.remove('added', 'w-icon-heart-full');
        }
    });

    let listHeart = $('.wishlist.label-down.link.d-xs-show i');
    if (wishList.length) {
        listHeart.attr('class', 'w-icon-heart-full');
    } else {
        if (location.href === `${base_url}wish-list`) {
            location.replace('/');
        }
        listHeart.attr('class', 'w-icon-heart');
    }
}
function removeAttributes(element, ...attrs) {
    attrs.forEach(attr => element.removeAttribute(attr))
}


//=====Product Filter Handle=====//
let filterStore = {}, typeNames = {};
$(document).on('change', '[data-product-filter]', function () {
    typeNames = {};
    filterStore = {};
    $('[data-product-filter]:input[type="checkbox"]:checked').each(function () {
        let type = this.dataset.productFilter, id = this.value, name = $(this).next().text();
        filterStore[type] = filterStore.hasOwnProperty(type) ? filterStore[type] : [];
        filterStore[type].push(id);
        typeNames[`${type}${id}`] = name;
    });
    getFilteredProducts();
});

let productContainer = $('#productContainer'), filterItemsContainer = $('#filterItems'), output = '', filterTypeName;
function getFilteredProducts() {
    output = '';
    //========Filter Item update======//
    for (let filterType in filterStore) {
        for (let id of filterStore[filterType]) {
            filterTypeName = typeNames[`${filterType}${id}`];
            output += `<span>${filterTypeName} <i class="far fa-times-circle" data-filter-id="${id}" data-filter-type="${filterType}"></i></span>`;
        }
    }
    filterItemsContainer.html(output.length ? `<b>Current Filters : </b>` + output : '');
    //======End=====//

    output = '';
    axios.get(`${base_url}filter-products`, { params: filterStore }).then(response => {
        let { products, wishCatch, cartCatch } = response.data, sliceCount = 0;
        wishCatch = wishCatch.map(w => parseInt(w));
        for (product of products) {
            output += `<div class="col-12 col-sm-4 col-md-3 col-lg-2">
                            <div class="product mb-0 p-3 shadow bg-body rounded text-center">
                                <div class="product-thumb-info border-0 mb-3">
                                    <a href="${base_url}product-details/${product.id}">
                                        <div class="product-thumb-info-image">
                                            <img alt="" class="img-fluid" src="${asset}${product.featured_image}">
                                        </div>
                                    </a>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3
                                            class="text-3-5 font-weight-medium font-alternative text-transform-none line-height-3 mb-0">
                                            <a href="${base_url}product-details/${product.id}"
                                                class="text-color-dark text-color-hover-primary">${product.name}</a>
                                        </h3>
                                    </div>
                                    <a type="button" data-wish="${product.id}"
                                        class="text-decoration-none text-color-default text-color-hover-dark text-4"><i
                                            class="${wishCatch.includes(product.id) ? 'fa fa-heart wished' : 'fa fa-heart-o'}"></i></a>
                                </div>

                                <p class="m-0">${product.style_number}</p>
                                <a href="${base_url}filtered-products?color_id=${product.color_id}">
                                    <div class="product-master-color" style="background-color: ${product.color_code}">
                                    </div>
                                </a>
                            </div>
                        </div>`;
        }
        productContainer.html(output.length ? output : '<h4 class="text-center not-found">No data available for this filters</h4>');
    });
}

$(document).ready(function () {
    cartProducts({ data: cartItems });
});








$(document).on('click', '#filterItems span i', function () {
    let id = this.dataset.filterId, filterType = this.dataset.filterType;
    $(this).parent().remove();
    if (filterStore[filterType].length === 1) {
        delete filterStore[filterType];
        delete typeNames[filterType];
    } else {
        filterStore[filterType] = deleteArrayItem(filterStore[filterType], id);
    }
    getFilteredProducts()
})

function deleteArrayItem(arrayData, value) {
    const index = arrayData.indexOf(value);
    if (index > -1) { // only splice array when item is found
        arrayData.splice(index, 1); // 2nd parameter means remove one item only
    }
    return arrayData;
}


//========Product Details Page Photo src handle=======//
$(document).on('click', '.change-photo', function () {
    $('#bigImg').attr('src', this.src);
})



function getFormData(selector) {
    formDataContainer = formDataContainer ? formDataContainer : new FormData();
    if (typeof selector === 'string') {
        $(selector).serializeArray().map(el => {
            let key = el.name.trim(), keyLength = key.length;
            let value = isNaN(el.value) ? el.value.trim() : parseFloat(el.value.trim());
            if (key.slice(keyLength - 3, keyLength) === '_id') {
                let selectDom = $(`${selector} select[name="${key}"]`);
                selectDom.length > 0 ? formDataContainer.append(key.split('_')[0] + 'Text', selectDom.find('option:selected').text()) : false;
            }
            formDataContainer.append(key, value);
        })
    }

    formDataContainer.append('_token', document.querySelector('[name="csrf-token"]').content);
    return formDataContainer;
}

//==========Start Wish============//
$(document).on('click', '[data-wish]', function () {
    if (this.disabled) return false;
    this.setAttribute("disabled", 'disabled');
    let product_id = this.dataset.wish;

    let beenWishing = $(this).find('i')[0].className === 'fa fa-heart-o', className = beenWishing ? 'fa fa-heart wished' : 'fa fa-heart-o';

    $(`[data-wish="${product_id}"] i`).each(function () {
        $(this).attr('class', className);
    });

    wishCounter(beenWishing);
    if (this.dataset.remove) {
        document.querySelector(`[data-wish-remove-item="${this.dataset.wish}"]`).remove();
    }

    axios.get(`${base_url}wish-catch`, { params: { product_id } }).then(r => this.removeAttribute('disabled'));

});
function wishCounter(beenWishing) {
    let wishCount = $('#wishCount'), wishAmount = parseInt(wishCount.text());
    if (beenWishing !== 0) {
        wishAmount = beenWishing ? wishAmount + 1 : wishAmount - 1;
    }
    wishCount.text(wishAmount > 0 ? wishAmount : 0);
    wishAmount > 0 ? wishCount.show() : wishCount.hide();
}
wishCounter(0);
//=======End========//



let validEventTypes = ['view_item', 'add_to_cart', 'add_to_wishlist', 'purchase'];
window.dataLayer = window.dataLayer || [];
function googleAnalytics() {
    dataLayer.push(arguments);
}

function googleAnalyticsAddToCartOrWishlist(type, product_id) {
    if (!type || !validEventTypes.includes(type) || !product_id) {
        // console.error('googleAnalyticsAddToCartOrWishlist function requires valid parameters: event type, product id.');
        return;
    }

    axios.get(`${base_url}get-catch-product-item`, { params: { product_id } }).then(r => callGoogleAnalytics(type, r.data));
}
function callGoogleAnalytics(eventName, product) {
    if (!eventName || !validEventTypes.includes(eventName) || !product) {
        console.error('callGoogleAnalytics function requires valid parameters: event name, product.');
        return;
    }

    try {

        const price = product.price ? product.price.toFixed(2) : '0.00';
        const discountPrice = product.discountPrice || 0;
        const itemBrand = product.brand_name || 'No Brand';
        const itemCategory = product.category_name || 'No Category';
        const optionsData = {
            currency: 'BDT',
            value: discountPrice > 0 ? discountPrice : price,
            items: [{
                item_id: product.id,
                item_name: product.name,
                affiliation: "Google Merchandise Store",
                coupon: "NO-COUPON",
                discount: 0,
                index: 0,
                item_brand: itemBrand,
                item_category: itemCategory,
                item_list_id: 0,
                item_list_name: "No Item List",
                item_variant: "No Variant",
                location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo",
                price: discountPrice > 0 ? discountPrice : price,
                quantity: 1
            }]
        };

        googleAnalytics("event", eventName, optionsData);
        console.log(eventName, 'google analytics called. product id ', product.id, 'optionsData', optionsData);
    } catch (e) {
        console.error('Error occurred while calling googleAnalytics function:', e);
    }
}

document.addEventListener("DOMContentLoaded", function () {

    googleAnalytics('js', new Date());
    googleAnalytics('config', googleAnalyticsId);

    const linkContainer = document.querySelector('.menu.active-underline');
    for (let link of linkContainer.querySelectorAll('li a')) {
        let parent = link.parentElement;
        if (location.href === link.href) {
            parent.classList.add('active');
        } else {
            parent.classList.remove('active');
        }
    }
});
function formatDate(date, shortM) {
    let d = new Date(date),
        day = d.getDate(),
        month = d.getMonth() + 1,
        year = d.getFullYear();
    return `${day} ${shortM ? shortMonths[month] : fullMonths[month]}, ${year}`;
}
function getFormValues(formSelector) {
    const form = document.querySelector(formSelector);
    const values = {};
    if (!form) return values;
    for (let element of form.elements) {
        // Skip elements without a name attribute or disabled ones
        if (!element.name || element.disabled) continue;

        // Handle checkboxes and radio buttons
        if ((element.type === "checkbox" || element.type === "radio") && !element.checked) {
            continue;
        }

        // Add name-value pair to the result
        values[element.name] = element.value;
    }

    return values;
}
function upFirst(str) {
    return str ? str.toLowerCase().replace(/\b[a-z]/g, function (letter) {
        return letter.toUpperCase();
    }) : str;
}