<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Lazy Load for Magento 2 (System)
 */

namespace Amasty\LazyLoad\Model\LazyScript;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\View\Helper\SecureHtmlRenderer;

class Vanilla implements LazyScriptInterface
{
    /**
     * @var SecureHtmlRenderer
     */
    private $secureRenderer;

    public function __construct(
        ?SecureHtmlRenderer $secureRenderer = null // TODO move to not optional
    ) {
        $this->secureRenderer = $secureRenderer ?? ObjectManager::getInstance()->get(SecureHtmlRenderer::class);
    }

    public function getName(): string
    {
        return (string)__('Vanilla Lazy Script');
    }

    public function getType(): string
    {
        return 'vanilla';
    }

    public function getCode(): string
    {
        $script = <<<SCRIPT
            window.amlazycallback = function () {
                if (typeof window.amLazyLoadInstance !== "undefined") {
                    window.amLazyLoadInstance.update();
                }
            };
            window.lazyLoadOptions = {
                "data_src": "amsrc",
                "data_srcset": "amsrcset",
                "elements_selector": "img[data-amsrc], img[data-amsrcset]"
            };
            window.addEventListener(
                "LazyLoad::Initialized",
                function (event) {
                    window.amLazyLoadInstance = event.detail.instance;
                },
                false
            );
            function amLazyLoadVanillaLib() {
                const dependencies = ["Amasty_LazyLoad/js/vanilla.lazyload"];
                // Dynamically define the dependencies
                if (!("IntersectionObserver" in window)) {
                    dependencies.unshift("Amasty_LazyLoad/js/intersection-observer");
                }

                require(dependencies, function() {});
            }
            amLazyLoadVanillaLib();
        SCRIPT;

        return $this->secureRenderer->renderTag(
            'script',
            [],
            $script,
            false
        );
    }

    public function getSupportedTags(): array
    {
        return ['img', 'source'];
    }
}
