<?php
declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\ProductStockItem;
use Magento\Catalog\Block\Product\View;
use Magento\Catalog\Model\Product;
use Magento\Framework\Escaper;

// phpcs:disable Generic.WhiteSpace.ScopeIndent.Incorrect

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

/** @var Product $product */
$product = $block->getProduct();

/** @var ProductStockItem $stockItemViewModel */
$stockItemViewModel = $viewModels->require(ProductStockItem::class);
$maxSalesQty        = $stockItemViewModel->getMaxSaleQty($product);

$maxSalesQtyLength  = ($maxSalesQty ? strlen((string) $maxSalesQty) : 4)
    + (/* add one if decimal for separator */
    (int) $stockItemViewModel->isQtyDecimal($product));

$step = $stockItemViewModel->getQtyIncrements($product)
    ? $stockItemViewModel->getQtyIncrements($product)
    : null;

?>
<?php if ($block->shouldRenderQuantity()): ?>
    <script>
        function initQtyField() {

            function findPathParam(key) {
                // get all path pairs after BASE_URL/front_name/action_path/action
                const baseUrl = (BASE_URL.substr(0, 2) === '//' ? 'http:' : '') + BASE_URL;
                const baseUrlParts = (new URL(baseUrl)).pathname.replace(/\/$/, '').split('/');
                const pathParts = window.location.pathname.split('/').slice(baseUrlParts.length + 3);
                for (let i = 0; i < pathParts.length; i += 2) {
                    if (pathParts[i] === key && pathParts.length > i) {
                        return pathParts[i + 1];
                    }
                }
            }

            return {
                qty: <?= $block->getProductDefaultQty() * 1 ?>,
                itemId: (new URLSearchParams(window.location.search)).get('id') || findPathParam('id'),
                productId: '<?= (int)$product->getId() ?>',
                <?php // populate the qty when editing a product from the cart ?>
                onGetCartData: function onGetCartData(data, $dispatch) {
                    const cart = data && data.data && data.data.cart;
                    if (this.itemId && cart && cart.items) {
                        const cartItem = cart.items.find((item) => {
                            return item.item_id === this.itemId && item.product_id === this.productId;
                        });
                        if (cartItem && cartItem.qty) {
                            this.qty = cartItem.qty;
                            $dispatch('update-qty-' + this.productId, this.qty);
                        }
                    }
                }
            };
        }
    </script>
    <div x-data="initQtyField()"
        class="w-2/12 lg:w-auto">
        <?php if ($product->isSaleable()): ?>
            <div>
                <label for="qty[<?= (int)$product->getId() ?>]"
                    class="sr-only"
                >
                    <?= $escaper->escapeHtml(__('Quantity')) ?>
                </label>
                <input name="qty"
                    @private-content-loaded.window="onGetCartData($event.detail, $dispatch)"
                    id="qty[<?= (int)$product->getId() ?>]"
                    form="product_addtocart_form"
                    <?php if ($stockItemViewModel->isQtyDecimal($product)): ?>
                    type="text"
                    pattern="[0-9](\.[0-9])?{0,<?= /** @noEscape */ $maxSalesQtyLength ?>}'"
                    inputmode="decimal"
                    <?php else: ?>
                    type="number"
                    pattern="[0-9]{0,<?= /** @noEscape */ $maxSalesQtyLength ?>}"
                    inputmode="numeric"
                    min="<?= /** @noEscape */ $stockItemViewModel->getMinSaleQty($product) ?: 1 ?>"
                    <?php if (null !== $maxSalesQty): ?>max="<?= /** @noEscape */ $maxSalesQty ?>"<?php endif; ?>
                    <?php if ($step): ?>step="<?= /** @noEscape */ $step ?>"<?php endif; ?>
                    <?php endif; ?>
                    :value="qty"
                    class="w-full px-2 py-2 text-center form-input invalid:ring-2 invalid:ring-red-500 lg:w-20"
                    x-model.number="qty"
                    @change="$dispatch('update-qty-<?= (int)$product->getId() ?>', qty)"
                />
            </div>
        <?php endif; ?>
    </div>
<?php endif; ?>
