<script src="/admin/app-assets/js/core/libraries/jquery.min.js"></script>
<script src="/admin/app-assets/vendors/js/forms/select/select2.full.min.js"></script>
<script src="/admin/app-assets/js/scripts/forms/select/form-select2.js"></script>
<script>

  const translations = {
    add: "<%= i18n.__('common.add') %>",
    edit: "<%= i18n.__('common.edit') %>",
  };


	function validateInput(input) {
    const i18n = {
        common: {
            emptyField: "<%= i18n.__('common.emptyField') %>",
            minLength: "<%= i18n.__('common.minLength', { minLength: '{{minLength}}' }) %>"
        }
    };

    try {
        const trimmedValue = input.value.trim();
        const minLength = 2;
        const emptyMessage = i18n.common.emptyField;
        const minLengthMessage = i18n.common.minLength.replace('{{minLength}}', minLength);

        if (trimmedValue === '') {
            input.classList.add('is-invalid');
            input.style.border = '1px solid red';
            input.setCustomValidity(emptyMessage);
        } else if (trimmedValue.length < minLength) {
            input.classList.add('is-invalid');
            input.style.border = '1px solid red';
            input.setCustomValidity(minLengthMessage);
        } else {
            input.classList.remove('is-invalid');
            input.style.border = '';
            input.setCustomValidity('');
        }

        input.reportValidity();
    } catch (error) {
        console.error("Validation error:", error);
    }
}


  function shared(e, action, formElement) {
    e.preventDefault();

    const confirm = translations[action];

    const nameAr = String($('textarea[name="name[ar]"]').val());

    const nameEn = String($('textarea[name="name[en]"]').val());

    const answerAr = String($('textarea[name="answer[ar]"]').val());

    const answerEn = String($('textarea[name="answer[en]"]').val());

    if (
      !nameAr.trim().length ||
      !nameEn.trim().length ||
      !answerAr.trim().length ||
      !answerEn.trim().length
    ) {
      $(formElement).removeClass("was-validated");
    } else {
      $(formElement).addClass("was-validated");
    }

    if (
      nameAr.trim().length &&
      nameEn.trim().length &&
      answerAr.trim().length &&
      answerEn.trim().length
    ) {
      ajaxUpload($(formElement), {}, "uploadWithoutImage", confirm);
    }
  }

  $(document).ready(function () {
    $(document).on("submit", "#addSupport", function (e) {
      shared(e, "add", this);
    });

    $(document).on("submit", "#editSupport", function (e) {
      shared(e, "edit", this);
    });
  });
</script>