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

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

$storeConfig = $viewModels->require(StoreConfig::class);
$recaptcha   = $viewModels->require(ReCaptcha::class);
$siteKey     = $storeConfig->getStoreConfig('recaptcha_frontend/type_invisible/public_key');
$position    = $storeConfig->getStoreConfig('recaptcha_frontend/type_invisible/position') ?: 'inline';

if (!$siteKey) {
    // No v2 invisible google API credentials configured
    return;
}

$inputElementId        = $block->getData('input_element_id');
$instanceSuffix        = $recaptcha->calcJsInstanceSuffix($inputElementId ?: $block->getData('form_id') ?: 'x');
$callback              = "googleRecaptchaCallback$instanceSuffix";
$elementIdSuffix       = $instanceSuffix ?: 'x';
$grecaptchaContainerId = "grecaptcha-container-$elementIdSuffix";
$grecaptchaInstanceId  = "grecaptchaInstance$instanceSuffix";

// reCaptcha v2 invisible form element
// Explicitly render the recaptcha, so it doesn't use the first .g-recaptcha on the page */
?>
<div id="<?= $escaper->escapeHtmlAttr($grecaptchaContainerId) ?>" class="g-recaptcha"></div>
<script>
    'use strict';

    (() => {
        const containerId = '<?= $escaper->escapeJs($grecaptchaContainerId) ?>';
        const initRecaptcha = () => {
            grecaptchaV2LoadCallbacks.push(() => {
                window.<?= /** @noEscape */ $grecaptchaInstanceId ?> = window.grecaptcha.render(containerId, {
                    sitekey: '<?= $escaper->escapeJs($siteKey) ?>',
                    callback: '<?= $escaper->escapeJs($callback) ?>',
                    size: 'invisible',
                    badge: '<?= $escaper->escapeJs($position) ?>',
                });
            });
        };

        // Dynamically rendered forms (eg. via Alpine or Magewire) are rendered post DOMContentLoaded event trigger
        if (document.readyState !== 'loading') {
            // Wait for 'nextTick' for alpine/magewire to finish re-rendering markup
            setTimeout(() => {
                initRecaptcha();
                forceLoadRecaptchaScript(document.getElementById(containerId).closest('form'));
            });
        } else {
            document.addEventListener('DOMContentLoaded', initRecaptcha);
        }
    })();
</script>
<?php $hyvaCsp->registerInlineScript() ?>
