<?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 Hyva\Theme\ViewModel\HyvaCsp;
use Hyva\Theme\ViewModel\SpeculationRules;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var Escaper $escaper */
/** @var Template $block */
/** @var ViewModelRegistry $viewModels */
/** @var HyvaCsp $hyvaCsp */

/** @var SpeculationRules $speculationRules */
$speculationRules = $viewModels->require(SpeculationRules::class);

$method = $speculationRules->getMethod();
if ($method === 'disabled') {
    return;
}

$eagerness = $speculationRules->getEagerness();
$extraExcludes = (array)$block->getExcludeList();
$excludeListJson = $speculationRules->getExcludeRules($extraExcludes);

?>
<script type="speculationrules">
{
    "tag": "Hyva Theme",
    "<?= $escaper->escapeHtmlAttr($method) ?>": [{
        "source": "document",
        "where": {
            "and": [
                { "href_matches": "/*" },
                { "not": {
                    "href_matches": <?= /* @noEscape */ json_encode($excludeListJson, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES) ?>
                }},
                { "not": {
                    "selector_matches": [".no-preload", ".do-not-prerender", "[download]", "[rel~=nofollow]", "[target]"]
                }}
            ]
        },
        "eagerness": "<?= $escaper->escapeHtmlAttr($eagerness) ?>"
    }]
}
</script>
<?php $hyvaCsp->registerInlineScript();
