<?php

declare(strict_types=1);

use Magento\Framework\View\Element\Template;

/** @var $block Template */
$nonceViewmodel = $block->getData('nonceProvider');
?>

<script <?= $nonceViewmodel->renderNonceAttribute() ?> >
    'use strict';
    (function (blackbird) {

        const addEventListenerOnElementToLoad = (elementToLoad, source) => new Promise((resolve, reject) => {
            elementToLoad.addEventListener('load', () => {
                elementToLoad.dataset.loaded = true;
                resolve(elementToLoad);
            })

            elementToLoad.addEventListener('error', () => {
                reject(new Error(`[External resource loader] : The resource "${source}", failed to load.`));
            });
        });

        blackbird.loadExternalScript = async (source) => {
            const scriptWithSameSrc = document.querySelector(`script[src="${source}"][data-loaded]`);

            if (scriptWithSameSrc && scriptWithSameSrc.dataset.loaded === 'true') {
                return scriptWithSameSrc;
            }

            const script = scriptWithSameSrc ?? document.createElement('script');
            script.type = 'text/javascript';
            script.async = true;
            script.src = source;
            script.dataset.loaded = false;

            document.head.appendChild(script);
            await addEventListenerOnElementToLoad(script, source);
            return script;
        }

        blackbird.loadExternalStyle = async (source) => {
            const linkWithSameHref = document.querySelector(`link[href="${source}"][data-loaded]`);

            if (linkWithSameHref && linkWithSameHref.dataset.loaded === 'true') {
                return linkWithSameHref;
            }

            const link = linkWithSameHref ?? document.createElement('link');
            link.type = 'text/css'
            link.rel = 'stylesheet';
            link.href = source;
            link.dataset.loaded = false;

            document.head.prepend(link);
            await addEventListenerOnElementToLoad(link, source);
            return link;
        }

        blackbird.loadExternalResource = (source) => {
            const scriptUrlRegex = /\.(js)$/i;
            const styleUrlRegex = /\.(css)$/i;

            if (scriptUrlRegex.test(source)) {
                return blackbird.loadExternalScript(source);
            }

            if (styleUrlRegex.test(source)) {
                return blackbird.loadExternalStyle(source);
            }
        }

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