<?php
/**
 * Hyvä Themes compatible template.
 *
 * Renders a single product card for the auto-related-products widget. Used
 * both as the slider item template (via Hyva\Theme\ViewModel\Slider) and,
 * for the grid/popup display layouts, rendered directly per item from
 * auto_related_products_rules.phtml.
 *
 * Rule-derived display flags (whether to show price/review/cart/wishlist/
 * compare) are not passed in through block arguments, since the Slider view
 * model only exposes an "item" data key per product - instead they are set
 * as ad-hoc data directly on each product entity before rendering, see
 * auto_related_products_rules.phtml.
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\LucideIcons;
use Hyva\Theme\ViewModel\ProductListItem;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Block\Product\ReviewRendererInterface;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;
use Magento\Wishlist\Helper\Data as WishlistHelper;

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

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

/** @var \Magento\Catalog\Model\Product $item */
if (!($item = $block->getData('item'))) {
    return;
}

/** @var LucideIcons $lucideIcons */
$lucideIcons = $viewModels->require(LucideIcons::class);

/** @var ListProduct $productListBlock */
$productListBlock = $block->getLayout()->createBlock(ListProduct::class);
$productListItemViewModel = $viewModels->require(ProductListItem::class);
$imageDisplayArea = 'category_page_grid';
$productId = (int) $item->getEntityId();
$productName = $item->getName();
$productType = $item->getTypeId();
$hasRequiredOptions = in_array($productType, ['configurable', 'bundle', 'grouped'], true);
$productUrl = $productListBlock->getProductUrl($item);

$canShowPrice = (bool) $item->getData('sparsh_can_show_price');
$canShowReview = (bool) $item->getData('sparsh_can_show_review');
$canShowCart = (bool) $item->getData('sparsh_can_show_cart');
$showWishlist = (bool) $item->getData('sparsh_show_wishlist');
$showCompare = (bool) $item->getData('sparsh_show_compare');
$popupBlockName = $item->getData('sparsh_popup_block_name');
?>
<div class="group flex h-full flex-col rounded-lg border border-gray-100 p-3 transition hover:shadow-md">
    <a href="<?= $block->escapeUrl($productUrl) ?>" class="product-item-photo mb-2 block overflow-hidden rounded-md">
        <?= $productListBlock->getImage($item, $imageDisplayArea)->toHtml() ?>
    </a>
    <div class="product-item-details flex flex-1 flex-col">
        <?php if ($popupBlockName): ?>
            <p class="mb-1 text-xs text-gray-500"><?= $escaper->escapeHtml($popupBlockName) ?></p>
        <?php endif ?>

        <strong class="product-item-name mb-1 text-sm font-medium leading-snug text-gray-900">
            <a
                class="product-item-link hover:text-gray-600"
                title="<?= $escaper->escapeHtmlAttr($productName) ?>"
                href="<?= $block->escapeUrl($productUrl) ?>"
            >
                <?= $escaper->escapeHtml($productName) ?>
            </a>
        </strong>

        <?php if ($canShowPrice): ?>
            <div class="price-box mb-1 text-sm">
                 <?= /* @noEscape */ $productListItemViewModel->getProductPriceHtml($item) ?>
            </div>
        <?php endif ?>

        <?php if ($canShowReview): ?>
            <div class="mb-1">
                <?= $productListBlock->getReviewsSummaryHtml($item, ReviewRendererInterface::SHORT_VIEW) ?>
            </div>
        <?php endif ?>

        <?php if ($canShowCart || $showWishlist || $showCompare): ?>
            <div class="product-item-actions mt-auto flex flex-col gap-2 pt-2">
                <?php if ($canShowCart): ?>
                    <?php if (!$item->getIsInStock()): ?>
                        <div class="stock unavailable text-xs text-gray-500">
                            <?= $escaper->escapeHtml(__('Out of stock')) ?>
                        </div>
                    <?php elseif ($hasRequiredOptions): ?>
                        <?php /* Products with required options are configured on their own page. */ ?>
                        <a
                            href="<?= $block->escapeUrl($productUrl) ?>"
                            class="btn btn-primary w-full text-sm"
                            aria-label="<?= $escaper->escapeHtmlAttr(__('Configure %1 on the product page', $productName)) ?>"
                        >
                            <?= $lucideIcons->pencilHtml('h-4 w-4', 16, 16, ['aria-hidden' => 'true']) ?>
                            <?= $escaper->escapeHtml(__('Configure')) ?>
                        </a>
                    <?php else: ?>
                        <form
                            method="post"
                            action="<?= $escaper->escapeUrl($productListBlock->getAddToCartUrl($item)) ?>"
                            class="product_addtocart_form"
                            x-data="initSparshAddToCart()"
                            x-on:submit.prevent="addToCart($el)"
                        >
                            <?= /* @noEscape */ $block->getBlockHtml('formkey') ?>
                            <input type="hidden" name="product" value="<?= $productId ?>">
                            <button
                                type="submit"
                                class="btn btn-primary w-full text-sm"
                                x-bind:disabled="loading"
                                aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Cart') . ' ' . $productName) ?>"
                            >
                                <?= $lucideIcons->shoppingCartHtml('h-4 w-4', 16, 16, ['aria-hidden' => 'true']) ?>
                                <span x-show="!loading"><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
                                <span x-show="loading"><?= $escaper->escapeHtml(__('Adding...')) ?></span>
                            </button>
                        </form>
                    <?php endif; ?>
                <?php endif; ?>

                <?php if ($showWishlist || $showCompare): ?>
                    <div class="secondary-addto-links flex items-center gap-3">
                        <?php if ($showWishlist): ?>
                            <button
                                type="button"
                                x-data="initSparshAddToWishlist()"
                                x-on:click="addToWishlist"
                                data-post="<?= $escaper->escapeHtmlAttr(
                                    (string) $this->helper(WishlistHelper::class)->getAddParams($item)
                                ) ?>"
                                class="action towishlist btn p-2 rounded-full"
                                aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Wish List') . ' ' . $productName) ?>"
                            >
                                <?= $lucideIcons->heartHtml('h-4 w-4', 16, 16, ['aria-hidden' => 'true']) ?>
                            </button>
                        <?php endif ?>
                        <?php if ($showCompare): ?>
                            <button
                                type="button"
                                x-data="initCompareOnProductList()"
                                x-on:click.prevent="addToCompare(<?= $productId ?>)"
                                class="action tocompare btn p-2 rounded-full"
                                aria-label="<?= $escaper->escapeHtmlAttr(__('Add to Compare') . ' ' . $productName) ?>"
                            >
                                <?= $lucideIcons->scaleHtml('h-4 w-4', 16, 16, ['aria-hidden' => 'true']) ?>
                            </button>
                        <?php endif ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>
