<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

use FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons;
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\HeroiconsSolid;
use Hyva\Theme\ViewModel\ProductCompare;
use Hyva\Theme\ViewModel\ProductListItem;
use Hyva\Theme\ViewModel\ProductPage;
use Hyva\Theme\ViewModel\Wishlist;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Helper\Output as CatalogOutputHelper;
use Magento\Framework\Escaper;

// phpcs:disable Magento2.Templates.ThisInTemplate.FoundHelper
// phpcs:disable Generic.Files.LineLength.TooLong

/** @var AbstractProduct $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */

/** @var ProductPage $productViewModel */
$productViewModel = $viewModels->require(ProductPage::class);

/** @var ProductListItem $productListItemViewModel */
$productListItemViewModel = $viewModels->require(ProductListItem::class);

/** @var CatalogOutputHelper $catalogOutputHelper */
$catalogOutputHelper = $this->helper(CatalogOutputHelper::class);

/** @var ProductCompare $compareViewModel */
$compareViewModel = $viewModels->require(ProductCompare::class);
/** @var Wishlist $wishlistViewModel */
$wishlistViewModel = $viewModels->require(Wishlist::class);

$themeicons = $viewModels->require(ThemeIcons::class);

/** @var Magento\Catalog\Model\Product $product */
$product = $block->getData('product');
$imageDisplayArea = $block->getData('image_display_area');
$templateType = $block->getData('template_type');
$viewMode = $block->getData('view_mode');
$showDescription = $block->getData('show_description');
$showAddToWishlist = $wishlistViewModel->isEnabled();
$showAddToCompare = $compareViewModel->showInProductList();
$viewIsGrid = $viewMode === 'grid';

if (!$product) {
    return '';
}
$productId = $product->getId();
$uniqueId = '_' . uniqid();

$hideDetails       = $block->getData('hide_details') ?: false;
$hideRatingSummary = $block->getData('hide_rating_summary') ?: false;
?>
<div class="item product product-item card flex flex-col w-full p-1 <?= $viewIsGrid ? '' : 'md:flex-row' ?>">
    <?php $productImage = $productViewModel->getImage($product, $imageDisplayArea); ?>
    <?php // Product Image ?>
    <?php if ($showAddToWishlist): ?>
        <button x-data="initWishlist()"
                @click.prevent="addToWishlist(<?= (int)$productId ?>)"
                aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Wish List')) ?>"
                type="button"
                class="absolute border-0 right-2 top-2">
            <?= $themeicons->heartRegularHtml(
                "hover:text-red-600 text-secondary hover:text-main",
                20,
                18
            ) ?>
        </button>
    <?php endif; ?>
    <a href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>"
       class="product photo product-item-photo block mx-auto mb-3 <?= $viewIsGrid ? '' : 'md:w-2/6 md:mb-0 md:mr-5' ?>"
       tabindex="-1">
        <img class="hover:shadow-sm object-contain"
             loading="lazy"
             x-data=""
             @update-gallery-<?= (int)$productId ?>.window="$el.src = $event.detail"
             alt="<?= $escaper->escapeHtmlAttr($productImage->getLabel()) ?>"
             title="<?= $escaper->escapeHtmlAttr($productImage->getLabel()) ?>"
             src="<?= $escaper->escapeUrl($productImage->getImageUrl()) ?>"
             width="<?= $escaper->escapeHtmlAttr($productImage->getWidth()) ?>"
             height="<?= $escaper->escapeHtmlAttr($productImage->getHeight()) ?>"
        />
    </a>
    <div class="product-info flex flex-col flex-grow">
        <?php $productNameStripped = $block->stripTags($product->getName(), null, true); ?>
        <div
            class="mt-2 mb-1 items-center justify-center text-primary">
            <a class="product-item-link"
               href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>">
                <?= /* @noEscape */
                $catalogOutputHelper->productAttribute($product, $product->getName(), 'name') ?>
            </a>
        </div>

        <script>
            function initPriceBox_<?= /** @noEscape */ $uniqueId ?>() {
                return {
                    updatePrice(priceData) {
                        const regularPriceLabel = this.$el.querySelector('.normal-price .price-label');
                        const regularPriceElement = this.$el.querySelector('.normal-price .price-wrapper .price');
                        if (priceData.finalPrice.amount < priceData.oldPrice.amount) {
                            regularPriceLabel.classList.add('hidden');
                        } else {
                            regularPriceLabel.classList.remove('hidden');
                        }
                        regularPriceElement.innerText = hyva.formatPrice(priceData.finalPrice.amount);
                    }
                }
            }
        </script>
        <div class="pt-1 text-gray-900"
             x-data="initPriceBox_<?= /** @noEscape */$uniqueId ?>()"
             @update-prices-<?= (int)$productId ?>.window="updatePrice($event.detail);"
        >
            <?= /* @noEscape */
            $productListItemViewModel->getProductPriceHtml($product) ?>
        </div>

        <div x-data=""
             class="flex flex-wrap items-center justify-center">
            <?php if ($product->isSaleable()): ?>
                <a href="#"
                   @click.prevent="$dispatch('triggerrelatedmodal', { productId: <?= $productId ?> })"
                   class="leading-4 w-full btn-primary
                        <?= $viewIsGrid ? 'mr-auto' : 'mr-auto md:mr-0' ?> text-center py-2"
                   aria-label="<?= $escaper->escapeHtmlAttr(__('Choose options')) ?>"
                >
                <span
                    class="leading-3 tracking-widerer font-bold inline <?= $viewIsGrid ? 'md:ml-0 lg:inline' : '' ?> uppercase text-sm">
                    <?= $escaper->escapeHtml(__('Choose options')) ?>
                </span>
                </a>
            <?php else : ?>
                <div class="mb-4 text-sm leading-4 text-center uppercase lg:text-lg lg:leading-5 tracking-widerer">
                    <?= $escaper->escapeHtml(__('Out of stock')) ?>
                </div>
            <?php endif ?>
        </div>
    </div>
</div>

<?php if ($product->isSaleable()): ?>
    <div x-cloak
         x-data="relatedProductModal<?= $productId ?>()"
         @triggerrelatedmodal.window="triggerRelatedProductModal($event.detail.productId)"
         x-on:keydown.escape.prevent.stop="showModal = false"
         x-show="showModal"
         role="dialog"
         aria-modal="true"
         class="fixed inset-0 overflow-y-auto z-50"
         id="related-model-<?= $product->getId() ?>">
        <div x-show="showModal"
             x-transition.opacity class="fixed inset-0 flex h-screen justify-center items-center bg-black bg-opacity-25">
            <form method="post"
                  action="<?= $escaper->escapeUrl($productViewModel->getAddToCartUrl($product)) ?>"
                  class="w-full p-4 bg-white relative z-50 lg:w-3/4 lg:flex
              <?= $viewIsGrid ? '' : 'md:flex-row' ?>"
                <?php if ($product->getOptions()): ?>
                    enctype="multipart/form-data"
                <?php endif; ?>
            >
                <a href="#"
                   class="absolute top-4 right-4"
                   @click.prevent="showModal = false">
                    <?= $themeicons->crossHtml('w-8 h-8') ?>
                </a>
                <?= /** @noEscape */
                $block->getBlockHtml('formkey') ?>

                <a href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>"
                   class="product photo product-item-photo block mx-auto mb-3 md:w-1/2"
                   tabindex="-1">
                    <img class="hover:shadow-sm object-contain m-auto"
                         loading="lazy"
                         x-data=""
                         @update-gallery-<?= (int)$productId ?>.window="$el.src = $event.detail"
                         alt="<?= $escaper->escapeHtmlAttr($productImage->getLabel()) ?>"
                         title="<?= $escaper->escapeHtmlAttr($productImage->getLabel()) ?>"
                         src="<?= $escaper->escapeUrl($productImage->getImageUrl()) ?>"
                         width="<?= $escaper->escapeHtmlAttr($productImage->getWidth()) ?>"
                         height="<?= $escaper->escapeHtmlAttr($productImage->getHeight()) ?>"
                    />
                </a>

                <div class="modal-product-content px-8 md:w-1/2">
                    <a class="product-item-link text-2xl font-bold text-black"
                       href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>">
                        <?= /* @noEscape */
                        $catalogOutputHelper->productAttribute($product, $product->getName(), 'name') ?>
                    </a>

                    <div class="pt-1"><?= __('Sku') ?>: <?= $product->getSku() ?></div>

                    <div class="pt-1 text-gray-900"
                         x-data="initPriceBox_<?= /** @noEscape */$uniqueId ?>()"
                         @update-prices-<?= (int)$productId ?>.window="updatePrice($event.detail);"
                    >
                        <?= /* @noEscape */
                        $productListItemViewModel->getProductPriceHtml($product) ?>
                    </div>

                    <input type="hidden" name="product" value="<?= (int)$productId ?>"/>
                    <?php if ($product->isAvailable() && !$hideDetails): ?>
                        <?= $block->getProductDetailsHtml($product) ?>
                    <?php endif; ?>

                    <div class="lg:flex justify-between flex-col mb-4">
                        <div class="mt-auto flex flex-wrap justify-center items-center">
                            <?php if ($product->isSaleable()): ?>
                                <button class="w-auto btn btn-primary justify-center text-sm
                            <?= $viewIsGrid ? 'mr-auto' : 'mr-auto md:mr-0' ?>"
                                        aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Cart')) ?>"
                                >
                                    <?= $escaper->escapeHtml(__('Add to Basket')) ?>
                                </button>
                            <?php endif; ?>
                            <?php if ($addToBlock = $block->getChildBlock('addto')): ?>
                                <?= $addToBlock->setProduct($product)->getChildHtml() ?>
                            <?php endif; ?>
                        </div>

                        <a href="<?= $product->getProductUrl() ?>"
                           class="inline-block mt-4">
                            <span class="border-b-2 border-black pb-2 font-semibold text-black"><?= __('Full product details') ?></span>
                        </a>
                    </div>
                </div>
            </form>

        </div>

        <script>
            function relatedProductModal<?= $productId ?>()
            {
                return {
                    productId : <?= $productId ?>,
                    showModal : false,
                    triggerRelatedProductModal(productId) {
                        if (productId === this.productId) {
                            this.showModal = true;
                        } else {
                            this.showModal = false;
                        }
                    }
                }
            }
        </script>
    </div>
<?php endif ?>

