@php
    $formId = $formId ?? null;
    $action = $action ?? 'submit';
    $recaptchaEnabled = setting('recaptcha.enabled') == 'on' && setting('recaptcha.api_site_key');
@endphp

@if ($recaptchaEnabled)
    @if (!empty($formId))
        <input type="hidden" name="g-recaptcha-response" value="">
        <input type="hidden" name="recaptcha_action" value="{{ $action }}">

        @if ($errors->has('recaptcha'))
            <p class="mt-2 text-sm text-red-600">
                {{ $errors->first('recaptcha') }}
            </p>
        @endif
    @endif

    @push('ch_header')
        @php
            if (!defined('CH_RECAPTCHA_SCRIPT_INCLUDED')) {
                define('CH_RECAPTCHA_SCRIPT_INCLUDED', true);
        @endphp
                <script src="https://www.google.com/recaptcha/api.js?render={{ setting('recaptcha.api_site_key') }}" async defer></script>
        @php
            }
        @endphp
    @endpush

    @push('ch_footer')
        @php
            if (!defined('CH_RECAPTCHA_BINDER_INCLUDED')) {
                define('CH_RECAPTCHA_BINDER_INCLUDED', true);
        @endphp
                <script>
                    window.chRecaptchaExecute = function (action) {
                        return new Promise(function (resolve, reject) {
                            if (typeof grecaptcha === 'undefined' || !grecaptcha.execute) {
                                reject(new Error('reCAPTCHA is unavailable'));
                                return;
                            }

                            grecaptcha.ready(function () {
                                grecaptcha.execute('{{ setting('recaptcha.api_site_key') }}', {action: action}).then(resolve).catch(reject);
                            });
                        });
                    };

                    window.chRecaptchaBind = function (form, action) {
                        var tokenField = form.querySelector('input[name="g-recaptcha-response"]');
                        var actionField = form.querySelector('input[name="recaptcha_action"]');

                        if (!tokenField) {
                            tokenField = document.createElement('input');
                            tokenField.type = 'hidden';
                            tokenField.name = 'g-recaptcha-response';
                            form.appendChild(tokenField);
                        }

                        if (!actionField) {
                            actionField = document.createElement('input');
                            actionField.type = 'hidden';
                            actionField.name = 'recaptcha_action';
                            form.appendChild(actionField);
                        }

                        actionField.value = action;

                        form.addEventListener('submit', function (event) {
                            if (form.dataset.recaptchaBypass === 'true') {
                                form.dataset.recaptchaBypass = 'false';
                                return;
                            }

                            event.preventDefault();

                            window.chRecaptchaExecute(action).then(function (token) {
                                if (tokenField) {
                                    tokenField.value = token;
                                }

                                form.dataset.recaptchaBypass = 'true';
                                form.submit();
                            }).catch(function () {
                                form.dataset.recaptchaBypass = 'true';
                                form.submit();
                            });
                        });
                    };
                </script>
        @php
            }
        @endphp

        @if (!empty($formId))
            <script>
                (function () {
                    var form = document.getElementById('{{ $formId }}');
                    if (!form || form.dataset.recaptchaBound === 'true') {
                        return;
                    }

                    form.dataset.recaptchaBound = 'true';

                    var binder = function () {
                        if (typeof window.chRecaptchaBind === 'function') {
                            window.chRecaptchaBind(form, '{{ $action }}');
                            return true;
                        }

                        return false;
                    };

                    if (!binder()) {
                        document.addEventListener('DOMContentLoaded', function handle() {
                            if (binder()) {
                                document.removeEventListener('DOMContentLoaded', handle);
                            }
                        });
                    }
                })();
            </script>
        @endif
    @endpush
@endif

