<?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 Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\HeroiconsSolid;
use Hyva\Theme\ViewModel\BlockJsDependencies;
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\Catalog\ViewModel\Product\OptionsData as ProductOptionsData;
use Magento\Framework\Escaper;

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

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

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);

/** @var HeroiconsSolid $heroiconsSolid */
$heroiconsSolid = $viewModels->require(HeroiconsSolid::class);

/** @var \Magento\Framework\View\Element\Template $block */

$productOptionsViewmodel = $viewModels->require(ProductOptionsData::class);

/** @var Magento\Catalog\Model\Product $product */
if (! ($product = $block->getData('product'))) {
    return;
}
$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';
$productType = $product->getTypeId();
$isProductGroupedOrBundle = $productType === 'bundle' || $productType === "grouped";
$productId = $product->getId();
$options   = $productOptionsViewmodel->getOptionsData($product);

$hideDetails       = $block->getData('hide_details') ?: false;
$hideRatingSummary = $block->getData('hide_rating_summary') ?: false;

$imageCustomAttributes = $product->getData('image_custom_attributes')
    ?? $block->getData('image_custom_attributes')
    ?? [];
$productName = $catalogOutputHelper->productAttribute($product, $product->getName(), 'name');

// Ensure the required JS is rendered on the page
$viewModels->require(BlockJsDependencies::class)->setBlockTemplateDependency($block, 'Magento_Catalog::product/list/js/price-box.phtml');

?>
<?php
$now = new \DateTime();
$specialPrice = $product->getSpecialPrice();
$fromDateRaw = $product->getSpecialFromDate();
$toDateRaw = $product->getSpecialToDate();

$isOnSale = false;

if ($specialPrice && $fromDateRaw) {
    $fromDate = new \DateTime($fromDateRaw);
    $toDate = $toDateRaw ? new \DateTime($toDateRaw) : null;

    if (
        $fromDate <= $now &&
        (!$toDate || $toDate >= $now)
    ) {
        $isOnSale = true;
    }
}


$mode = $block->getRequest()->getParam('product_list_mode');

if (!$mode) {
    $productListBlock = $block->getLayout()->getBlock('category.products.list');
    if ($productListBlock && method_exists($productListBlock, 'getMode')) {
        $mode = $productListBlock->getMode();
    } else {
        $mode = 'grid'; // fallback default mode
    }
}
$priceClass = ($mode === 'list') ? 'text-left' : 'text-center';

?>




<?php if ($product->isSaleable()): ?>
<form method="post"
    action="<?= $escaper->escapeUrl($productViewModel->getAddToCartUrl($product, ['useUencPlaceholder' => true])) ?>"
    class="item product product-item product_addtocart_form card card-interactive grow flex flex-col w-full p-0 <?= $viewIsGrid ? '' : 'md:flex-row' ?>"
    <?php if ($product->getOptions()): ?>
    enctype="multipart/form-data"
    <?php endif; ?>
    <?php foreach ($block->getData('product_data_attributes') ?? [] as $attribute => $include): ?>
        <?php if ($include): ?>
            <?php /** Append data-* attributes based on layout XML arguments */ ?>
            <?= $escaper->escapeHtml(sprintf('data-%s', $attribute)); ?>="<?= $escaper->escapeHtmlAttr($product->getData($attribute)); ?>"
        <?php endif; ?>
    <?php endforeach; ?>
>
    <?= /** @noEscape */ $block->getBlockHtml('formkey') ?>
    <input type="hidden" name="product" value="<?= (int)$productId ?>"/>
    <?php foreach ($options as $optionItem): ?>
    <input type="hidden"
           name="<?= $escaper->escapeHtml($optionItem['name']) ?>"
           value="<?= $escaper->escapeHtml($optionItem['value']) ?>">
    <?php endforeach; ?>
<?php else: ?>
<div class="item product product-item card card-interactive flex flex-col w-full p-0 <?= $viewIsGrid ? '' : 'md:flex-row' ?>"
     <?php foreach ($block->getData('product_data_attributes')  ?? [] as $attribute => $include): ?>
         <?php if ($include): ?>
             <?php /** Append data-* attributes based on layout XML arguments */ ?>
             <?= $escaper->escapeHtml(sprintf('data-%s', $attribute)); ?>="<?= $escaper->escapeHtmlAttr($product->getData($attribute)); ?>"
         <?php endif; ?>
    <?php endforeach; ?>
>
<?php endif; ?>
<?php /* Product Image */ ?>
<a href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>"
   title="<?= $escaper->escapeHtmlAttr($product->getName()) ?>"
   class="relative product photo product-item-photo block mx-auto mb-3 <?= $viewIsGrid ? '' : 'md:w-2/6 md:mb-0 md:shrink-0' ?>"
   tabindex="-1"
>

    <?php if ($isOnSale): ?>
        <div class="absolute bg-red font-medium left-2 px-3 py-1 rounded text-sm text-white top-2">Sale</div>
    <?php endif; ?>

    <?= $block->getImage($product, $imageDisplayArea)
        ->setTemplate('Magento_Catalog::product/list/image.phtml')
        ->setData('custom_attributes', $imageCustomAttributes)
        ->setProductId($productId)
        ->toHtml(); ?>
</a>
<div class="product-info flex flex-col grow <?= $viewIsGrid ? '' : 'md:pl-5 md:w-4/6' ?>">
    <div class="mt-2 mb-1 text-center  <?= $viewIsGrid ? '' : 'md:text-left' ?>">
        <a
            class="product-item-link text-xs md:text-sm lg:text-base font-medium text-black font-inter h-8 md:h-10 lg:min-h-12 line-clamp-2"
            href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>"
            :id="`slide-desc-<?= $escaper->escapeHtmlAttr($product->getId()) ?>-${$id('slider-id')}`"
        >
            <?= /* @noEscape */ $productName ?>
        </a>
    </div>


    <?php if ($product->isAvailable() && !$hideDetails): ?>
        <?= $block->getProductDetailsHtml($product) ?>
    <?php endif; ?>

    <?php if ($showDescription): ?>
        <div class="mt-2 mb-1 items-center justify-center text-primary text-center <?= $viewIsGrid ? '' : 'md:text-left' ?>">
            <?= /* @noEscape */ $productViewModel->getShortDescriptionForProduct($product) ?>
        </div>
    <?php endif; ?>

    <?php if ($isProductGroupedOrBundle): ?>
        <span class="sr-only">
                <?= $escaper->escapeHtml(__('The price depends on the options chosen on the product page')) ?>
            </span>
    <?php endif; ?>

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

    <?php if (!$hideRatingSummary): ?>
        <div class="py-1 mx-auto <?= $viewIsGrid ? '' : 'md:mx-0 md:w-auto' ?>">
            <?= $block->getReviewsSummaryHtml($product, 'short') ?>
        </div>
    <?php endif; ?>
    <div class="mt-auto pt-3 flex flex-wrap items-center gap-y-4 gap-x-2 hidden
            <?= $viewIsGrid ? '' : 'md:justify-center' ?>">
        <?php if ($product->isSaleable()): ?>
            <?php if ($isProductGroupedOrBundle): ?>
                <a
                    href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>"
                    class="w-auto btn btn-primary justify-center text-sm <?= $viewIsGrid ? 'mr-auto' : 'mr-auto md:mr-0' ?>"
                    title="<?= $escaper->escapeHtmlAttr(__('Configure %1 on the product page', $productName)) ?>"
                    aria-label="<?= $escaper->escapeHtmlAttr(__('Configure %1 on the product page', $productName)) ?>"
                >
                    <?= $heroicons->pencilAltHtml('', 24, 24, ['aria-hidden' => 'true']) ?>
                    <span class="inline <?= $viewIsGrid ? 'md:hidden lg:inline' : '' ?>">
                        <?= $escaper->escapeHtml(__('Configure')) ?>
                    </span>
                </a>
            <?php else: ?>
                <button
                    class="w-auto btn btn-primary justify-center text-sm <?= $viewIsGrid ? 'mr-auto' : 'mr-auto md:mr-0' ?>"
                    title="<?= $escaper->escapeHtmlAttr(__('Add to Cart') . ' ' . $productName) ?>"
                    aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Cart') . ' ' . $productName) ?>"
                    data-addto="cart"
                >
                    <?= $heroicons->shoppingCartHtml('', 24, 24, ['aria-hidden' => 'true']) ?>
                    <span class="inline <?= $viewIsGrid ? 'md:hidden lg:inline' : '' ?>">
                        <?= $escaper->escapeHtml(__('Add to Cart')) ?>
                    </span>
                </button>
            <?php endif; ?>

        <?php else: ?>
            <div class="w-auto justify-center <?= $viewIsGrid ? 'mr-auto' : 'mr-auto md:mr-0' ?>">
                <?= $block->getChildBlock('stockstatus')->setData('product', $product)->toHtml() ?>
            </div>
        <?php endif; ?>
        <div class="flex flex-wrap gap-2">
            <?php if ($showAddToWishlist): ?>
                <?= $block->getChildBlock('wishlist')->setData('product', $product)->toHtml() ?>
            <?php endif; ?>
            <?php if ($showAddToCompare): ?>
                <button x-data="initCompareOnProductList()"
                        x-defer="intersect"
                        @click.prevent="addToCompare(<?= (int)$productId ?>)"
                        aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Compare') . ' ' . $productName) ?>"
                        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; ?>
            <?php if ($addToBlock = $block->getChildBlock('addto')): ?>
                <?= $addToBlock->setProduct($product)->getChildHtml() ?>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php if ($product->isSaleable()): ?>
    </form>
<?php else: ?>
    </div>
<?php endif; ?>
