/**
 * CAPTCHA Refresh Handler
 * Handles AJAX refresh of CAPTCHA image without full page reload
 */

document.addEventListener('DOMContentLoaded', function() {
    const refreshBtn = document.getElementById('captcha-refresh-btn');
    const captchaImage = document.getElementById('captcha-image');
    const captchaInput = document.getElementById('captcha');
    const checksumInput = document.getElementById('captcha_checksum');
    const loginForm = document.getElementById('login-form');

    if (!refreshBtn || !captchaImage) return;

    /**
     * Refresh CAPTCHA via AJAX
     */
    function refreshCaptcha() {
        refreshBtn.classList.add('opacity-50', 'cursor-not-allowed');
        refreshBtn.disabled = true;
        
        // Add spinner animation
        const icon = refreshBtn.querySelector('i');
        icon.classList.add('animate-spin');

        const csrfToken = document.querySelector('input[name="_token"]')?.value || 
                         document.querySelector('meta[name="csrf-token"]')?.content;

        fetch('/captcha-refresh', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to refresh CAPTCHA');
            }
            return response.json();
        })
        .then(data => {
            if (data.checksum) {
                // Update hidden checksum input
                checksumInput.value = data.checksum;

                // Update image source with new checksum for cache-busting
                captchaImage.src = `/captcha/${data.checksum}?t=${Date.now()}`;

                // Clear input field
                captchaInput.value = '';
                captchaInput.focus();

                // Clear any previous error messages
                const errorMsg = captchaInput.parentElement.querySelector('p');
                if (errorMsg) {
                    errorMsg.remove();
                }
            }
        })
        .catch(error => {
            console.error('CAPTCHA refresh error:', error);
            // Show user-friendly error
            alert('Gagal refresh CAPTCHA. Silakan coba lagi.');
        })
        .finally(() => {
            // Remove spinner animation
            icon.classList.remove('animate-spin');
            refreshBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            refreshBtn.disabled = false;
        });
    }

    // Attach click handler to button
    refreshBtn.addEventListener('click', function(e) {
        e.preventDefault();
        refreshCaptcha();
    });

    // Also allow clicking image to refresh
    captchaImage.addEventListener('click', function() {
        refreshCaptcha();
    });

    // Form submission validation
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            const captchaValue = captchaInput.value.trim();
            
            if (!captchaValue) {
                e.preventDefault();
                captchaInput.focus();
                captchaInput.classList.add('ring-2', 'ring-red-500');
                return false;
            }

            // Clear ring on submit
            captchaInput.classList.remove('ring-2', 'ring-red-500');
        });
    }

    // Clear error ring when user starts typing
    captchaInput.addEventListener('input', function() {
        this.classList.remove('ring-2', 'ring-red-500');
    });
});
