jQuery(document).ready(function(jQuery) {

    jQuery('.integrazo-wczo-setup-select-change').on('change', function() {
        jQuery("#integrazo-wczo-setup-mapping-area").remove();
        jQuery("#integrazo_wczo_setup_next_button").show();
    });

    jQuery(document).on('change', '#integrazo_wczo_product_event_select', function() {
        var priority = jQuery(this).find(':selected').data('priority') || '';
        var $form = jQuery(this).closest('form');
        var $priorityInput = $form.find('input[name="integrazo_wczo_run_priority"]');
        if (priority) {
            if ($priorityInput.length) {
                $priorityInput.val(priority);
            } else {
                $form.append('<input type="hidden" name="integrazo_wczo_run_priority" value="' + parseInt(priority, 10) + '" />');
            }
        } else {
            $priorityInput.remove();
        }
    });
    

    const container = jQuery('#integrazo-wczo-mapping-container');
    function disableAlreadySelectedCRMFields() {
        const selectedValues = jQuery('.integrazo-wczo-crm-field-select').map(function() {
            return jQuery(this).val();
        }).get().filter(val => val !== '');

        jQuery('.integrazo-wczo-crm-field-select').each(function() {
            const currentVal = jQuery(this).val();
            jQuery(this).find('option').each(function() {
                 const isAlwaysDisabled = jQuery(this).data('premium') === true;

                if (isAlwaysDisabled) {
                    jQuery(this).prop('disabled', true).removeAttr('style');
                    return; // skip rest
                }
                if(jQuery(this).val()!="integrazo_wczo_additional_attachment")
                {
                    if (jQuery(this).val() && jQuery(this).val() !== currentVal && selectedValues.includes(jQuery(this).val())) {
                        jQuery(this).prop('disabled', true).removeAttr('style');
                    } else {
                        jQuery(this).prop('disabled', false).attr('style', 'color: blue;');
                    }
                }
            });
        });
    }

    function applyMandatoryRules(row) {
        const crmSelect = row.find('.integrazo-wczo-crm-field-select');
        const selectedOption = crmSelect.find(':selected');
        const isMandatory = selectedOption && selectedOption.data('mandatory') === 1;

        if (isMandatory) {
            row.addClass('integrazo-wczo-mandatory-row');
            crmSelect.prop('disabled', true);
        }
    }

    function resetMappingRow(row) {
        row.find('.integrazo-wczo-form-field-select').val('');
        row.find('.integrazo-wczo-crm-field-select').val('').prop('disabled', false);
        row.find('.integrazo-wczo-custom-textarea textarea').val('');
        row.find('.integrazo-wczo-custom-textarea').hide();
        row.find('#integrazo-wczo-form-field-wrapper').show();
        row.find('.integrazo-wczo-picklist-combined').hide().find('.integrazo-wczo-picklist-select').html('');

        const crmHelpBox = row.find('.integrazo-wczo-crm-help');
        crmHelpBox.attr('style', 'display: none !important;');
        row.find('.integrazo-wczo-crm-field-select').css('width', '100%');
    }

    container.on('click', '.integrazo-wczo-add-row', function() {
        const template = jQuery('#integrazo-wczo-template-row');
        const newRow = template.clone();
        newRow.removeAttr('id').css('display', 'flex').removeClass('integrazo-wczo-mandatory-row');
        resetMappingRow(newRow);
        jQuery(this).closest('.integrazo-wczo-mapping-row').after(newRow);
        disableAlreadySelectedCRMFields();
    });

    container.on('click', '.integrazo-wczo-remove-field', function() {
        const row = jQuery(this).closest('.integrazo-wczo-mapping-row');
        if (!row.hasClass('integrazo-wczo-mandatory-row')) {
            row.remove();
            disableAlreadySelectedCRMFields();
        }
    });

    container.on('change', '.integrazo-wczo-crm-field-select', function() {
        const row = jQuery(this).closest('.integrazo-wczo-mapping-row');
        const picklistData = jQuery(this).find(':selected').data('picklist');
        const picklistWrapper = row.find('.integrazo-wczo-picklist-combined');
        const picklistDropdown = row.find('.integrazo-wczo-picklist-select');
        const formFieldWrapper = row.find('#integrazo-wczo-form-field-wrapper');
        const textareaBox = row.find('.integrazo-wczo-custom-textarea');
        const crmHelpBox = row.find('.integrazo-wczo-crm-help');
        const crmSelect = row.find('.integrazo-wczo-crm-field-select');

        applyMandatoryRules(row);
        disableAlreadySelectedCRMFields();

        if (picklistData && picklistData.length) {
            picklistDropdown.empty();
            picklistDropdown.append(jQuery('<option>', {
                value: '',
                text: 'Select Option'
            }));
            jQuery.each(picklistData, function(_, opt) {
                picklistDropdown.append(jQuery('<option>', {
                    value: opt.actual_value,
                    text: opt.display_value
                }));
            });

            picklistDropdown.append(jQuery('<option>', {
                disabled: true,
                text: '────────────'
            }));
            picklistDropdown.append(jQuery('<option>', {
                value: '__custom_value__',
                text: 'Use a Custom Value'
            }));
            picklistDropdown.append(jQuery('<option>', {
                value: '__map_form_field__',
                text: 'Map to Form Field'
            }));

            picklistWrapper.show();
             formFieldWrapper.hide();
            textareaBox.hide();
            // crmHelpBox.css('display', 'inline-block !important');
            crmHelpBox.attr('style', 'display: inline-block !important;');

            crmSelect.css('width', '90%');
        } else {
            picklistWrapper.hide();
             formFieldWrapper.show();
            // textareaBox.hide();
            crmHelpBox.attr('style', 'display: none !important;');


            crmSelect.css('width', '100%');
        }
    });

    container.on('change', '.integrazo-wczo-picklist-select', function() {
        const row = jQuery(this).closest('.integrazo-wczo-mapping-row');
        const formFieldWrapper = row.find('#integrazo-wczo-form-field-wrapper');
        const textareaBox = row.find('.integrazo-wczo-custom-textarea');
        const formFieldSelect = formFieldWrapper.find('select'); // Add this to target the inner dropdown

        if (jQuery(this).val() === '__custom_value__') {
            textareaBox.show();
            formFieldWrapper.hide();
        } else if (jQuery(this).val() === '__map_form_field__') {
            formFieldWrapper.show();
            textareaBox.hide();
            formFieldSelect.find('option[value="custom_value"]').remove();
        } else {
            formFieldWrapper.hide();
            textareaBox.hide();
        }
    });

    container.on('change', '.integrazo-wczo-form-field-select', function() {
        const row = jQuery(this).closest('.integrazo-wczo-mapping-row');
        const textareaBox = row.find('.integrazo-wczo-custom-textarea');
        const crmRightColumn = row.find('.integrazo-wczo-field-right');
        const selectedVal = jQuery(this).val();

        // Toggle textarea for custom_value
        textareaBox.toggle(selectedVal === 'custom_value');

        // ✅ Hide CRM dropdown only for non-mandatory rows
        if (!row.hasClass('integrazo-wczo-mandatory-row')) {
            if (selectedVal !== '') {
                // crmRightColumn.hide();
            } else {
                // crmRightColumn.show();
            }
        }
    });


    jQuery(function (jQuery) {

  // Utility: show/clear error
  function setError($el, msg) {
    clearError($el);
    $el.addClass('integrazo-wczo-error').css('border', '2px solid red');
    const $msg = jQuery('<small class="integrazo-wczo-error-msg" style="color:#d00;display:block;margin-top:4px;"></small>').text(msg);
    $el.after($msg);
  }
  function clearError($el) {
    $el.removeClass('integrazo-wczo-error').css('border', '');
    // remove only the message right after this element if it’s our error
    const $next = $el.next('.integrazo-wczo-error-msg');
    if ($next.length) $next.remove();
  }

  // Per-row validation
  function validateRow($row) {
    const $picklistWrap = $row.find('.integrazo-wczo-picklist-combined:visible').first();
    const $picklist     = $row.find('.integrazo-wczo-picklist-select').first();
    const $formWrap     = $row.find('.integrazo-wczo-form-field-wrapper:visible').first();
    const $formSelect   = $row.find('.integrazo-wczo-form-field-select').first();
    const $customWrap   = $row.find('.integrazo-wczo-custom-textarea:visible').first();
    const $customTA     = $customWrap.find('textarea').first();

    // clear any previous errors in this row
    [$picklist, $formSelect, $customTA].forEach(function ($el) { if ($el && $el.length) clearError($el); });

    // CASE A: picklist_combined path (boolean/picklist field with extra options)
    if ($picklistWrap.length) {
      const v = (($picklist.val() || '').trim());

      if (!v) {
        setError($picklist, 'Choose an option');
        return false;
      }
      if (v === '__custom_value__') {
        const txt = (($customTA.val() || '').trim());
        if (!txt) {
          // ensure textarea is visible when custom selected (in case UI toggle missed)
          $customWrap.show();
          setError($customTA, 'Enter a custom value');
          return false;
        }
        return true; // valid custom value
      }
      if (v === '__map_form_field__') {
        // ensure form field wrapper visible (in case)
        $formWrap.show();
        const f = (($formSelect.val() || '').trim());
        if (!f) {
          setError($formSelect, 'Select a form field');
          return false;
        }
        return true; // valid map to form field
      }
      return true; // an actual picklist value chosen (e.g., true/false/…)
    }

    // CASE B: plain form_fields path
    const f = (($formSelect.val() || '').trim());
    if (!f) {
      setError($formSelect, 'Select a source field');
      return false;
    }
    if (f === 'custom_value') {
      const txt = (($customTA.val() || '').trim());
      if (!txt) {
        $customWrap.show();
        setError($customTA, 'Enter a custom value');
        return false;
      }
    }
    return true;
  }

  // Validate on submit
  jQuery('form').on('submit', function (e) {

     var $form = jQuery(this);

    // Check if this form is the mapping form
    var isMappingForm = $form.find('input[name="action"][value="integrazo_wczo_handle_field_mapping_step"]').length > 0;

    if (!isMappingForm) {
      // Not the mapping form → skip validation
      return true;
    }
    let ok = true;
    let $firstBad = null;

    jQuery('.integrazo-wczo-mapping-row.integrazo-wczo-mandatory-row').each(function () {
      const $row = jQuery(this);
      const rowOk = validateRow($row);
      if (!rowOk) {
        ok = false;
        if (!$firstBad) {
          // pick the first field with error in this row to focus/scroll
          const $bad = $row.find('.integrazo-wczo-error').first();
          $firstBad = $bad.length ? $bad : $row;
        }
      }
    });

    if (!ok) {
      e.preventDefault();
      if ($firstBad && $firstBad.length) {
        jQuery('html, body').animate({ scrollTop: $firstBad.offset().top - 60 }, 250);
        $firstBad.focus();
      }
        alert('Please review the fields. Some are not selected.');    }
  });

  // Live-clear error as user fixes inputs
  jQuery(document).on('change input', '.integrazo-wczo-picklist-select, .integrazo-wczo-form-field-select, .integrazo-wczo-custom-textarea textarea', function () {
    clearError(jQuery(this));
  });

});


    jQuery('.integrazo-wczo-mapping-row').each(function() {
        applyMandatoryRules(jQuery(this));
    });

    disableAlreadySelectedCRMFields();

    jQuery('.integrazo-wczo-mandatory-row .integrazo-wczo-crm-field-select').each(function() {
        const val = jQuery(this).val();
        if (val) {
            jQuery(this).find(`option[value="${val}"]`).prop('selected', true);
        }
    });


       // Save Mapping button click
       jQuery('#integrazo-wczo-save-mapping').on('click', function (e) {
        var isValid = true;
        var mappings = [];
    
        jQuery('#integrazo-wczo-mapping-container .integrazo-wczo-mapping-row:visible').each(function () {
            var crmField = jQuery(this).find('.integrazo-wczo-crm-field-select').val();
            var picklistSelect = jQuery(this).find('.integrazo-wczo-picklist-select');
            var formFieldSelect = jQuery(this).find('.integrazo-wczo-form-field-select');
            var customValueTextarea = jQuery(this).find('.integrazo-wczo-custom-textarea textarea');
            var formFieldWrapper = jQuery(this).find('#integrazo-wczo-form-field-wrapper select');
            var picklistVal = picklistSelect.val() || '';
            var customValue = customValueTextarea.val().trim();
    
            if (!crmField) {
                isValid = false;
                 alert('Please review the fields. Some are not selected.');
                e.preventDefault();
                return false;
            }
    
            var mapItem = {
                product_field: crmField
            };
    
            if (picklistSelect.length && picklistSelect.is(':visible')) {
                if (picklistVal === '__custom_value__') {
                    if (!customValue) {
                        isValid = false;
                        alert('Please enter a custom value.');
                        customValueTextarea.focus();
                        e.preventDefault();
                        return false;
                    }
                    mapItem.source = 'option_custom_value';
                    mapItem.value = customValue;
                } else if (picklistVal === '__map_form_field__') {
                    let selectedFormField = formFieldWrapper.val();
                    if (!selectedFormField) {
                        isValid = false;
                        alert('Please review the fields. Some are not selected.');
                        e.preventDefault();
                        return false;
                    }
                    mapItem.source = 'option_map_form_field';
                    mapItem.value = selectedFormField;
                } else {
                    if (!picklistVal) {
                        isValid = false;
                        alert('Please review the fields. Some are not selected.');
                        e.preventDefault();
                        return false;
                    }
                    mapItem.source = 'option_value';
                    mapItem.value = picklistVal;
                }
            } else {
                // Default non-picklist logic
                var formField = formFieldSelect.val();
                if (!formField) {
                    isValid = false;
                    alert('Please review the fields. Some are not selected.');
                    e.preventDefault();
                    return false;
                }
    
                if (formField === 'custom_value') {
                    if (!customValue) {
                        isValid = false;
                        alert('Please enter a custom value.');
                        customValueTextarea.focus();
                        e.preventDefault();
                        return false;
                    }
                    mapItem.source = 'custom_value';
                    mapItem.value = customValue;
                } else {
                    mapItem.source = 'form_field';
                    mapItem.value = formField;
                }
            }
    
            // 💥 ADD THIS: Capture data-type for form field and CRM field
            let selectedFormFieldType = formFieldSelect.find(':selected').data('type') || '';
            let selectedCRMFieldType = jQuery(this).find('.integrazo-wczo-crm-field-select option:selected').data('type') || '';
    
            mapItem.form_data_type = selectedFormFieldType;
            mapItem.product_data_type = selectedCRMFieldType;
    
            mappings.push(mapItem);
        });
    
        if (isValid) {
            
           // ----- Check Record Action
           var selectedRecordAction = jQuery('input[name="integrazo_wczo_record_action"]:checked').val();
           jQuery('input[name="record_action"]').val(selectedRecordAction);
           
        //    if (selectedRecordAction === "add_update") {
        //        var primaryKey = jQuery('#integrazo_wczo_setup_primary_key').val();
        //        if (!primaryKey) {
        //            alert("Please select a Primary Key");
        //            return false; // Stop form submission
        //        }
        //        jQuery('input[name="primary_key"]').val(primaryKey);
        //    }           
            // ----- Check Filter Criteria
            var selectedFilterCriteria = jQuery('input[name="filter_criteria"]:checked').val();
            jQuery('input[name="filter_criteria"]').val(selectedFilterCriteria);

            if (selectedFilterCriteria === "yes") {
                var filterJson = getFilterData();

                if (filterJson.status === true) {
                    // Store JSON string, not object, in hidden input
                    jQuery('input[name="filter_criteria_json"]').val(JSON.stringify(filterJson.data));
                } else {
                    alert(filterJson.message);
                    return false; // stop submission
                }
            }
            //
            var jsonOutput = JSON.stringify(mappings);
            jQuery('input[name="final_json"]').val(jsonOutput);  
            return true;
        }
    });
    
    
});