<script>

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);
      const feedback = input.nextElementSibling;

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

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

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

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

    const confirm = translations[action];

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

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

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

    const objData = new FormData(formElement);

    if ($("#image")[0]?.files.length) {
      if (!/(jpg|jpeg|png)$/.test($("#image")[0].files[0].type)) {
        Swal.fire({
          icon: "error",
          title: translations.imageRequired,
          showConfirmButton: false,
          timer: 1500,
        });

        return delete $("#image")[0].files;
      }

      $.each($("#image")[0].files, function (i, file) {
        objData.append("image", file[0]);
      });
    }

    if (nameAr.trim().length && nameEn.trim().length) {
      ajaxUpload($(formElement), objData, "uploadWithImage", confirm);
    }
  }

  $(document).ready(function () {
    // create
    $(document).on("submit", "#howWork", function (e) {
      shared(e, "add", this);
    });
    // edit
    $(document).on("submit", "#editHowWork", function (e) {
      shared(e, "edit", this);
    });
  });
</script>
