
<script src="https://www.google.com/recaptcha/api.js?render={$siteKey}"></script>

<script>var siteKey = "{$siteKey}";</script>

{literal}
<script type="module">
    function verifyRecaptcha(form, dataElement) {
        const { sitekey, size } = dataElement.dataset;
        const id = dataElement.id;

        if (!sitekey) return;

        return new Promise((resolve, reject) => {
            grecaptcha.execute(sitekey, {action: 'submit'}).then((token) => {
                if (token) {
                    resolve(token);
                }

                reject('Invalid Captcha');
            })
        });
    }

    const allForm = document.querySelectorAll('form');

    allForm.forEach((form) => {
        const dataElement = form.querySelector('.g-recaptcha');

        if (!dataElement) return;

        form.addEventListener("submit", async (event) => {
            event.preventDefault();
            event.stopPropagation();

            grecaptcha.ready(() =>
                {
                    const response = verifyRecaptcha(form, dataElement)

                    response.then((token) => {
                        const customEvent = new CustomEvent('validRecaptcha', {
                            detail: {
                                token,
                                form,
                            }
                        })

                        form.dispatchEvent(customEvent);
                    })
                    .catch((error) => console.log(error))
                }
            );
        })
    })
</script>
{/literal}