// Simulate prompt for input

function parseSlots(value) {
    if (!value) {
        return [];
    }

    return String(value)
        .split(',')
        .map((item) => parseInt(item.trim(), 10))
        .filter((item) => Number.isInteger(item) && item >= 0);
}

function isBloomreachDisabled(slots) {
    return !slots.length || slots.every((s) => s === 0);
}

function toggleHybrisProductBanners(inputs) {
    const banners = document.querySelectorAll('.card-product-banner');
    const disabled = isBloomreachDisabled(inputs.bloomreachSlots);

    banners.forEach((banner) => {
        if (disabled) {
            banner.classList.remove('d-none');
            banner.classList.remove('card-product-banner--inactive');
        } else {
            banner.classList.add('d-none');
            banner.classList.add('card-product-banner--inactive');
        }
    });
}

function getPositionAttr() {
    const isMobile = Wick.BannerPlacementManager.isMobileResolution();

    return isMobile ? 'data-mobile-position' : 'data-desktop-position';
}

function setUnifiedPosition(el, slot) {
    el.setAttribute('data-desktop-position', String(slot));
    el.setAttribute('data-mobile-position', String(slot));
}

function hasLegacyBanners() {
    return Boolean(
        document.querySelector('.card-product-banner') ||
        document.querySelector('.card-sponsor-product') ||
        document.querySelector('.card-sponsor-banner')
    );
}

function getInputs() {
    const hasLegacy = hasLegacyBanners();

    const bloomreachSlots = parseSlots(
        prompt('Enter Bloomreach Banner Slots (comma-separated):', '3') || ''
    );

    if (!hasLegacy) {
        return {
            bloomreachSlots,
            sponsorProductPositions: [],
            sponsorBannerPositions: [],
            productBannerPositions: [],
        };
    }

    const productBannerPositions =
        prompt('Enter Product Banner Positions (comma-separated):', '2') || '';

    const sponsorProductPositions =
        prompt('Enter Sponsor Product Positions (comma-separated):', '6,7,8') || '';

    const sponsorBannerPositions =
        prompt('Enter Sponsor Banner Positions (comma-separated):', '10') || '';

    return {
        productBannerPositions: parseSlots(productBannerPositions),
        sponsorProductPositions: parseSlots(sponsorProductPositions),
        sponsorBannerPositions: parseSlots(sponsorBannerPositions),
        bloomreachSlots,
    };
}

function updateBannerPositions(selector, positions) {
    if (!positions?.length) {
        return;
    }

    const positionAttr = getPositionAttr();
    const elements = document.querySelectorAll(selector);

    elements.forEach((el, index) => {
        if (positions[index] !== undefined) {
            el.setAttribute(positionAttr, String(positions[index]));
        }
    });
}

function updatePositions(inputs) {
    updateBannerPositions('.card-product-banner', inputs.productBannerPositions);
    updateBannerPositions('.card-sponsor-product', inputs.sponsorProductPositions);
    updateBannerPositions('.card-sponsor-banner', inputs.sponsorBannerPositions);
}

function patchBannerPlacementManagerForBloomreachEmulation(inputs) {
    const manager = window.Wick?.BannerPlacementManager;

    if (!manager || manager.__bloomreachEmulationPatched) {
        return;
    }

    const shouldDisableProductBanners = Boolean(inputs.bloomreachSlots?.length);

    manager.el.bloomreachBanners = '.card-bloomreach-media-banner';

    manager.el.allBanners = shouldDisableProductBanners
        ? '.card-bloomreach-media-banner, .card-sponsor-banner, .card-sponsor-product'
        : '.card-product-banner, .card-bloomreach-media-banner, .card-sponsor-banner, .card-sponsor-product';

    manager.el.allListSlots = shouldDisableProductBanners
        ? '.product-card, .card-bloomreach-media-banner, .card-sponsor-banner, .card-sponsor-product'
        : '.product-card, .card-product-banner, .card-bloomreach-media-banner, .card-sponsor-banner, .card-sponsor-product';

    manager.classes.bloomreachBanners = 'card-bloomreach-media-banner';

    manager.getListSlots = function () {
        return $(manager.el.productsWrap)
            .children(manager.el.allListSlots)
            .filter(function () {
                if (
                    $(this).hasClass(manager.classes.productBanners) ||
                    $(this).hasClass(manager.classes.bloomreachBanners)
                ) {
                    const position = manager.getBannerPosition(this);
                    const productsCount = manager.getListLength();

                    return position <= productsCount;
                }

                return true;
            });
    };

    manager.arrangeBannersInRightOrder = function () {
        const $allBanners = $(manager.el.allBanners);

        function getSameSlotInsertionOrder(el) {
            if ($(el).hasClass(manager.classes.bloomreachBanners)) {
                return 0;
            }

            if ($(el).hasClass(manager.classes.sponsorBanners)) {
                return 1;
            }

            if ($(el).hasClass(manager.classes.sponsorProducts)) {
                return 2;
            }

            if ($(el).hasClass(manager.classes.productBanners)) {
                return 3;
            }

            return 4;
        }

        $allBanners
            .sort((a, b) => {
                const positionA = manager.getBannerPosition(a);
                const positionB = manager.getBannerPosition(b);

                if (positionA !== positionB) {
                    return positionA - positionB;
                }

                return getSameSlotInsertionOrder(a) - getSameSlotInsertionOrder(b);
            })
            .appendTo(manager.el.productsWrap);
    };

    manager.__bloomreachEmulationPatched = true;
}

function rebuildBloomreachBannersForEmulation(inputs) {
    const slots = inputs.bloomreachSlots || [];
    const productsWrap = document.querySelector('.products-list.products-list-v2');

    if (!productsWrap) {
        return;
    }

    const existingBanners = document.querySelectorAll('.card-bloomreach-media-banner');

    if (isBloomreachDisabled(slots)) {
        existingBanners.forEach((banner) => banner.remove());
        return;
    }

    if (!existingBanners.length) {
        return;
    }

    const template = existingBanners[0].cloneNode(true);

    existingBanners.forEach((banner) => banner.remove());

    const fragment = document.createDocumentFragment();

    slots.forEach((slot) => {
        if (slot === 0) return;

        const node = template.cloneNode(true);

        node.removeAttribute('data-slots');
        setUnifiedPosition(node, slot);

        fragment.appendChild(node);
    });

    productsWrap.appendChild(fragment);
}

function applyBloomreachEmulation() {
    const inputs = getInputs();

    updatePositions(inputs);

    const isDisabled = isBloomreachDisabled(inputs.bloomreachSlots);

    toggleHybrisProductBanners(inputs);

    if (!isDisabled) {
        patchBannerPlacementManagerForBloomreachEmulation(inputs);
    }

    rebuildBloomreachBannersForEmulation(inputs);

    if (
        window.Wick &&
        Wick.BannerPlacementManager &&
        typeof Wick.BannerPlacementManager.checkProductsInColumn === 'function'
    ) {
        Wick.BannerPlacementManager.checkProductsInColumn();
    }
}

$(document).ready(function () {
    if ($('.products-list.products-list-v2').length) {
        setTimeout(() => {
            applyBloomreachEmulation();
        }, 100);
    }
});
