<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes. All rights reserved.
 * See COPYING.txt for license details.
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Magento\Checkout\Block\Cart\ValidationMessages;
use Magento\Framework\Escaper;

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

if (!$block->getMessageCollection()->getCount()) {
    return;
}

$messages = [];
foreach ($block->getMessageTypes() as $type) {
    foreach ($block->getMessagesByType($type) as $message) {
        $messages[] = ['type' => $type, 'text' => $message->getText()];
    }
}
?>
<script>
    <?php
    /**
     * The `hyva` JS namespace is being set by Hyva_Theme/src/view/frontend/templates/page/js/hyva.phtml
     * and should be included through Hyva_Theme/src/view/frontend/layout/default_hyva.xml
     */
    ?>
    if (typeof hyva === 'undefined' || (!hyva.getBrowserStorage || !hyva.getCookie || !hyva.setCookie)) {
        console.warn("Hyvä helpers are not loaded yet. Make sure they are included before this script");
    }

    (function (hyva, undefined) {
        hyva.initCartMessages = () => {
            <?php
            /**
             * Wrap window.dispatchMessages() to avoid duplicate error messages.
             * Duplicate messages are permitted to be displayed again after 10 seconds.
             *
             * Out of stock error messages are triggered when the cart page loads initially and
             * are then triggered again when the GraphQL cart query is processed.
             * This leads to duplicate error messages.
             */
            ?>
            if (window.dispatchMessages && !window.dispatchMessages._checkoutproxy) {
                window.dispatchedMessages = [];
                const origDispatchMessages = window.dispatchMessages;
                window.dispatchMessages = function (messages, hideAfter) {
                    if (messages.length === 0) {
                        return;
                    }

                    const oldMessages = window.dispatchedMessages.filter(message => {
                        return message.ttl > Date.now()
                    });

                    const newMessages = messages.filter(newMessage => {
                        const isInOldMessages = oldMessages.find(oldMessage => {
                            return newMessage.type === oldMessage.type && newMessage.text === oldMessage.text
                        });
                        return !isInOldMessages;
                    });

                    <?php /* Use requestAnimationFrame to give the message component time to reinitialize after replaceDomElement */ ?>
                    requestAnimationFrame(() => origDispatchMessages(newMessages, hideAfter));

                    window.dispatchedMessages = oldMessages.concat(newMessages.map(message => {
                        return Object.assign(message, {ttl: Date.now() + 5000}) // expire after 5 seconds
                    }));

                }
                window.dispatchMessages._checkoutproxy = true;
            }

            try {
                const messages = <?= /** @noEscape */ json_encode($messages) ?>;
                window.dispatchMessages && window.dispatchMessages(messages);
            } catch (error) {
                console.warn('Error parsing Messages:', error);
            }
        }

        window.addEventListener('load', () => hyva.initCartMessages());
        window.addEventListener('reload-customer-section-data', () => hyva.initCartMessages());

    }(window.hyva = window.hyva || {}));
</script>
