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

$_product = isset($_product) ? $_product : $block->getData('product');
if (!$_product) {
    return;
}

$labels = method_exists($block, 'getLabels') ? $block->getLabels() : [];
$mediaBaseUrl = method_exists($block, 'getMediaBaseUrl') ? $block->getMediaBaseUrl() : '';
?>
<?php if (!empty($labels)) : ?>
    <div class="agd-labels agd-labels--plp" data-agd-labels="plp">
        <?php foreach ($labels as $label) : ?>
            <?php /** @var \Autogedal\Labels\Model\LabelView $label */ ?>
            <?php
            $cssClass = $label->getCssClass() ?: 'agd-label';
            $imagePath = $label->getImagePath();
            $inlineStyle = $label->getInlineStyle();
            $textStyle = $label->getTextStyle();
            $imageWidth = $label->getImageWidth();
            $imageHeight = $label->getImageHeight();

            $styleAttr = $inlineStyle ? ' style="' . $block->escapeHtmlAttr($inlineStyle) . '"' : '';
            $textStyleAttr = $textStyle ? ' style="' . $block->escapeHtmlAttr($textStyle) . '"' : '';
            $hasManualSizing = ($inlineStyle !== null && trim((string)$inlineStyle) !== '')
                || ($textStyle !== null && trim((string)$textStyle) !== '')
                || ($imageWidth !== null && trim((string)$imageWidth) !== '')
                || ($imageHeight !== null && trim((string)$imageHeight) !== '');
            $manualSizingAttr = $hasManualSizing ? ' data-agd-manual-sizing="1"' : '';
            $imageStyleParts = [];
            $mediaImagePath = method_exists($block, 'normalizeMediaImagePath')
                ? $block->normalizeMediaImagePath($imagePath)
                : (string)$imagePath;
            if ($imageWidth !== null && $imageWidth !== '') {
                $w = trim($imageWidth);
                if (is_numeric($w)) {
                    $w .= 'px';
                }
                $imageStyleParts[] = 'width: ' . $w . ' !important';
            }
            if ($imageHeight !== null && $imageHeight !== '') {
                $h = trim($imageHeight);
                if (is_numeric($h)) {
                    $h .= 'px';
                }
                $imageStyleParts[] = 'height: ' . $h . ' !important';
            }
            $hasText = trim((string)$label->getText()) !== '';
            $imageInlineStyle = [
                'width: 100% !important',
                'height: 100% !important',
                'display: block !important',
                'object-fit: contain !important',
                'max-width: 100% !important',
                'max-height: 100% !important',
            ];
            if ($imageStyleParts) {
                $imageInlineStyle = array_merge($imageInlineStyle, $imageStyleParts);
            }
            $imageStyleAttr = ' style="' . $block->escapeHtmlAttr(implode(';', $imageInlineStyle)) . '"';
            ?>
            <span class="<?= $block->escapeHtmlAttr($cssClass) ?>"<?= $styleAttr ?><?= $manualSizingAttr ?>>
                <?php if ($imagePath) : ?>
                    <span class="agd-label__image-wrap">
                    <img
                        class="agd-label__image"
                        src="<?= $block->escapeUrl($mediaBaseUrl . $mediaImagePath) ?>"<?= $imageStyleAttr ?>
                        alt="<?= $block->escapeHtmlAttr($label->getText() ?: $label->getCode()) ?>"
                    />
                    <?php if ($hasText) : ?>
                        <span class="agd-label__text agd-label__text--overlay"<?= $textStyleAttr ?>><?= $block->escapeHtml($label->getText()) ?></span>
                    <?php endif; ?>
                    </span>
                <?php else : ?>
                    <span class="agd-label__text"<?= $textStyleAttr ?>>
                        <?= $block->escapeHtml($label->getText()) ?>
                    </span>
                <?php endif; ?>
            </span>
        <?php endforeach; ?>
    </div>
    <script>
        require(['jquery'], function ($) {
            var resizeObserver = null;
            var scheduled = false;

            function getPlpAnchorClass($node) {
                var className = ($node && $node.attr('class')) ? $node.attr('class') : '';
                var anchors = [
                    'top-left',
                    'top-center',
                    'top-right',
                    'middle-left',
                    'middle-center',
                    'middle-right',
                    'bottom-left',
                    'bottom-center',
                    'bottom-right'
                ];

                for (var i = 0; i < anchors.length; i++) {
                    if (className.indexOf(anchors[i]) !== -1) {
                        return anchors[i];
                    }
                }

                return 'top-left';
            }

            function getPlpAnchorTransform(anchor) {
                switch (anchor) {
                    case 'top-center':
                        return 'translateX(-50%)';
                    case 'top-right':
                        return '';
                    case 'middle-left':
                        return 'translateY(-50%)';
                    case 'middle-center':
                        return 'translate(-50%, -50%)';
                    case 'middle-right':
                        return 'translateY(-50%)';
                    case 'bottom-left':
                        return '';
                    case 'bottom-center':
                        return 'translateX(-50%)';
                    case 'bottom-right':
                        return '';
                    case 'top-left':
                    default:
                        return '';
                }
            }

            function getPlpAnchorOrigin(anchor) {
                switch (anchor) {
                    case 'top-center':
                        return 'center top';
                    case 'top-right':
                        return 'right top';
                    case 'middle-left':
                        return 'left center';
                    case 'middle-center':
                        return 'center center';
                    case 'middle-right':
                        return 'right center';
                    case 'bottom-left':
                        return 'left bottom';
                    case 'bottom-center':
                        return 'center bottom';
                    case 'bottom-right':
                        return 'right bottom';
                    case 'top-left':
                    default:
                        return 'left top';
                }
            }

            function getPlpLabelBounds(anchor) {
                return { width: 0.44, height: 0.24 };
            }

            function isHomepagePlp($labelBox) {
                return $('body').hasClass('cms-index-index') && (
                    $labelBox.closest('.homepage-products').length ||
                    $labelBox.closest('.content-data.slider-products').length
                );
            }

            function getPlpTargetRect($labelBox) {
                var $productInfo = $labelBox.closest('.product-item-info');
                var $popupPhoto = $labelBox.closest('.amsearch-autocomplete-image');
                var $popupImageContainer = $popupPhoto.find('.amsearch-product-image-container').first();
                var $popupImageWrapper = $popupPhoto.find('.product-image-wrapper').first();
                var $photo = $productInfo.find('.product-item-photo').first();
                var photoNode = $photo.length ? $photo.get(0) : null;
                var popupPhotoNode = $popupPhoto.length ? $popupPhoto.get(0) : null;
                var popupImageContainerNode = $popupImageContainer.length ? $popupImageContainer.get(0) : null;
                var popupImageWrapperNode = $popupImageWrapper.length ? $popupImageWrapper.get(0) : null;
                var photoRect;
                var width;
                var height;
                var maxSide = 185;

                if (!photoNode && popupImageContainerNode) {
                    photoNode = popupImageContainerNode;
                }

                if (!photoNode && popupImageWrapperNode) {
                    photoNode = popupImageWrapperNode;
                }

                if (!photoNode && popupPhotoNode) {
                    photoNode = popupPhotoNode;
                }

                if (!photoNode) {
                    return {
                        width: 0,
                        height: 0,
                        top: 0,
                        left: 0
                    };
                }

                photoRect = photoNode.getBoundingClientRect();
                if (!photoRect || !photoRect.width || !photoRect.height) {
                    if (popupImageContainerNode) {
                        photoRect = popupImageContainerNode.getBoundingClientRect();
                    }
                }

                if (!photoRect || !photoRect.width || !photoRect.height) {
                    if (popupImageWrapperNode) {
                        photoRect = popupImageWrapperNode.getBoundingClientRect();
                    }
                }

                if (!photoRect || !photoRect.width || !photoRect.height) {
                    if (popupPhotoNode) {
                        photoRect = popupPhotoNode.getBoundingClientRect();
                    }
                }

                if (!photoRect || !photoRect.width || !photoRect.height) {
                    return {
                        width: 0,
                        height: 0,
                        top: 0,
                        left: 0
                    };
                }

                width = Math.min(photoRect.width, maxSide);
                height = Math.min(photoRect.height, maxSide);

                return {
                    width: width,
                    height: height,
                    top: 0,
                    left: isHomepagePlp($labelBox) ? 25 : 0
                };
            }

            function getPlpImageMetrics($image) {
                var node = $image && $image.length ? $image.get(0) : null;
                var width = 0;
                var height = 0;

                if (!node) {
                    return { width: 0, height: 0 };
                }

                width = node.naturalWidth || node.width || 0;
                height = node.naturalHeight || node.height || 0;

                if (!width || !height) {
                    width = node.getBoundingClientRect().width || 0;
                    height = node.getBoundingClientRect().height || 0;
                }

                return {
                    width: width,
                    height: height
                };
            }

            function fitPlpLabel($labelBox, photoRect) {
                var $inner = $labelBox.children().first();
                var $image = $inner.find('img.agd-label__image').first();
                var innerNode;
                var anchor;
                var bounds;
                var origin;
                var maxWidth;
                var maxHeight;
                var currentTransform;
                var width;
                var height;
                var scale;
                var $text;
                var textValue;
                var textLength;
                var longestWord;
                var textFontSize;
                var textPadding;

                if (!$inner.length || !photoRect.width || !photoRect.height) {
                    return;
                }

                innerNode = $inner.get(0);
                if (!innerNode) {
                    return;
                }

                anchor = getPlpAnchorClass($labelBox);
                bounds = getPlpLabelBounds(anchor);
                origin = getPlpAnchorOrigin(anchor);
                currentTransform = getPlpAnchorTransform(anchor);

                if ($labelBox.data('agdManualSizing') === 1 || $labelBox.data('agdManualSizing') === '1') {
                    $inner.css({
                        transformOrigin: origin,
                        transform: currentTransform || '',
                        willChange: 'transform'
                    });

                    return;
                }

                if ($image.length) {
                    maxWidth = photoRect.width * bounds.width;
                    maxHeight = photoRect.height * bounds.height;
                    $text = $inner.find('.agd-label__text--overlay').first();

                    $image.each(function () {
                        if (!this || !this.style) {
                            return;
                        }

                        this.style.setProperty('width', '100%', 'important');
                        this.style.setProperty('height', '100%', 'important');
                        this.style.setProperty('display', 'block', 'important');
                        this.style.setProperty('object-fit', 'contain', 'important');
                        this.style.setProperty('max-width', '100%', 'important');
                        this.style.setProperty('max-height', '100%', 'important');
                    });

                    $inner.css({
                        width: Math.round(maxWidth) + 'px',
                        height: Math.round(maxHeight) + 'px'
                    });
                    $inner.css({
                        transformOrigin: origin,
                        transform: currentTransform || '',
                        willChange: 'transform'
                    });

                    if ($text.length) {
                        textValue = $.trim($text.text());
                        textLength = textValue.length || 1;
                        longestWord = textValue.split(/\s+/).reduce(function (max, part) {
                            return Math.max(max, part.length);
                        }, 0) || textLength;
                        textFontSize = Math.floor(Math.min(
                            maxHeight * 0.34,
                            (maxWidth / Math.max(4, textLength)) * 1.9,
                            (maxWidth / Math.max(3, longestWord)) * 2.6
                        ));
                        textFontSize = Math.max(8, Math.min(18, textFontSize));
                        textPadding = Math.max(2, Math.round(maxWidth * 0.04));

                        $text.css({
                            fontSize: textFontSize + 'px',
                            lineHeight: '1.05',
                            paddingLeft: textPadding + 'px',
                            paddingRight: textPadding + 'px',
                            whiteSpace: 'normal',
                            overflowWrap: 'anywhere',
                            wordBreak: 'break-word'
                        });
                    }
                } else {
                    width = innerNode.offsetWidth || innerNode.getBoundingClientRect().width;
                    height = innerNode.offsetHeight || innerNode.getBoundingClientRect().height;

                    if (!width || !height) {
                        return;
                    }

                    scale = Math.min(
                        (photoRect.width * bounds.width) / width,
                        (photoRect.height * bounds.height) / height,
                        1
                    );

                    if (scale < 1) {
                        currentTransform = currentTransform ? (currentTransform + ' scale(' + scale.toFixed(4) + ')') : ('scale(' + scale.toFixed(4) + ')');
                    }

                    $inner.css({
                        transformOrigin: origin,
                        transform: currentTransform || '',
                        willChange: 'transform'
                    });
                }
            }

            function syncPlpLabels() {
                var $labels = $('[data-agd-labels="plp"]');
                if (!$labels.length) {
                    return;
                }

                $labels.each(function () {
                    var $labelBox = $(this);
                    var targetRect = getPlpTargetRect($labelBox);

                    if (!targetRect.width || !targetRect.height) {
                        return;
                    }

                    $labelBox.css({
                        position: 'absolute',
                        top: Math.round(targetRect.top) + 'px',
                        left: Math.round(targetRect.left) + 'px',
                        width: Math.round(targetRect.width) + 'px',
                        height: Math.round(targetRect.height) + 'px'
                    });

                    $labelBox.children('.agd-label, .sticker, span').each(function () {
                        fitPlpLabel($(this), targetRect);
                    });

                    $labelBox.find('img.agd-label__image').each(function () {
                        if (this && !this.complete) {
                            $(this).one('load.agdLabels', scheduleSync);
                        }
                    });
                });

                scheduled = false;
            }

            function scheduleSync() {
                if (scheduled) {
                    return;
                }

                scheduled = true;
                window.requestAnimationFrame(function () {
                    window.requestAnimationFrame(syncPlpLabels);
                });
            }

            $(scheduleSync);
            $(window).on('load resize orientationchange', scheduleSync);
            $(document).on('contentUpdated', scheduleSync);

            $('.owl-carousel').on(
                'initialized.owl.carousel translated.owl.carousel resized.owl.carousel refreshed.owl.carousel loaded.owl.lazy',
                scheduleSync
            );

            if (window.ResizeObserver) {
                resizeObserver = new ResizeObserver(scheduleSync);
                $('.product-item-info').each(function () {
                    resizeObserver.observe(this);
                });
            }
        });
    </script>
<?php endif; ?>
