/**
 * Guard Dog CAPTCHA Admin Page JavaScript
 * 
 * Handles provider selection and form visibility for CAPTCHA settings.
 *
 * @package GuardDog
 * @since 1.1.0
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        
        const $providerRadios = $('input[name="guard_dog_captcha_provider"]');
        const $providerFields = $('.guard-dog-provider-fields');
        
        // Initialize form state
        function initializeProviderFields() {
            const selectedProvider = $('input[name="guard_dog_captcha_provider"]:checked').val();
            showProviderFields(selectedProvider);
        }

        // Show/hide provider configuration fields
        function showProviderFields(provider) {
            // Hide all provider configuration sections
            $providerFields.removeClass('active');
            
            // Show the selected provider's configuration
            if (provider && provider !== 'none') {
                $(`.guard-dog-provider-fields[data-provider="${provider}"]`).addClass('active');
            }
            
            // Update radio button visual states
            $('.guard-dog-radio-item').removeClass('selected');
            $('input[name="guard_dog_captcha_provider"]:checked').closest('.guard-dog-radio-item').addClass('selected');
        }
        
        // Handle provider selection change
        $providerRadios.on('change', function() {
            const selectedProvider = $(this).val();
            showProviderFields(selectedProvider);
        });

        // Handle clicks on provider cards (not just radio buttons)
        $('.guard-dog-radio-item').on('click', function(e) {
            // Don't handle if they clicked directly on the radio button
            if ($(e.target).is('input[type="radio"]')) {
                return;
            }
            
            // Find the radio button in this card and trigger it
            const $radioButton = $(this).find('input[type="radio"]');
            if ($radioButton.length) {
                $radioButton.prop('checked', true).trigger('change');
            }
        });

        // Initialize secret key field enhancements
        function initializeSecretKeyFields() {
            const $secretKeyInputs = $('input[name*="_secret_key"]');
            
            $secretKeyInputs.each(function() {
                const $input = $(this);
                const hasValue = $input.data('has-value') === 1;
                const originalValue = $input.val();
                
                // Add visual indicator for fields with existing keys
                if (hasValue && originalValue.includes('•')) {
                    $input.addClass('guard-dog-obfuscated-key');
                }
                
                // Handle focus event - clear obfuscated value when user starts editing
                $input.on('focus', function() {
                    if ($(this).val().includes('•')) {
                        $(this).val('').removeClass('guard-dog-obfuscated-key').addClass('guard-dog-editing-key');
                        $(this).attr('placeholder', 'Enter new secret key to update');
                    }
                });
                
                // Handle blur event - restore obfuscated value if field is empty
                $input.on('blur', function() {
                    if ($(this).val() === '' && hasValue) {
                        $(this).val(originalValue).removeClass('guard-dog-editing-key').addClass('guard-dog-obfuscated-key');
                        $(this).attr('placeholder', 'Key configured - enter new key to update');
                    }
                });
                
                // Handle input event - mark as modified
                $input.on('input', function() {
                    if ($(this).val() !== '' && !$(this).val().includes('•')) {
                        $(this).removeClass('guard-dog-obfuscated-key').addClass('guard-dog-new-key');
                    }
                });
            });
        }

        // Handle form submission validation and cleanup
        $('.guard-dog-settings-form').on('submit', function(e) {
            const selectedProvider = $('input[name="guard_dog_captcha_provider"]:checked').val();
            
            // Remove inactive provider fields from form submission
            $('.guard-dog-provider-fields').each(function() {
                const $section = $(this);
                const sectionProvider = $section.data('provider');
                
                // If this section is not for the selected provider, disable its inputs
                if (sectionProvider !== selectedProvider) {
                    $section.find('input, select').each(function() {
                        $(this).prop('disabled', true);
                    });
                }
            });
            
            if (selectedProvider && selectedProvider !== 'none') {
                // Only validate fields that are visible (active provider)
                const $activeProviderSection = $(`.guard-dog-provider-fields[data-provider="${selectedProvider}"].active`);
                
                if ($activeProviderSection.length === 0) {
                    // Provider section not found or not active, skip validation
                    return true;
                }
                
                const $siteKeyField = $activeProviderSection.find(`input[name="guard_dog_${selectedProvider}_site_key"]`);
                const $secretKeyField = $activeProviderSection.find(`input[name="guard_dog_${selectedProvider}_secret_key"]`);
                
                if ($siteKeyField.length === 0 || $secretKeyField.length === 0) {
                    // Fields not found, skip validation
                    return true;
                }
                
                const siteKey = $siteKeyField.val().trim();
                const secretKey = $secretKeyField.val().trim();
                const hasExistingKey = $secretKeyField.data('has-value') == 1;
                
                // Check if site key is empty
                if (!siteKey) {
                    e.preventDefault();
                    alert('Please enter both Site Key and Secret Key for the selected provider.');
                    $siteKeyField.focus();
                    return false;
                }
                
                // Check if secret key is empty (accounting for obfuscated existing keys)
                if (!secretKey || (secretKey === '' && !hasExistingKey)) {
                    e.preventDefault();
                    alert('Please enter both Site Key and Secret Key for the selected provider.');
                    $secretKeyField.focus();
                    return false;
                }
                
                // If secret key looks obfuscated (contains bullet characters), it's OK
                if (secretKey.includes('•') && hasExistingKey) {
                    // This is an existing obfuscated key, allow submission
                    return true;
                }
            }
            
            return true;
        });

        // Initialize the form
        initializeProviderFields();
        initializeSecretKeyFields();
        
    });

})(jQuery);