@props(['location' => 'unknown', 'attributes' => []])

@php
    $captchaService = app(\App\Services\Captcha\CaptchaService::class);

    // Check if CAPTCHA is enabled for this location
    if (!$captchaService->isEnabled($location)) {
        return;
    }

    // Check if IP is whitelisted
    if ($captchaService->isWhitelisted()) {
        return;
    }

    $provider = $captchaService->getProviderName();
    $scriptUrl = $captchaService->getScriptUrl();
    $siteKey = $captchaService->getSiteKey();
@endphp

@if($provider && $scriptUrl)
    {{-- Load CAPTCHA script --}}
    @once
        @if($provider === 'recaptcha_v3')
            <script src="{{ $scriptUrl }}" async defer></script>
        @else
            <script src="{{ $scriptUrl }}" async defer></script>
        @endif
    @endonce

    {{-- Render CAPTCHA widget --}}
    <div class="captcha-container mb-4">
        @if($provider === 'hcaptcha')
            <div class="h-captcha" data-sitekey="{{ $siteKey }}" {!! $attributes !!}></div>

        @elseif($provider === 'recaptcha_v2')
            <div class="g-recaptcha" data-sitekey="{{ $siteKey }}" {!! $attributes !!}></div>

        @elseif($provider === 'recaptcha_v2_invisible')
            <div class="g-recaptcha"
                 data-sitekey="{{ $siteKey }}"
                 data-size="invisible"
                 data-callback="onSubmitCaptcha"
                 {!! $attributes !!}></div>
            <script>
                function onSubmitCaptcha(token) {
                    document.querySelector('form').submit();
                }
            </script>

        @elseif($provider === 'recaptcha_v3')
            <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response-v3">
            <script>
                grecaptcha.ready(function() {
                    document.querySelector('form').addEventListener('submit', function(e) {
                        e.preventDefault();
                        grecaptcha.execute('{{ $siteKey }}', {action: '{{ $location }}'}).then(function(token) {
                            document.getElementById('g-recaptcha-response-v3').value = token;
                            e.target.submit();
                        });
                    });
                });
            </script>

        @elseif($provider === 'turnstile')
            <div class="cf-turnstile" data-sitekey="{{ $siteKey }}" {!! $attributes !!}></div>

        @elseif($provider === 'trustip')
            <div class="trustip-captcha" data-apikey="{{ $siteKey }}" {!! $attributes !!}></div>
        @endif

        @error('captcha')
            <div class="mt-2 text-sm text-red-600 dark:text-red-400">
                {{ $message }}
            </div>
        @enderror
    </div>
@endif
