@php
    $captchaContext = $context ?? 'contact';
    $captcha = app(\App\Services\CaptchaService::class)->frontendPayload($captchaContext);
@endphp
@if($captcha['show'])
    @error('captcha')
        <p class="text-red-600 text-sm mb-2">{{ $message }}</p>
    @enderror
    @if($captcha['provider'] === 'cloudflare')
        <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
        <div class="cf-turnstile mb-4" data-sitekey="{{ $captcha['site_key'] }}"></div>
    @elseif($captcha['google_type'] === 'v2')
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        <div class="g-recaptcha mb-4" data-sitekey="{{ $captcha['site_key'] }}"></div>
    @else
        <input type="hidden" name="g-recaptcha-response" value="" class="gcms-recaptcha-v3-token" data-site-key="{{ $captcha['site_key'] }}" data-action="{{ $captchaContext }}">
        @once
            @push('scripts')
            <script src="https://www.google.com/recaptcha/api.js?render={{ $captcha['site_key'] }}"></script>
            <script>
            document.addEventListener('submit', function (e) {
                var form = e.target;
                if (!form || form.tagName !== 'FORM') return;
                var tokenInput = form.querySelector('input.gcms-recaptcha-v3-token[name="g-recaptcha-response"]');
                if (!tokenInput) return;
                if (form.dataset.gcmsRecaptchaV3Done === '1') return;
                e.preventDefault();
                e.stopPropagation();
                var siteKey = tokenInput.getAttribute('data-site-key');
                var action = tokenInput.getAttribute('data-action') || 'submit';
                if (typeof grecaptcha === 'undefined') {
                    console.error('reCAPTCHA v3 non chargé');
                    return;
                }
                grecaptcha.ready(function () {
                    grecaptcha.execute(siteKey, { action: action }).then(function (token) {
                        tokenInput.value = token;
                        form.dataset.gcmsRecaptchaV3Done = '1';
                        if (typeof form.requestSubmit === 'function') {
                            form.requestSubmit();
                        } else {
                            form.submit();
                        }
                    });
                });
            }, true);
            </script>
            @endpush
        @endonce
    @endif
@endif
