/*global document, jQuery, alert */
jQuery(document).ready(function () {
    
    var validationSelect = "#griffinforms-inputtextvalidation-selectfield, #griffinforms-inputnumbervalidation-selectfield, #griffinforms-inputemailvalidation-selectfield, #griffinforms-inputpasswordvalidation-selectfield, #griffinforms-inputphonevalidation-selectfield, #griffinforms-inputaddressvalidation-selectfield, #griffinforms-inputurlvalidation-selectfield, #griffinforms-inputdatevalidation-selectfield, #griffinforms-inputcheckboxvalidation-selectfield, #griffinforms-textareavalidation-selectfield, #griffinforms-inputtimevalidation-selectfield, #griffinforms-inputratingvalidation-selectfield, #griffinforms-imageselectionvalidation-selectfield";
    
    showFieldDefaultSuboption();
    showUrlGetValue();
    showValidationOptions();
    showDecimalValueOption();
    showRestrictedDomainsOption();
    
    jQuery("#griffinforms-fielddefaultvalue-selectfield").change(showFieldDefaultSuboption);
    jQuery("#griffinforms-urlget-togglecheckbox").click(showUrlGetValue);
    jQuery(validationSelect).change(showValidationOptions);
    jQuery("#griffinforms-allownumbertype-selectfield").change(showDecimalValueOption);
    jQuery("#griffinforms-restrictdomains-togglecheckbox").click(showRestrictedDomainsOption);
    
    function showFieldDefaultSuboption() {
        jQuery(".griffinforms-field-default-suboption").hide();
        var defaultValType = jQuery("#griffinforms-fielddefaultvalue-selectfield").val();
        jQuery("#griffinforms-field-default-value-" + defaultValType + "-wrap").show(300);
    }
    
    function showUrlGetValue() {
        var isGetOn = jQuery("#griffinforms-urlget-togglecheckbox").is(":checked");
        if(isGetOn == true) {
            jQuery("#griffinforms-getvalue-inputtext-wrap").show(300);
        } else {
            jQuery("#griffinforms-getvalue-inputtext-wrap").hide();
        }
    }
    
    function showValidationOptions() {
        
        var selectionField, ValidationType;
        
        jQuery(".gf-validation-options").hide();
    	
    	validationType = jQuery(validationSelect).val();
        
        if (validationType === "pattern") {
    		jQuery("#gf-pattern-wrap").fadeIn();
    	}
    	
    	if (validationType === "custom-parameters") {
    		jQuery("#gf-custom-parameters-wrap").fadeIn();
    	}

        if (validationType === "min_max_select") {
            jQuery("#gf-custom-parameters-wrap").fadeIn();
        }
    	
    	if (validationType === "db-validate") {
    		jQuery("#gf-db-validate-wrap").fadeIn();
    	}
    	
    	if (validationType === "multiples_of") {
    		jQuery("#gf-multiples-wrap").fadeIn();
    	}

    	if (validationType === "min_rating") {
    		jQuery("#gf-min-rating-wrap").fadeIn();
    	}
    }
    
    function showDecimalValueOption() {
        
        var allowDecimalValue = jQuery("#griffinforms-allownumbertype-selectfield").val();
        
        if (allowDecimalValue === "any_number") {
            jQuery("#gf-allow-decimal-value-wrap").fadeIn();
        } else {
            jQuery("#gf-allow-decimal-value-wrap").fadeOut();
        }
    }
    
    function showRestrictedDomainsOption() {
        if (jQuery("#griffinforms-restrictdomains-togglecheckbox").is(":checked")) {
            jQuery("#griffinforms-field-restricted-domain-names-wrap").fadeIn();
        } else {
            jQuery("#griffinforms-field-restricted-domain-names-wrap").hide();
        }
    }

    changeDateFormat();
    jQuery("#griffinforms-fieldsettingsdateformat-selectfield").change(changeDateFormat);

    function changeDateFormat() {
        let dateFormat = jQuery("#griffinforms-fieldsettingsdateformat-selectfield").val();
        jQuery(".griffinforms-inputdate").datepicker("option", "dateFormat", dateFormat);
    }

    // Image aspect ratio UI toggling
    showAspectOptions();
    jQuery("#gf-img-aspect-mode").change(showAspectOptions);

    function showAspectOptions() {
        var mode = jQuery("#gf-img-aspect-mode").val();
        var presetBlock = jQuery("#gf-img-aspect-preset").closest(".mb-2");
        var customRow   = jQuery("#gf-img-aspect-custom-w").closest(".row");

        // Guard against missing fields on non-file-upload screens
        if (!jQuery("#gf-img-aspect-mode").length) { return; }

        if (mode === "preset") {
            if (presetBlock.length) { presetBlock.fadeIn(); }
            if (customRow.length)   { customRow.hide(); }
        } else if (mode === "custom") {
            if (presetBlock.length) { presetBlock.hide(); }
            if (customRow.length)   { customRow.fadeIn(); }
        } else { // free
            if (presetBlock.length) { presetBlock.hide(); }
            if (customRow.length)   { customRow.hide(); }
        }
    }

    // Toggle Image Constraints box when at least one image MIME is selected
    function toggleImageConstraints() {
        var wrap = jQuery('#gf-image-constraints-wrap');
        if (!wrap.length) { return; }

        // Detect selection from the rendered "Images" MIME group container
        var imageGroup = jQuery('.gf-mime-container[data-gf-mime-group="image"]');
        if (!imageGroup.length) { wrap.hide(); return; }

        var hasImage = imageGroup.find('input[name="allowed_mimes[]"]:checked').length > 0;
        if (hasImage) { wrap.fadeIn(); } else { wrap.hide(); }
    }
    // Initial state and change handler
    toggleImageConstraints();
    jQuery(document).on('change', "input[name='allowed_mimes[]']", toggleImageConstraints);

    // Quick Select: control container visibility and bulk-select checkboxes
    function applyMimeQuickSelect() {
        var selectEl = jQuery('#gf-mime-quick-select');
        if (!selectEl.length) { return; }

        var val = (selectEl.val() || '').toLowerCase();
        var containers = jQuery('.gf-mime-container');
        var allBoxes = jQuery('input[name="allowed_mimes[]"]');

        // Default: hide all containers
        containers.hide();

        if (val === 'manually_select') {
            // Show all containers and UNCHECK all
            //allBoxes.prop('checked', false).trigger('change');
            containers.fadeIn();
            toggleImageConstraints();
            return;
        }

        if (val === 'all') {
            // Check ALL extensions (keep containers hidden)
            allBoxes.prop('checked', true).trigger('change');
            toggleImageConstraints();
            return;
        }

        // Map dropdown values to group keys used in data-gf-mime-group
        var map = {
            'images': 'image',
            'documents': 'document',
            'spreadsheets': 'spreadsheet',
            'presentations': 'presentation',
            'pdf': 'pdf',
            'audio': 'audio',
            'video': 'video',
            'archives': 'archive',
            'code': 'code',
            'text': 'text'
        };

        // Specific category selected: UNCHECK all, then check only that group's boxes
        var groupKey = map[val];
        if (groupKey) {
            allBoxes.prop('checked', false);
            // Show only the selected group's container; keep others hidden
            containers.hide();
            var group = jQuery('.gf-mime-container[data-gf-mime-group="' + groupKey + '"]');
            if (group.length) {
                group.find('input[name="allowed_mimes[]"]').prop('checked', true);
                group.fadeIn();
            }
            // Trigger single change after bulk ops
            allBoxes.first().trigger('change');
        }

        // Sync constraints visibility
        toggleImageConstraints();
    }

    // Initialize and bind
    applyMimeQuickSelect();
    jQuery(document).on('change', '#gf-mime-quick-select', applyMimeQuickSelect);

    togglePasswordConfirmation();
    jQuery(document).on('change', '#griffinforms-requireconfirmation-togglecheckbox', togglePasswordConfirmation);

    togglePasswordEncryption();
    jQuery(document).on('change', '#griffinforms-encryptpasswords-togglecheckbox', togglePasswordEncryption);

    syncPasswordRequirementMessages();
    jQuery(document).on('change', '#griffinforms-password-requiredsets input[type="checkbox"]', syncPasswordRequirementMessages);

    jQuery(document).on('click', '#griffinforms-generate-encryption-key', function() {
        var keyInput = jQuery('#griffinforms-encryptionkey-inputtext');
        if (!window.crypto || !window.crypto.getRandomValues) {
            alert('Secure random generation is not supported in this browser.');
            return;
        }
        var bytes = new Uint8Array(32);
        window.crypto.getRandomValues(bytes);
        var binary = Array.from(bytes, function(byte) { return String.fromCharCode(byte); }).join("");
        var key = btoa(binary).replace(/=+$/, "");
        keyInput.val(key);
    });

    function togglePasswordConfirmation() {
        var wrap = jQuery("#griffinforms-confirmation-settings");
        if (!wrap.length) {
            return;
        }
        var isEnabled = jQuery("#griffinforms-requireconfirmation-togglecheckbox").is(":checked");
        wrap.toggle(isEnabled);
    }

    function togglePasswordEncryption() {
        var wrap = jQuery("#griffinforms-encryption-settings");
        if (!wrap.length) {
            return;
        }
        var isEnabled = jQuery("#griffinforms-encryptpasswords-togglecheckbox").is(":checked");
        wrap.toggle(isEnabled);
    }

    function syncPasswordRequirementMessages() {
        var map = {
            "uppercase": "#griffinforms-require_uppercase-message-inputtext",
            "lowercase": "#griffinforms-require_lowercase-message-inputtext",
            "numbers": "#griffinforms-require_number-message-inputtext",
            "symbols": "#griffinforms-require_symbol-message-inputtext"
        };

        jQuery.each(map, function(key, selector) {
            var checkbox = jQuery('#griffinforms-password-requiredsets input[value="' + key + '"]');
            var input = jQuery(selector);
            if (!input.length) {
                return;
            }
            if (checkbox.is(":checked")) {
                input.prop("disabled", false);
            } else {
                input.prop("disabled", true);
            }
        });
    }
});
