<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_FrequentlyBought
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

use Magento\Catalog\ViewModel\Product\Listing\PreparePostData;
use Magento\Framework\App\ActionInterface;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\HeroiconsSolid;

/** @var Mageplaza\FrequentlyBought\Block\Product\ProductList\FrequentlyBought $block */

$product           = $block->getProduct();
$productId         = $product->getId();
$items             = $block->getItems();
$countSlider             = $block->getNumberOfProductOnSlider() >= count($items) ? count($items) : $block->getNumberOfProductOnSlider();
$templateType      = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
$canItemsAddToCart = false;
$type              = 'related';
$showAddTo         = true;
$showCart          = true;
/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);
/** @var HeroiconsSolid $heroiconsSolid */
$heroiconsSolid = $viewModels->require(HeroiconsSolid::class);

if ($block->isShow() && $items->getSize()):?>
    <hr>
    <?php if ($title = $block->getTitleBlock()): ?>
        <div
            class="mageplaza-fbt-title block-title title container mx-auto flex pt-6 pb-3 mb-6 md:flex-row border-b-2 border-gray-300">
            <h2 id="block-mageplaza-fbt-heading"
                class="text-gray-900 text-2xl title-font font-base text-center md:text-left w-full"><?= $escaper->escapeHtml($title) ?></h2>
        </div>
    <?php endif; ?>
    <div class="mageplaza-fbt-content card w-full px-6 py-3">
        <div class="wrapper products-grid">
            <ol class="mageplaza-fbt-image-box flex items-start">
                <?php if ($isSalable = $block->getProductIsSalable($product)): ?>
                    <li class="item product first-item product-item mageplaza-fbt-item-<?= /* @noEscape */
                    $productId ?>">
                    <span>
                        <input type="checkbox" class="related-checkbox"
                               data-mageplaza-fbt-product-id="<?= /* @noEscape */
                               $productId ?>" data-price-amount="<?= /* @noEscape */
                        $block->getPriceAmount($product) ?>" id="mageplaza-fbt-slider-checkbox-<?= /* @noEscape */
                        $productId; ?>" name="mageplaza_fbt[<?= /* @noEscape */
                        $productId ?>]" <?= (!$block->getProductIsSalable($product)) ? 'disabled="disabled"' : '' ?> />
                        <?= $block->getImage($product, 'related_products_list')->toHtml() ?>
                        <div class="product details product-item-details">
                                <strong class="product name product-item-name"><a
                                        class="product-item-link"
                                        title="<?= $escaper->escapeHtmlAttr($product->getName()) ?>"
                                        href="<?= $block->escapeUrl($block->getProductUrl($product)) ?>">
                                        <?= $escaper->escapeHtml($product->getName()) ?></a>
                                </strong>

                                <?= /* @noEscape */
                                $block->getProductPrice($product) ?>

                            <?php if ($templateType): ?>
                                <?= $block->getReviewsSummaryHtml($product, $templateType) ?>
                            <?php endif; ?>

                            <?php if ($canItemsAddToCart && !$product->isComposite() && $product->isSaleable()
                                && $type == 'related'): ?>
                                <?php if (!$product->getRequiredOptions()): ?>
                                    <div class="field choice related">
                                            <input
                                                type="checkbox"
                                                class="checkbox related"
                                                id="related-checkbox<?= $escaper->escapeHtmlAttr($productId) ?>"
                                                name="related_products[]"
                                                value="<?= $escaper->escapeHtmlAttr($productId) ?>"/>
                                            <label class="label"
                                                   for="related-checkbox<?= $escaper->escapeHtmlAttr($productId)
                                                   ?>"><span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                            </label>
                                        </div>
                                <?php endif; ?>
                            <?php endif; ?>

                            <?php if ($showAddTo || $showCart): ?>
                                <div class="product actions product-item-actions">
                                        <?php if ($showCart): ?>
                                            <div class="actions-primary">
                                                <?php if ($product->isSaleable()): ?>
                                                    <?php if (!$product->getTypeInstance()->isPossibleBuyFromList($product) && !$block->usePopup()): ?>
                                                        <button
                                                            class="action tocart primary mt-3 mb-3"
                                                            type="button"
                                                            title="<?= $escaper->escapeHtmlAttr(__('Add to Cart')) ?>">
                                                            <span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                                        </button>
                                                    <?php else : ?>
                                                        <?php
                                                        /** @var $viewModel PreparePostData */
                                                        $viewModel = $block->getViewModel();
                                                        $postArray = $viewModel->getPostData(
                                                            $block->escapeUrl($block->getAddToCartUrl($product)),
                                                            ['product' => $product->getEntityId()]
                                                        );
                                                        $value     = $postArray['data'][ActionInterface::PARAM_NAME_URL_ENCODED];
                                                        ?>
                                                        <form data-role="tocart-form"
                                                              data-product-sku="<?= $escaper->escapeHtmlAttr($product->getSku()) ?>"
                                                              action="<?= $block->escapeUrl($block->getAddToCartUrl($product)) ?>"
                                                              method="post">
                                                            <input type="hidden" name="product"
                                                                   value="<?= /* @noEscape */
                                                                   (int) $product->getEntityId() ?>">
                                                            <input type="hidden"
                                                                   name="<?= /* @noEscape */
                                                                   ActionInterface::PARAM_NAME_URL_ENCODED ?>"
                                                                   value="<?= /* @noEscape */
                                                                   $value ?>">
                                                            <?= $block->getBlockHtml('formkey') ?>
                                                            <button
                                                                class="w-auto btn btn-primary justify-center text-sm mr-auto mt-3 mb-3"
                                                                title="Add to Cart"
                                                                aria-label="Add to Cart"
                                                                data-addto="cart">
                                                                                <?= $heroicons->shoppingCartHtml('border-current inline'); ?>
                                                                  <span
                                                                      class="ml-2 inline md:ml-0 md:hidden lg:ml-2 lg:inline">
                                                                       Add to Cart
                                                                  </span>
                                                                </button>
                                                        </form>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <?php if ($product->isAvailable()): ?>
                                                        <div class="stock available">
                                                            <span><?= $escaper->escapeHtml(__('In stock')) ?></span>
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="stock unavailable">
                                                            <span><?= $escaper->escapeHtml(__('Out of stock')) ?></span>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>

                                    <?php if ($showAddTo): ?>
                                        <button x-data="initWishlist()"
                                                x-defer="intersect"
                                                @click.prevent="addToWishlist(<?= (int) $product->getId() ?>)"
                                                aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Wish List') . ' ' . $product->getProductName()) ?>"
                                                type="button"
                                                class="rounded-full w-9 h-9 bg-gray-200 p-0 border-0 inline-flex shrink-0 items-center justify-center text-gray-500 hover:text-red-600"
                                                data-addto="wishlist"
                                        >
                                                                        <?= $heroiconsSolid->heartHtml("w-5 h-5", 25,
                                                                            25, ['aria-hidden' => 'true']) ?>
                                                                    </button>
                                        <button x-data="initCompareOnProductList()"
                                                x-defer="intersect"
                                                @click.prevent="addToCompare(<?= (int) $productId ?>)"
                                                aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Compare') . ' ' . $product->getProductName()) ?>"
                                                type="button"
                                                class="rounded-full w-9 h-9 bg-gray-200 p-0 border-0 inline-flex shrink-0 items-center justify-center text-gray-500 hover:text-yellow-500"
                                                data-addto="compare"
                                        >
                                                                        <?= $heroicons->scaleHtml("w-5 h-5", 25, 25,
                                                                            ['aria-hidden' => 'true']) ?>
                                                                    </button>
                                    <?php endif; ?>
                                    </div>
                            <?php endif; ?>
                            </div>
                    </span>
                    </li>
                    <li class="product-item-plus" style="margin: 0 25px">
                        <?php if ($separateImage = $block->getSeparatorImage()): ?>
                            <img src="<?= $block->escapeUrl($separateImage) ?>" alt="+"/>
                        <?php else: ?>
                            <span>&#43;</span>
                        <?php endif; ?>
                    </li>
                <?php endif; ?>
                <div class="mageplaza-fbt-carousel-container">
                    <section id="mageplaza-fbt-carousel" class="splide" aria-label="Frequently bought together">
                        <div class="splide__track">
                            <ul class="splide__list mp-list-post">
                                <?php foreach ($items as $_item): ?>
                                    <?php $itemId = $_item->getProductId() ?: $_item->getId() ?>
                                    <?php if ($isSalable = $block->getProductIsSalable($_item)): ?>
                                        <li class="item product mp-product-item mageplaza-fbt-item-<?= /* @noEscape */
                                        $itemId ?> splide__slide" style="padding: 15px !important;">
                                            <div class="fbt-product-item-info">
                                                <input type="checkbox" class="related-checkbox"
                                                       data-mageplaza-fbt-product-id="<?= /* @noEscape */
                                                       $itemId ?>" data-price-amount="<?= /* @noEscape */
                                                $block->getPriceAmount($_item); ?>"
                                                       id="mageplaza-fbt-slider-checkbox-<?= /* @noEscape */
                                                       $itemId ?>" name="mageplaza_fbt[<?= /* @noEscape */
                                                $itemId ?>]"/>
                                                <a href="<?= $block->escapeUrl($block->getProductUrl($_item)) ?>"
                                                   class="product photo product-item-photo">
                                                    <?= $block->getImage($_item, 'related_products_list')->toHtml() ?>
                                                </a>
                                                <div class="product details product-item-details">
                                                    <strong class="product name product-item-name"><a
                                                            class="product-item-link"
                                                            title="<?= $escaper->escapeHtmlAttr($_item->getName()) ?>"
                                                            href="<?= $block->escapeUrl($block->getProductUrl($_item)) ?>">
                                                            <?= $escaper->escapeHtml($_item->getName()) ?></a>
                                                    </strong>

                                                    <?= /* @noEscape */
                                                    $block->getProductPrice($_item) ?>

                                                    <?php if ($templateType): ?>
                                                        <?= $block->getReviewsSummaryHtml($_item, $templateType) ?>
                                                    <?php endif; ?>

                                                    <?php if ($canItemsAddToCart && !$_item->isComposite() && $_item->isSaleable()
                                                        && $type == 'related'): ?>
                                                        <?php if (!$_item->getRequiredOptions()): ?>
                                                            <div class="field choice related">
                                                                <input
                                                                    type="checkbox"
                                                                    class="checkbox related"
                                                                    id="related-checkbox<?= $escaper->escapeHtmlAttr($_item->getId()) ?>"
                                                                    name="related_products[]"
                                                                    value="<?= $escaper->escapeHtmlAttr($_item->getId()) ?>"/>
                                                                <label class="label"
                                                                       for="related-checkbox<?= $escaper->escapeHtmlAttr($_item->getId())
                                                                       ?>"><span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                                                </label>
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php endif; ?>

                                                    <?php if ($showAddTo || $showCart): ?>
                                                        <?php // phpcs:disable ?>
                                                        <div class="product actions product-item-actions">
                                                            <?php if ($showCart): ?>
                                                                <div class="actions-primary">
                                                                    <?php if ($_item->isSaleable()): ?>
                                                                        <?php if (!$_item->getTypeInstance()->isPossibleBuyFromList($_item) && !$block->usePopup()): ?>
                                                                            <button
                                                                                class="w-auto btn btn-primary justify-center text-sm mr-auto mt-3 mb-3"
                                                                                title="Add to Cart"
                                                                                aria-label="Add to Cart"
                                                                                data-addto="cart">
                                                                                <?= $heroicons->shoppingCartHtml('border-current inline'); ?>
                                                                                <span
                                                                                    class="ml-2 inline md:ml-0 md:hidden lg:ml-2 lg:inline">
                                                                                    Add to Cart
                                                                                </span>
                                                                            </button>
                                                                        <?php else : ?>
                                                                            <?php
                                                                            /** @var $viewModel PreparePostData */
                                                                            $viewModel = $block->getViewModel();
                                                                            $postArray = $viewModel->getPostData(
                                                                                $block->escapeUrl($block->getAddToCartUrl($_item)),
                                                                                ['product' => $_item->getEntityId()]
                                                                            );
                                                                            $value     = $postArray['data'][ActionInterface::PARAM_NAME_URL_ENCODED];
                                                                            ?>
                                                                            <form data-role="tocart-form"
                                                                                  data-product-sku="<?= $escaper->escapeHtmlAttr($_item->getSku()) ?>"
                                                                                  action="<?= $block->escapeUrl($block->getAddToCartUrl($_item)) ?>"
                                                                                  method="post">
                                                                                <input type="hidden" name="product"
                                                                                       value="<?= /* @noEscape */
                                                                                       (int) $_item->getEntityId() ?>">
                                                                                <input type="hidden"
                                                                                       name="<?= /* @noEscape */
                                                                                       ActionInterface::PARAM_NAME_URL_ENCODED ?>"
                                                                                       value="<?= /* @noEscape */
                                                                                       $value ?>">
                                                                                <?= $block->getBlockHtml('formkey') ?>
                                                                                <button
                                                                                    class="w-auto btn btn-primary justify-center text-sm mr-auto mt-3 mb-3"
                                                                                    title="Add to Cart"
                                                                                    aria-label="Add to Cart"
                                                                                    data-addto="cart">
                                                                                    <?= $heroicons->shoppingCartHtml('border-current inline'); ?>
                                                                                    <span
                                                                                        class="ml-2 inline md:ml-0 md:hidden lg:ml-2 lg:inline">
                                                                                    Add to Cart
                                                                                </span>
                                                                                </button>
                                                                            </form>
                                                                        <?php endif; ?>
                                                                    <?php else: ?>
                                                                        <?php if ($_item->isAvailable()): ?>
                                                                            <div class="stock available">
                                                                                <span><?= $escaper->escapeHtml(__('In stock')) ?></span>
                                                                            </div>
                                                                        <?php else: ?>
                                                                            <div class="stock unavailable">
                                                                                <span><?= $escaper->escapeHtml(__('Out of stock')) ?></span>
                                                                            </div>
                                                                        <?php endif; ?>
                                                                    <?php endif; ?>
                                                                </div>
                                                            <?php endif; ?>

                                                            <?php if ($showAddTo): ?>
                                                                <div class="flex flex-wrap gap-2 mt-3 mb-3">
                                                                    <button x-data="initWishlist()"
                                                                            x-defer="intersect"
                                                                            @click.prevent="addToWishlist(<?= (int) $_item->getId() ?>)"
                                                                            aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Wish List') . ' ' . $_item->getProductName()) ?>"
                                                                            type="button"
                                                                            class="rounded-full w-9 h-9 bg-gray-200 p-0 border-0 inline-flex shrink-0 items-center justify-center text-gray-500 hover:text-red-600"
                                                                            data-addto="wishlist"
                                                                    >
                                                                        <?= $heroiconsSolid->heartHtml("w-5 h-5", 25,
                                                                            25, ['aria-hidden' => 'true']) ?>
                                                                    </button>
                                                                    <button x-data="initCompareOnProductList()"
                                                                            x-defer="intersect"
                                                                            @click.prevent="addToCompare(<?= (int) $_item->getId() ?>)"
                                                                            aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Compare') . ' ' . $_item->getProductName()) ?>"
                                                                            type="button"
                                                                            class="rounded-full w-9 h-9 bg-gray-200 p-0 border-0 inline-flex shrink-0 items-center justify-center text-gray-500 hover:text-yellow-500"
                                                                            data-addto="compare"
                                                                    >
                                                                        <?= $heroicons->scaleHtml("w-5 h-5", 25, 25,
                                                                            ['aria-hidden' => 'true']) ?>
                                                                    </button>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <?php // phpcs:enable ?>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </li>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </section>
                </div>
            </ol>
        </div>
        <form id="mageplaza-fbt-form" method="post"
              action="<?= $block->escapeUrl($block->getUrl('frequentlybought/cart/add')) ?>"
              x-data="{...hyva.formValidation($el),...initMpFbtForm($el),...hyva.modal()}"
              @submit="myFormSubmit"
              x-bind="eventListeners">
            <?= $block->getFormKeyHtml() ?>
            <div class="mageplaza-fbt-price-box">
                <div class="mageplaza-fbt-total-price">
                        <span class="mageplaza-fbt-total-price-label">
                            <?= /* @noEscape */
                            __('Total price:') ?>
                        </span>
                    <span data-price-amount="0" class="mageplaza-fbt-price-wrapper">
                            <span class="mageplaza-fbt-price">
                                <?= /* @noEscape */
                                $block->getPriceWithCurrency(0) ?>
                            </span>
                        </span>
                </div>
                <div class="mageplaza-fbt-buttons">
                    <div class="mageplaza-fbt-add-to-cart">
                        <?php if (!$block->usePopup()): ?>
                            <button
                                class="w-auto btn btn-primary justify-center text-sm mr-auto action primary mpfbt-tocart"
                                type="submit" title="<?= /* @noEscape */
                            __('Add selected to cart') ?>">
                                <?= $heroicons->shoppingCartHtml('border-current inline'); ?>
                                <span><?= /* @noEscape */
                                    __('Add selected to cart') ?></span>
                            </button>
                        <?php else: ?>
                            <button
                                class="w-auto btn btn-primary justify-center text-sm mr-auto action primary mpfbt-tocart"
                                @click="_showPopup($el, null)"
                                type="button" title="<?= /* @noEscape */
                            __('Add selected to cart') ?>">
                                <?= $heroicons->shoppingCartHtml('border-current inline'); ?>
                                <span><?= /* @noEscape */
                                    __('Add selected to cart') ?></span>
                            </button>
                        <?php endif; ?>
                    </div>
                    <?php if ($block->getShowWishList()): ?>
                        <div class="mageplaza-fbt-add-to-wishlist">
                            <button type="button"
                                    class="btn btn-secondary"
                                    title="<?= /* @noEscape */
                                    __('Add selected to wishlist') ?>"
                                    data-url="<?= /* @noEscape */
                                    $block->getUrl('frequentlybought/wishlist/add') ?>"
                                    @click="_addToWishList('<?= /* @noEscape */
                                    $block->getUrl('frequentlybought/wishlist/add') ?>')">
                                    <span><?= /* @noEscape */
                                        __('Add selected to wishlist') ?></span>
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="mp-clear"></div>
            <div class="mageplaza-fbt-rows">
                <ul>
                    <li>
                        <input type="checkbox" class="related-checkbox"
                               data-mageplaza-fbt-product-id="<?= /* @noEscape */
                               $productId ?>" data-price-amount="<?= /* @noEscape */
                        $block->getPriceAmount($product) ?>" id="mageplaza-fbt-checkbox-<?= /* @noEscape */
                        $productId; ?>" name="mageplaza_fbt[<?= /* @noEscape */
                        $productId ?>]" <?= (!$block->getProductIsSalable($product)) ? 'disabled="disabled"' : '' ?> />
                        <span>
                            <div class="mageplaza-fbt-checkbox-label">
                                <strong><?= /* @noEscape */
                                    __('This item:') ?></strong>
                                <span class="mageplaza-fbt-name-<?= /* @noEscape */
                                $productId; ?>"><?= $escaper->escapeHtml($product->getName()) ?></span>
                                <span class="item-price mageplaza-fbt-price-<?= /* @noEscape */
                                $productId ?>" data-price-amount="<?= /* @noEscape */
                                $block->getPriceAmount($product) ?>"><?= /* @noEscape */
                                    $block->getPriceWithCurrency($block->getPriceAmount($product)) ?></span>
                                <?php if (!$block->getProductIsSalable($product)): ?>
                                    <span class="mageplaza-fbt-out-of-stock"><?= /* @noEscape */
                                        __('Out of stock') ?></span>
                                <?php endif; ?>
                                <?php if (!$block->usePopup()): ?>
                                    <span class="mageplaza-fbt-detail"></span>
                                <?php endif; ?>
                            </div>
                        </span>
                        <?php if (!$block->usePopup()): ?>
                            <div
                                class="fieldset mageplaza-fbt-option-product mageplaza-fbt-option-wrapper-<?= /* @noEscape */
                                $productId ?> mageplaza-fbt-hidden"><?= /* @noEscape */
                                $block->getOptionWrapper() ?></div>
                            <div
                                class="fieldset mageplaza-fbt-option-product mageplaza-fbt-custom-option-<?= /* @noEscape */
                                $productId ?> mageplaza-fbt-hidden"><?= /* @noEscape */
                                $block->getCustomOption() ?></div>
                        <?php endif; ?>
                    </li>
                    <?php foreach ($items as $_item): ?>
                        <?php $itemId = $_item->getProductId() ?: $_item->getId(); ?>
                        <?php $isSalable = $block->getProductIsSalable($_item); ?>
                        <li>
                            <input type="checkbox" class="related-checkbox"
                                   data-mageplaza-fbt-product-id="<?= /* @noEscape */
                                   $itemId ?>" data-price-amount="<?= /* @noEscape */
                            $block->getPriceAmount($_item); ?>" id="mageplaza-fbt-checkbox-<?= /* @noEscape */
                            $itemId ?>" name="mageplaza_fbt[<?= /* @noEscape */
                            $itemId ?>]" <?= (!$isSalable) ? 'disabled="disabled"' : '' ?> />
                            <span>
                                <div class="mageplaza-fbt-checkbox-label">
                                    <a class="text-blue-900" href="<?= /* @noEscape */
                                    $block->getProductUrl($_item) ?>">
                                        <?= $escaper->escapeHtml($_item->getName()) ?>
                                    </a>
                                    <span class="item-price mageplaza-fbt-price-<?= /* @noEscape */
                                    $itemId ?>" data-price-amount="<?= /* @noEscape */
                                    $block->getPriceAmount($_item) ?>">
                                        <?= /* @noEscape */
                                        $block->getPriceWithCurrency($block->getPriceAmount($_item)); ?>
                                    </span>
                                    <?php if (!$isSalable): ?>
                                        <span class="mageplaza-fbt-out-of-stock"><?= /* @noEscape */
                                            __('Out of stock') ?></span>
                                    <?php endif; ?>
                                    <?php if (!$block->usePopup()): ?>
                                        <span class="mageplaza-fbt-detail"></span>
                                    <?php endif; ?>
                                </div>
                            </span>
                            <?php if (!$block->usePopup()): ?>
                                <div
                                    class="fieldset mageplaza-fbt-option-product mageplaza-fbt-option-wrapper-<?= /* @noEscape */
                                    $itemId ?> mageplaza-fbt-hidden"><?= /* @noEscape */
                                    $block->getOptionWrapper($itemId) ?></div>
                                <div
                                    class="fieldset mageplaza-fbt-option-product mageplaza-fbt-custom-option-<?= /* @noEscape */
                                    $itemId ?> mageplaza-fbt-hidden"><?= /* @noEscape */
                                    $block->getCustomOption($itemId) ?></div>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php if ($block->usePopup()): ?>
                <?php
                $modalViewModel = $viewModels->require(\Hyva\Theme\ViewModel\Modal::class);

                $modal      = $modalViewModel->createModal()
                    ->withTemplate('Mageplaza_FrequentlyBought::hyva/product/modal/modal-options.phtml')
                    ->withDialogRefName("mp-fbt-modal-options")->addDialogClass('w-full xl:w-1/2 md:w-3/4 max-h-dialog relative')
                    ->removeDialogClass('p-10');
                $modalBlock = $modal->getContentRenderer();
                $modalBlock->setData('data', $block);
                ?>
                <?= /* @noEscape */
                $modal ?>
            <?php endif; ?>
        </form>
    </div>
    <hr>


    <script>
        hyva.formValidation.addRule('validate-one-required-by-name', function(value, options, field, context) {
            const elm = field.element;
            let selector = '';

            if (options === 'true') {
                const name = elm.name.replace(/([\\[\]])/g, '\\$1');
                selector = `input[name^="${name}"]:checked`;
            } else {
                selector = `input[name^="${options.replace(/([\\[\]])/g, '\\$1')}"]:checked`;
            }

            const container = elm.closest('form');
            return container.querySelectorAll(selector).length > 0
                ? true
                : 'Please select one of the options.';
        });

        hyva.formValidation.addRule('validate-grouped-qty', function(value, options, field, context) {
            let result = false;
            let total = 0;

            document.querySelectorAll(`${options} input[data-validate*="validate-grouped-qty"]`).forEach(function(element) {
                const val = element.value;
                const valInt = parseFloat(val) || 0;

                if (val && val.length > 0 && valInt >= 0) {
                    total += valInt;
                    result = true;
                } else {
                    result = false;
                }
            });

            return result && total > 0
                ? true
                : 'Please specify the quantity of product(s).';
        });
        function initMpFbtForm (element) {
            return {
                options: <?= /* @noEscape */ $block->getJsonConfig() ?>,
                removeRelatedBlock: <?= /* @noEscape */ $this->getHelperData()->getConfigGeneral('remove_related_block') ?>,
                init () {
                    if(this.removeRelatedBlock) {
                        let relatedBlock = document.querySelector('section .product-slider.related-product-slider');
                        if(relatedBlock) {
                            relatedBlock.remove()
                        }
                    }
                    var items = <?=  /** @noEscape */  $countSlider ?>;
                    new Splide('#mageplaza-fbt-carousel', {
                        perPage: items >= 3 ? 3 : items,
                        perMove: 1,
                        gap: 10,
                        arrows: true,
                        navigation: false,
                        breakpoints: {
                            768: {
                                perPage: items >= 2 ? 2 : items,
                                snap: true,
                                arrows: false,
                            },
                            1028: {
                                perPage: items >= 3 ? 3 : items,
                                snap: true
                            }
                        }
                    }).mount();
                    this._initCheckBoxItem();
                    this._EventListener();
                    this._bind();
                    this._renderShowDetail();

                    let infoDetails = document.querySelector('.product-info-main > div');
                    if(infoDetails) {
                        let wrapFbtBlock  = document.querySelector('.mageplaza-frequently-bought-together-block');
                        infoDetails.before(wrapFbtBlock);
                    }

                    let totalSelectedGrouped = document.querySelector('.mpfbt-total-items-value');
                    if (totalSelectedGrouped) {
                        totalSelectedGrouped.innerText = this._countSelectedItems();
                    }

                },
                cache: {
                    priceObject: {}
                },
                _initCheckBoxItem() {
                    document.querySelectorAll('.mageplaza-fbt-image-box .related-checkbox').forEach(function (checkbox) {
                        var productId = checkbox.getAttribute('data-mageplaza-fbt-product-id');
                        var fbtCheckbox = document.getElementById('mageplaza-fbt-checkbox-' + productId);
                        checkbox.checked = fbtCheckbox.checked;

                        checkbox.addEventListener('change', function () {
                            fbtCheckbox.checked = checkbox.checked;
                            var event = new InputEvent('change', {
                                bubbles: true,
                                cancelable: true,
                            });
                            fbtCheckbox.dispatchEvent(event);
                        });

                        fbtCheckbox.addEventListener('change', function () {
                            checkbox.checked = fbtCheckbox.checked;

                            if (!document.querySelectorAll('.mageplaza-fbt-rows .related-checkbox:checked').length) {
                                document.querySelector('.mageplaza-fbt-image-box').classList.add('mageplaza-fbt-hidden');
                            } else {
                                document.querySelector('.mageplaza-fbt-image-box').classList.remove('mageplaza-fbt-hidden');
                            }
                        });
                    });

                },
                _EventListener () {
                    let self = this;
                    element.addEventListener('change', function (event) {
                        if (event.target.matches('.mageplaza-fbt-rows .related-checkbox')) {
                            self._reloadTotalPrice();
                        }
                    });

                    element.addEventListener('change', function (event) {
                        if (event.target.matches('.mageplaza-fbt-rows .mageplaza-fbt-grouped .mageplaza-fbt-grouped-qty')) {
                            self._reloadGroupedPrice(event.target);
                            let totalSelectedGrouped = document.querySelector('.mpfbt-total-items-value');
                            if (totalSelectedGrouped) {
                                totalSelectedGrouped.innerText = self._countSelectedItems();
                            }
                        }
                    });

                    element.querySelectorAll('.mageplaza-fbt-rows .product-custom-option').forEach(function (option) {
                        option.addEventListener('change', (event) => self._onOptionChanged(event.target));
                    });


                    element.addEventListener('click', function (event) {
                        if (event.target.matches('.mageplaza-fbt-detail .detailed-node')) {
                            self._showHideDetail(event.target);
                        }
                    });

                    element.addEventListener('click', function (event) {
                        if (event.target.matches('.mageplaza-fbt-add-to-cart button.action.mpfbt-tocart')) {
                            if (self.options.usePopup !== '1') {
                                // self._addValidation();
                            }
                        }
                    });
                    if (self.options.usePopup === '1') {
                        element.addEventListener('change', function (event) {
                            if (event.target.matches('#mpfbt-popup-content .mageplaza-fbt-grouped .mageplaza-fbt-grouped-qty')) {
                                self._reloadGroupedPrice(event.target);
                                let totalSelectedGrouped = document.querySelector('.mpfbt-total-items-value');
                                if (totalSelectedGrouped) {
                                    totalSelectedGrouped.innerText = self._countSelectedItems();
                                }
                            }
                        });
                        element.querySelectorAll('#mpfbt-popup-content  .product-custom-option').forEach(function (option) {
                            option.addEventListener('change', (event) => {    console.log('bbbbbb'); self._onOptionChanged(event.target)});
                        });
                    }

                },
                _bind () {
                    var self = this;
                    element.querySelectorAll('.mageplaza-fbt-rows .related-checkbox').forEach(function (checkbox) {
                        checkbox.click();
                    });
                    element.querySelectorAll('.mageplaza-fbt-rows .mageplaza-fbt-grouped').forEach(function (groupedElement) {
                        self._reloadGroupedPrice(groupedElement);
                    });
                    if (this.options.usePopup === '1') {
                        document.querySelectorAll('.mageplaza-fbt-rows ul li').forEach(function (listItem) {
                            var relatedCheckbox = listItem.querySelector('.related-checkbox');
                            var productId       = relatedCheckbox.getAttribute('data-mageplaza-fbt-product-id');
                            var productInput    = document.getElementById('mpfbt-product-input-' + productId);

                            if (!relatedCheckbox.checked) {
                                productInput.value = '';
                            } else {
                                productInput.value = '1';
                            }
                        });
                    }
                },
                _renderShowDetail: function () {
                    document.querySelectorAll('.mageplaza-fbt-rows .mageplaza-fbt-option-product div').forEach(function (el) {
                        var html = '';
                        if (el.children.length > 0) {
                            var closestLi     = el.closest('li');
                            var detailElement = closestLi.querySelector('.mageplaza-fbt-detail');
                            html += '<a class="detailed-node not-active" href="javascript:void(0)">';
                            html += 'Show details';
                            html += '</a>';
                            if (detailElement && detailElement.children.length === 0) {
                                detailElement.innerHTML = html;
                            }
                        }
                    });
                },
                _reloadGroupedPrice (element) {
                    var totalPrice      = 0;

                    if(this.options.usePopup === '1') {
                        var productDetail = element.closest('.mpfbt-popup-product-detail');
                        var productInput = productDetail.querySelector('.mpfbt-product-input');
                        var productId = productInput.getAttribute('data-mpfbt-popup-product-id');

                        var qtyElements = document.querySelectorAll(
                            '#mpfbt-popup-content #mageplaza-fbt-super-product-table-' + productId + ' .mageplaza-fbt-grouped-qty'
                        );
                        qtyElements.forEach(function (qtyElement) {
                            var price = 0;
                            if (parseFloat(qtyElement.value) > 0) {
                                var qty = parseFloat(qtyElement.value);
                                var priceAmount = parseFloat(qtyElement.getAttribute('data-child-product-price-amount'));
                                price = qty * priceAmount;
                            }
                            qtyElement.setAttribute('data-child-product-price-total', price);
                            totalPrice += parseFloat(qtyElement.getAttribute('data-child-product-price-total'));
                        });
                    } else {
                        var listItem        = element.closest('li');
                        var relatedCheckbox = listItem.querySelector('.related-checkbox');
                        var productId       = relatedCheckbox.getAttribute('data-mageplaza-fbt-product-id');
                        var quantityInputs = document.querySelectorAll('.mageplaza-fbt-rows #mageplaza-fbt-super-product-table-' + productId + ' .mageplaza-fbt-grouped-qty');
                        quantityInputs.forEach(function (input) {
                            var price = 0;

                            if (parseFloat(input.value) > 0) {
                                price = parseFloat(input.value) * parseFloat(input.getAttribute('data-child-product-price-amount'));
                            }

                            input.setAttribute('data-child-product-price-total', price);

                            totalPrice += parseFloat(input.getAttribute('data-child-product-price-total')) || 0;
                        });
                    }

                    document.querySelectorAll('.mageplaza-fbt-price-' + productId).forEach((priceElement) => {
                        if (priceElement) {
                            priceElement.setAttribute('data-price-amount', totalPrice);
                        }
                    });


                    this._reloadTotalPrice();
                },
                _reloadTotalPrice () {
                    var totalPrice = 0;
                    var totalPricePopup = 0;
                    var count      = 0;
                    var self       = this;
                    if (this.options.usePopup === '1') {
                        var productInputs = document.querySelectorAll('#mpfbt-popup-content .mpfbt-product-input');
                        productInputs.forEach(function (input) {
                            if (input.value) {
                                let selectorCheckBox = `.mageplaza-fbt-rows li input[name="${input.name}"]`;
                                let inpCheck = document.querySelector(selectorCheckBox);
                                var closestRow   = input.closest('tr');
                                var priceElement = closestRow.querySelector('.item-price');
                                var priceAmount  = parseFloat(priceElement.getAttribute('data-price-amount'));
                                if(inpCheck) {
                                    var closestListItem = inpCheck.closest('li');
                                    var priceElementCheckBox    = closestListItem.querySelector('.item-price');
                                    priceElementCheckBox.setAttribute('data-price-amount', priceAmount);
                                }
                                totalPricePopup += priceAmount;
                                priceElement.innerHTML = hyva.formatPrice(priceAmount);
                            }
                        });
                        var relatedCheckboxes = document.querySelectorAll('.mageplaza-fbt-rows .related-checkbox');
                        relatedCheckboxes.forEach(function (checkbox) {
                            var closestListItem = checkbox.closest('li');
                            var priceElement    = closestListItem.querySelector('.item-price');
                            var priceAmount     = priceElement.getAttribute('data-price-amount');
                            priceElement.innerHTML = hyva.formatPrice(priceAmount);

                        });
                    }
                    document.querySelectorAll('.mageplaza-fbt-rows .related-checkbox').forEach(function (checkbox) {
                        var listItem     = checkbox.closest('li');
                        var priceElement = listItem.querySelector('.item-price');
                        var priceAmount  = parseFloat(priceElement.getAttribute('data-price-amount'));

                        if (checkbox.checked) {
                            totalPrice += priceAmount;
                            self._reloadImageProductList(checkbox, true);
                            count++;
                        } else {
                            self._reloadImageProductList(checkbox, false);
                        }

                        priceElement.innerHTML = hyva.formatPrice(priceAmount);
                    });

                    var priceBox = document.querySelector('.mageplaza-fbt-price-box');
                    if (count === 0) {
                        if (!priceBox.classList.contains('mageplaza-fbt-hidden')) {
                            priceBox.classList.add('mageplaza-fbt-hidden');
                        }
                    } else {
                        priceBox.classList.remove('mageplaza-fbt-hidden');
                    }

                    document.querySelectorAll('.mageplaza-fbt-price-wrapper').forEach(priceWrapper=>{
                        if (priceWrapper) {
                            priceWrapper.setAttribute('data-price-amount', totalPrice);
                        }
                    });

                    document.querySelectorAll('.mageplaza-fbt-price').forEach(priceDisplay =>{
                        if (priceDisplay) {
                            priceDisplay.innerHTML = hyva.formatPrice(totalPrice);
                        }
                    });

                    self._reloadButtonLabel(count);
                },
                _reloadImageProductList (element, checked) {
                    if (this.options.useSlider === true) {
                        return;
                    }
                    var productId = element.getAttribute('data-mageplaza-fbt-product-id');
                    if (checked) {
                        document.querySelector('.mageplaza-fbt-item-' + productId)?.classList.remove('mageplaza-fbt-hidden');
                        document.querySelector('.mageplaza-fbt-plus-' + productId)?.classList.remove('mageplaza-fbt-hidden');
                    } else {
                        document.querySelector('.mageplaza-fbt-item-' + productId)?.classList.add('mageplaza-fbt-hidden');
                        document.querySelector('.mageplaza-fbt-plus-' + productId)?.classList.add('mageplaza-fbt-hidden');
                    }

                    var firstVisibleItem = document.querySelector('.mageplaza-fbt-image-box li:not(.mageplaza-fbt-hidden)');
                    if (firstVisibleItem && firstVisibleItem.classList.contains('product-item-plus')) {
                        firstVisibleItem.classList.add('mageplaza-fbt-hidden');
                    }
                },
                _reloadButtonLabel (number) {
                    var buttonCartLabel      = 'Add %s to Cart';
                    var buttonWishlistLabel  = 'Add %s to Wishlist';
                    var numberLessThanTwelve = [
                        'zero', 'one', 'two', 'three', 'four', 'five',
                        'six', 'seven', 'eight', 'nine', 'ten',
                        'eleven', 'twelve'
                    ];
                    var num                  = parseInt(number, 10);
                    var replace              = '';

                    if (num > 1) {
                        replace = ' all';
                        if (num <= 12) {
                            replace += ' ' + numberLessThanTwelve[num];
                        }
                    }

                    buttonCartLabel     = buttonCartLabel.replace(' %s', replace);
                    buttonWishlistLabel = buttonWishlistLabel.replace(' %s', replace);

                    var cartButton = document.querySelector('.mageplaza-fbt-add-to-cart button');
                    if (cartButton) {
                        cartButton.setAttribute('title', buttonCartLabel);
                        var cartButtonText = cartButton.querySelector('span');
                        if (cartButtonText) {
                            cartButtonText.textContent = buttonCartLabel;
                        }
                    }

                    var wishlistButton = document.querySelector('.mageplaza-fbt-add-to-wishlist button');
                    if (wishlistButton) {
                        wishlistButton.setAttribute('title', buttonWishlistLabel);
                        var wishlistButtonText = wishlistButton.querySelector('span');
                        if (wishlistButtonText) {
                            wishlistButtonText.textContent = buttonWishlistLabel;
                        }
                    }

                    return this;
                },
                _showHideDetail (el) {
                    if (el.classList.contains('not-active')) {
                        el.classList.remove('not-active');
                        el.innerHTML = 'Hide details';
                        el.closest('li').querySelectorAll('.mageplaza-fbt-option-product').forEach(e => {
                            e.classList.remove('mageplaza-fbt-hidden');
                        })

                    } else {
                        el.classList.add('not-active');
                        el.innerHTML = 'Show details';
                        el.closest('li').querySelectorAll('.mageplaza-fbt-option-product').forEach(e => {
                            e.classList.add('mageplaza-fbt-hidden');
                        })
                    }
                },
                _addToWishList: function (url) {
                    if (url) {
                        const formData = new FormData(element);
                        const wishListData = new FormData();
                        formData.forEach((value, key) => {
                            if (value === 'on') {
                                wishListData.append(key, value);
                            }
                        });
                        wishListData.append('form_key',hyva.getFormKey())
                        fetch(url,{
                            headers: {
                                "X-Requested-With": "XMLHttpRequest"
                            },
                            body: wishListData,
                            method: "POST",
                        }).then(response => {
                            if (response.redirected) {
                                window.location.href = response.url;
                            }
                        }).catch(e => {
                            console.log(e.message);
                        })
                    }
                },
                myFormSubmit (event) {
                    event.preventDefault();
                    let allMessages = element.querySelectorAll('.mageplaza-fbt-rows ul li ul.messages');
                    allMessages.forEach(el => {
                        el.remove();
                    });
                    element.querySelectorAll('.mageplaza-fbt-rows ul li').forEach(function (listItem) {
                        let selectTypesFlag = false;

                        const relatedCheckbox = listItem.querySelector('.related-checkbox');
                        if (relatedCheckbox && !relatedCheckbox.checked) {
                            const clickableLink = listItem.querySelector('.mageplaza-fbt-detail a:not(.not-active)');
                            if (clickableLink) clickableLink.click();
                            return;
                        }

                        const groupedElements = listItem.querySelectorAll('.mageplaza-fbt-grouped');
                        if (groupedElements.length > 0) {
                            let active = false;

                            listItem.querySelectorAll('.mageplaza-fbt-grouped-qty').forEach(function (qtyElement) {
                                const qty = parseFloat(qtyElement.value);
                                if (qty > 0) {
                                    active = true;
                                }
                            });

                            if (!active) {
                                const notActiveLink = listItem.querySelector('.mageplaza-fbt-detail a.not-active');
                                if (notActiveLink) notActiveLink.click();
                            }
                        }

                        listItem.querySelectorAll('[aria-required="true"]').forEach(function (requiredElement) {
                            const optionType = requiredElement.type;

                            if (optionType !== 'hidden' && !requiredElement.classList.contains('qty')) {
                                switch (optionType){
                                    case 'text':
                                    case 'textarea':
                                    case 'select-one':
                                        selectTypesFlag = requiredElement.value;
                                        break;

                                    case 'radio':
                                        selectTypesFlag      = false;
                                        const radioGroupName = requiredElement.name;
                                        document.querySelectorAll(`[name="${radioGroupName}"]`).forEach(function (radio) {
                                            if (radio.checked) {
                                                selectTypesFlag = true;
                                            }
                                        });
                                        break;

                                    case 'select-multiple':
                                        selectTypesFlag = false;
                                        requiredElement.querySelectorAll('option').forEach(function (option) {
                                            if (option.selected) {
                                                selectTypesFlag = true;
                                            }
                                        });
                                        break;

                                    case 'checkbox':
                                        selectTypesFlag             = false;
                                        const multiSelectCheckboxes = listItem.querySelectorAll('.mg-fbt-options-list .mp-fbt-multi-select');
                                        multiSelectCheckboxes.forEach(function (checkbox) {
                                            if (checkbox.checked) {
                                                selectTypesFlag = true;
                                            }
                                        });
                                        break;

                                    case 'file':
                                        selectTypesFlag = requiredElement.value && !requiredElement.disabled;
                                        break;
                                }

                                if (!selectTypesFlag) return false;
                            }
                        });

                        if (!selectTypesFlag && groupedElements.length === 0) {
                            const notActiveLink = listItem.querySelector('.mageplaza-fbt-detail a.not-active');
                            if (notActiveLink) notActiveLink.click();
                        }
                    });
                    this.validate()
                    .then(() => {
                        event.target.submit()
                    })
                    .catch((invalid) => {
                        if (invalid.length > 0) {
                            invalid[0].focus();
                        }
                    });
                },
                _showPopup (event, singleProductId) {
                    var mpFbtPopupContent = document.getElementById('mpfbt-popup-content');
                    var addToCartBtn      = document.querySelector('button#mpfbt-btn-addtocart');
                    if (singleProductId !== null) {
                        var productInputs = mpFbtPopupContent.querySelectorAll('.mpfbt-product-input');
                        productInputs.forEach(function (input) {
                            input.value = '';
                        });

                        var productDetails = mpFbtPopupContent.querySelectorAll('.mpfbt-popup-product-detail');
                        productDetails.forEach(function (detail) {
                            detail.style.display = 'none';
                        });

                        document.querySelector('#mpfbt-popup .mpfbt-total-items').style.display       = 'none';
                        document.querySelector('#mpfbt-popup .mageplaza-fbt-price-box').style.display = 'none';

                        addToCartBtn.textContent = 'Add to Cart';
                        addToCartBtn.setAttribute('title', 'Add to Cart');

                        document.getElementById('mpfbt-product-input-' + singleProductId).value = 1;

                        var singleProductDetail = mpFbtPopupContent.querySelector(
                            '.mpfbt-popup-product-detail[data-mpfbt-popup-product-id="' + singleProductId + '"]'
                        );
                        if (singleProductDetail) {
                            singleProductDetail.style.display = 'table-row';
                        }
                    } else {
                        var productRows = document.querySelectorAll('.mageplaza-fbt-rows ul li');

                        productRows.forEach(function (row) {
                            var relatedCheckbox = row.querySelector('.related-checkbox');
                            var productId       = relatedCheckbox.dataset.mageplazaFbtProductId;

                            if (!relatedCheckbox.checked) {
                                document.getElementById('mpfbt-product-input-' + productId).value = '';
                                var productDetail                                                 = mpFbtPopupContent.querySelector(
                                    '.mpfbt-popup-product-detail[data-mpfbt-popup-product-id="' + productId + '"]'
                                );
                                if (productDetail) {
                                    productDetail.style.display = 'none';
                                }
                            } else {
                                document.getElementById('mpfbt-product-input-' + productId).value = 1;
                                var productDetail                                                 = mpFbtPopupContent.querySelector(
                                    '.mpfbt-popup-product-detail[data-mpfbt-popup-product-id="' + productId + '"]'
                                );
                                if (productDetail) {
                                    productDetail.style.display = 'table-row';
                                }
                            }
                        });
                    }
                    window.dispatchEvent(
                        new CustomEvent('hyva-modal-show', {detail: {dialog: 'mp-fbt-modal-options'}})
                    );
                },
                _onOptionChanged (element) {
                    let optionPrice       = 0;
                    const changes         = {};
                    const optionName      = element.name;
                    const optionType      = element.type;
                    let productId = null;
                    let productPrice = null;
                    let parentElement   = null;

                    if(this.options.usePopup === '1') {
                        parentElement   = element.closest('tr');
                        let inputElement = parentElement.querySelector('.mpfbt-product-input');
                        productId       = inputElement.getAttribute('data-mpfbt-popup-product-id');
                        productPrice      = parseFloat(inputElement.getAttribute('data-price-amount'));
                    } else {
                        parentElement   = element.closest('li');
                        let checkboxElement = parentElement.querySelector('.related-checkbox');
                        productId       = checkboxElement.getAttribute('data-mageplaza-fbt-product-id');
                        productPrice      = parseFloat(checkboxElement.getAttribute('data-price-amount'));
                    }
                    switch (optionType){
                        case 'text':
                        case 'textarea':
                            optionPrice         = parseFloat(
                                parentElement.querySelector('div.field .price-wrapper').getAttribute('data-price-amount')
                            );
                            changes[optionName] = element.value ? optionPrice : 0;
                            break;

                        case 'radio':
                            optionPrice = parseFloat(element.getAttribute('price'));
                            if (element.checked) {
                                changes[optionName] = optionPrice;
                            }
                            break;

                        case 'select-one':
                            const selectedOption = element.options[element.selectedIndex];
                            if (selectedOption && selectedOption.getAttribute('price')) {
                                optionPrice = parseFloat(selectedOption.getAttribute('price'));
                            }
                            changes[optionName] = optionPrice;
                            break;

                        case 'select-multiple':
                            optionPrice = 0;
                            Array.from(element.options).forEach(function (option) {
                                if (option.selected && option.getAttribute('price')) {
                                    optionPrice += parseFloat(option.getAttribute('price'));
                                }
                            });
                            changes[optionName] = optionPrice;
                            break;

                        case 'checkbox':
                            optionPrice      = 0;
                            const checkboxes = parentElement.querySelectorAll('.options-list .product-custom-option');
                            checkboxes.forEach(function (checkbox) {
                                if (checkbox.checked) {
                                    optionPrice += parseFloat(checkbox.getAttribute('price'));
                                }
                            });
                            changes[optionName] = optionPrice;
                            break;

                        case 'file':
                            if (element.value && !element.disabled) {
                                optionPrice = parseFloat(
                                    parentElement.querySelector('div.field .price-wrapper').getAttribute('data-price-amount')
                                );
                            }
                            changes[optionName] = optionPrice;
                            break;
                    }
                    Object.assign(this.cache.priceObject, changes);

                    Object.keys(this.cache.priceObject).forEach(function (key) {
                        const value               = this.cache.priceObject[key];
                        let productIdUpdate = null;
                        if(this.options.usePopup === '1') {
                            let parentElementUpdate = document.querySelector(`[name="${key}"]`).closest('tr');
                            productIdUpdate     = parentElementUpdate.querySelector('.mpfbt-product-input').getAttribute('data-mpfbt-popup-product-id');
                        } else {
                            let parentElementUpdate = document.querySelector(`[name="${key}"]`).closest('li');
                            productIdUpdate     = parentElementUpdate.querySelector('.related-checkbox').getAttribute('data-mageplaza-fbt-product-id');
                        }
                        if (productId === productIdUpdate) {
                            productPrice += parseFloat(value);
                        }
                    }, this);
                    parentElement.querySelector('.item-price').setAttribute('data-price-amount', productPrice);
                    this._reloadTotalPrice();
                },
                _countSelectedItems: function () {
                    var count = 0;
                    document.querySelectorAll('.mageplaza-fbt-rows ul li').forEach(function (listItem) {
                        var checkbox  = listItem.querySelector('.related-checkbox');
                        var productId = checkbox.getAttribute('data-mageplaza-fbt-product-id');

                        if (checkbox.checked) {
                            var groupedItems = document.querySelectorAll('#mageplaza-fbt-super-product-table-' + productId + ' .mageplaza-fbt-grouped-qty');

                            if (groupedItems.length > 0) {
                                groupedItems.forEach(function (groupedItem) {
                                    if (parseInt(groupedItem.value) > 0) {
                                        count += parseInt(groupedItem.value);
                                    }
                                });
                            } else {
                                count++;
                            }
                        }
                    });

                    return count;
                },
                eventListeners: {
                    ['@reload-price-frequently-bought.window'] () {
                        this._reloadTotalPrice();
                    }
                }

            }
        }
    </script>

    <style>
        .mageplaza-fbt-carousel-container {
            width: 55%;
        }
        #mpfbt-popup-content .product-image-photo {
            max-width: 75px;
        }
        #mageplaza-fbt-carousel .splide__arrow {
            display: flex !important;
        }

        #mageplaza-fbt-carousel .splide__arrow--prev {
            left: -2.6em;
        }

        #mageplaza-fbt-carousel .splide__arrow--next {
            right: -2.6em;
        }

        #mageplaza-fbt-carousel .splide__pagination {
            display: none;
        }

        .mageplaza-fbt-image-box li.product-item .fbt-product-item-info, .mageplaza-fbt-image-box li.first-item {
            position: relative;
            width: auto;
        }

        .mageplaza-fbt-image-box li.product-item .related-checkbox {
            position: absolute;
            right: 20px;
            z-index: 15;
        }


        @media (max-width: 1023px) {
            .mageplaza-fbt-image-box {
                float: none;
            }

        }

        @media (max-width: 767px) {
            .mageplaza-fbt-carousel-container {
                width: 100% !important;
            }
            .mageplaza-fbt-carousel-container {
                float: none;
            }

            .mageplaza-fbt-image-box {
                display: flex;
                flex-direction: column;
                align-items: center;
            }

            .product-item-plus {
                margin-top: 0;
            }

            .mageplaza-fbt-image-box .product-item-actions .actions-primary {
                display: inline-block;
            }
            #mpfbt-popup-content tbody tr td[data-th="Options"] div {
                width: min-content;
            }
            #mpfbt-popup-content tbody tr td[data-th="Options"] input[type="text"], #mpfbt-popup-content tbody tr td[data-th="Options"] select {
                max-width: 125px;
            }
        }

        .mageplaza-fbt-option-product .bundle-options-container .bundle-options-wrapper,
        .mageplaza-fbt-option-product .bundle-options-container .product-options-wrapper {
            width: auto;
        }

        .mageplaza-fbt-image-box li.product-item {
            width: unset !important;
        }

        .column.main .mageplaza-fbt-image-box .product-item {
            margin-top: 10px;
        }

        @media (min-width: 1024px) {
            .mageplaza-fbt-price-box {
                margin-top: 100px;
                margin-left: 15px;
            }
        }

        @media (min-width: 1200px) {
            .mageplaza-fbt-content .products-grid .fbt-product-item-info:hover,
            .mageplaza-fbt-content .products-grid .fbt-product-item-info.active {
                background: #ffffff;
                box-shadow: 3px 4px 4px 0 rgba(0, 0, 0, 0.3);
                border: 1px solid #bbbbbb;
                margin: -10px;
                padding: 9px;
                position: relative;
                z-index: 9;
            }

            .mageplaza-fbt-image-box li.product-item .fbt-product-item-info:hover input {
                margin-top: 11px;
                margin-right: 14px;
                padding: -9px;
            }
        }

        <?php if ($block->getNumberOfProductOnSlider() === 1): ?>
        <?php if ($block->getProductLayoutDesign() === '3columns'): ?>
        .mageplaza-fbt-image-box {
            width: auto;
        }

        <?php else: ?>
        .mageplaza-fbt-image-box {
            width: 40%;
        }

        <?php endif; ?>


        @media (max-width: 1439px) {
            .mageplaza-fbt-image-box {
                width: 45%;
            }

        }

        @media (max-width: 1023px) {
            .mageplaza-fbt-image-box {
                width: 66%;
            }
        }

        @media (max-width: 767px) {
            .mageplaza-fbt-image-box {
                width: 75%;
            }
        }

        @media (max-width: 639px) {
            .mageplaza-fbt-image-box {
                width: 90%;
            }

        }

        <?php elseif ($block->getNumberOfProductOnSlider() === 2): ?>
        .mageplaza-fbt-image-box {
            width: 60%;
        }

        @media (max-width: 1439px) {
            .mageplaza-fbt-image-box {
                width: 66%;
            }
        }

        @media (max-width: 1023px) {
            .mageplaza-fbt-image-box {
                width: 90%;
            }
        }

        @media (max-width: 767px) {
            .mageplaza-fbt-image-box {
                width: 100%;
            }

        }


        <?php else: ?>

        @media (max-width: 1439px) {

        }

        @media (max-width: 1023px) {
            .mageplaza-fbt-image-box {
                width: 90%;
            }
        }

        @media (max-width: 767px) {
            .mageplaza-fbt-image-box {
                width: 100%;
            }

        }

        <?php if ($block->getSeparatorImage()): ?>
        .product-item-plus {
            margin-left: -12px;
        }

        <?php endif; ?>
        <?php endif; ?>
    </style>
<?php endif; ?>
