<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<?php
/** @var $block \Magento\Catalog\Block\Product\Image */
/** @var $escaper \Magento\Framework\Escaper */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
/**
 * Enable lazy loading for images with borders and if variable enable_lazy_loading_for_images_without_borders
 * is enabled in view.xml. Otherwise small size images without borders may be distorted. So max-width is used for them
 * to prevent stretching and lazy loading does not work.
 */
$borders = (bool)$block->getVar('product_image_white_borders', 'Magento_Catalog');
$enableLazyLoadingWithoutBorders = (bool)$block->getVar(
    'enable_lazy_loading_for_images_without_borders',
    'Magento_Catalog'
);
$width = (int)$block->getWidth();
$paddingBottom = $block->getRatio() * 100;
$id_product_fixed = $block->getProductId().rand();
?>
<span class="product-image-container product-image-container-<?= /* @noEscape */ $id_product_fixed ?>">
    <span class="product-image-wrapper">
        <img class="<?= $escaper->escapeHtmlAttr($block->getClass()) ?>"
            src="<?= $escaper->escapeUrl($block->getImageUrl()) ?>"
            loading="lazy"
            <?php if ($borders || $enableLazyLoadingWithoutBorders): ?>
                width="<?= $escaper->escapeHtmlAttr($block->getWidth()) ?>"
                height="<?= $escaper->escapeHtmlAttr($block->getHeight()) ?>"
            <?php else: ?>
                max-width="<?= $escaper->escapeHtmlAttr($block->getWidth()) ?>"
                max-height="<?= $escaper->escapeHtmlAttr($block->getHeight()) ?>"
            <?php endif; ?>
            alt="<?= $escaper->escapeHtmlAttr($block->getLabel()) ?>"/></span>
</span>
<?php
$styles = <<<STYLE
.product-image-container-{$id_product_fixed} {
    width: {$width}px;
}
.product-image-container-{$id_product_fixed} span.product-image-wrapper {
    padding-bottom: {$paddingBottom}%;
}
STYLE;
//In case a script was using "style" attributes of these elements
$script = <<<SCRIPT
prodImageContainers = document.querySelectorAll(".product-image-container-{$id_product_fixed}");
for (var i = 0; i < prodImageContainers.length; i++) {
    prodImageContainers[i].style.width = "{$width}px";
}
prodImageContainersWrappers = document.querySelectorAll(
    ".product-image-container-{$id_product_fixed}  span.product-image-wrapper"
);
for (var i = 0; i < prodImageContainersWrappers.length; i++) {
    prodImageContainersWrappers[i].style.paddingBottom = "{$paddingBottom}%";
}
SCRIPT;

?>
<?= /* @noEscape */ $secureRenderer->renderTag('style', [], $styles, false) ?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', ['type' => 'text/javascript'], $script, false) ?>
