let addToCartResponseIndex = 0;

function formatBundlePrice(value) {
    return new Intl.NumberFormat('en-GB', {
        style: 'currency',
        currency: 'GBP',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(value);
}

function getPriceData(product) {
    return product.price || product.displayPrice || {};
}

function getBundleProductPrice(product) {
    const price = getPriceData(product);

    return typeof price.value === 'number' ? price.value : 0;
}

function getBundleProductWasPrice(product) {
    const price = getPriceData(product);

    return typeof price.wasPrice === 'number' ? price.wasPrice : null;
}

function getBundleProductExcVatPrice(product) {
    const priceExcVat = product.displayPriceExclusiveVat || product.priceExclusiveVat;
    if (priceExcVat && typeof priceExcVat.value === 'number') return priceExcVat.value;
    const price = getPriceData(product);
    if (typeof price.value !== 'number') return 0;
    const vatRate = price.vatRatePercentage || 20;
    return price.value / (1 + vatRate / 100);
}

function getBundleProductExcVatWasPrice(product) {
    const display = product.displayPriceExclusiveVat;
    const raw = product.priceExclusiveVat;
    if (display && typeof display.wasPrice === 'number') return display.wasPrice;
    if (raw && typeof raw.wasPrice === 'number') return raw.wasPrice;
    const price = getPriceData(product);
    if (typeof price.wasPrice !== 'number') return null;
    const vatRate = price.vatRatePercentage || 20;
    return price.wasPrice / (1 + vatRate / 100);
}

function calculateBundleTotal(entries) {
    let totalPrice = 0;
    let totalWasPrice = 0;
    let totalExcVatPrice = 0;
    let totalExcVatWasPrice = 0;
    let hasWasPrice = false;

    entries.forEach(function (entry) {
        const quantity = entry.quantity || 1;
        const price = getBundleProductPrice(entry.product);
        const wasPrice = getBundleProductWasPrice(entry.product);
        const excVatPrice = getBundleProductExcVatPrice(entry.product);
        const excVatWasPrice = getBundleProductExcVatWasPrice(entry.product);

        totalPrice += price * quantity;
        totalWasPrice += (wasPrice || price) * quantity;
        totalExcVatPrice += excVatPrice * quantity;
        totalExcVatWasPrice += (excVatWasPrice || excVatPrice) * quantity;

        if (wasPrice) {
            hasWasPrice = true;
        }
    });

    return {
        totalPrice: formatBundlePrice(totalPrice),
        totalWasPrice: hasWasPrice ? formatBundlePrice(totalWasPrice) : null,
        totalExcVatPrice: formatBundlePrice(totalExcVatPrice),
        totalExcVatWasPrice: hasWasPrice ? formatBundlePrice(totalExcVatWasPrice) : null,
    };
}

function bindCalculateProductBundleTotalEvent() {
    $(window).on('calculateProductBundleTotal', function ({ detail: { payload, resolve } }) {
        const entries = payload.entries || [];

        setTimeout(function () {
            resolve(calculateBundleTotal(entries));
        }, 200);
    });
}

function getAddProductBundleResponse() {
    const responses = [
        {
            bulkAddToCartData: {
                messageType: 'success',
                messageText: 'Selected product(s) were added to basket',
            },
        },
        {
            bulkAddToCartData: {
                messageType: 'warning',
                messageText: 'Selected product(s) were partially added to basket',
            },
        },
        {
            bulkAddToCartData: {
                messageType: 'error',
                messageText: 'Selected product(s) were not added to basket',
            },
        },
    ];

    const response = responses[addToCartResponseIndex % responses.length];

    addToCartResponseIndex++;

    return response;
}

function bindAddProductBundleToCartEvent() {
    $(window).on('bulkAddToCart', function ({ originalEvent }) {
        const entries = originalEvent.detail.entries || [];

        setTimeout(function () {
            const response = getAddProductBundleResponse(entries);

            window.dispatchEvent(
                new CustomEvent('productAddedToCart', {
                    detail: {
                        bulkAddToCartData: response.bulkAddToCartData,
                    },
                })
            );
        }, 1200);
    });
}

$(document).ready(function () {
    bindCalculateProductBundleTotalEvent();
    bindAddProductBundleToCartEvent();
});
