<?php

declare(strict_types=1);

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 \FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons $icons */
$icons = $viewModels->require(\FoundationCommerce\ThemeViewModels\ViewModels\ThemeIcons::class);

/** @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);

/** @var HeroiconsOutline $heroiconsOutline */
$heroiconsOutline = $viewModels->require(HeroiconsOutline::class);
/** @var HeroiconsSolid $heroiconsSolid */
$heroiconsSolid = $viewModels->require(HeroiconsSolid::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;

$sliderType = $block->getData('slider_type') ?: false;
?>

<?php if ($product->isSaleable()): ?>
<form method="post"
    action="<?= $escaper->escapeUrl($productViewModel->getAddToCartUrl($product)) ?>"
    class="item product product-item product_addtocart_form card flex flex-col w-full <?= $viewIsGrid ? '' : 'md:flex-row'?>"
    <?php if ($product->getOptions()): ?>
    enctype="multipart/form-data"
    <?php endif; ?>
>
    <?= /** @noEscape */ $block->getBlockHtml('formkey') ?>
    <input type="hidden" name="product" value="<?= (int)$productId ?>"/>
    <?php else: ?>
    <div class="item product product-item card flex flex-col w-full <?= $viewIsGrid ? '' : 'md:flex-row' ?>">
    <?php endif; ?>
    <?php $productImage = $productViewModel->getImage($product, $imageDisplayArea); ?>
    <?php // Product Image ?>
    <div class="relative">
        <div class="absolute">
            <?php if ($labels = $block->getChildBlock('labels')): ?> <?= $labels->setProduct($product)->toHtml(); ?> <?php endif; ?>
        </div>
    <?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">
                <?= $icons->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="object-contain hover:shadow-sm"
             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>
    <div class="px-1 py-3<?php if ($sliderType != 'related') : ?> md:p-3<?php endif; ?> product-info">
        <?php $productNameStripped = $block->stripTags($product->getName(), null, true); ?>
        <div class="mt-2 mb-3">
            <a class="product-item-link"
               href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>">
                <?= /* @noEscape */ $catalogOutputHelper->productAttribute($product, $product->getName(), 'name') ?>
            </a>
        </div>

        <?php if (!$hideRatingSummary): ?>
        <div class="py-1 mx-auto <?= $viewIsGrid ? '' : 'md:mx-0 md:w-auto' ?> hidden">
            <?= $block->getReviewsSummaryHtml($product, 'short') ?>
        </div>
        <?php endif; ?>
         <div class="hidden">
        <?php if ($product->isAvailable() && !$hideDetails): ?>
            <?= $block->getProductDetailsHtml($product) ?>
        <?php endif; ?>
        </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="mt-auto"
             x-data="initPriceBox_<?= /** @noEscape */ $uniqueId ?>()"
             @update-prices-<?= (int)$productId ?>.window="updatePrice($event.detail);"
        >
            <?= /* @noEscape */ $productListItemViewModel->getProductPriceHtml($product) ?>
        </div>

        <div class="item_action">
            <?php if ($product->isSaleable()): ?>
                <a href="<?= $escaper->escapeUrl($product->getProductUrl()); ?>"
                   class="w-full btn btn-primary mx-auto"
                   aria-label="<?= $escaper->escapeHtmlAttr(__('View product')) ?>"
                >
                    <?= $escaper->escapeHtml(__('View product')) ?>
                </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>
<?php if ($product->isSaleable()): ?>
</form>
<?php else: ?>
</div>
<?php endif; ?>
