jQuery(document).ready(function ($) {
  const nonce   = swsAjax.nonce;
  const ajaxUrl = ajaxurl;

  /* =============== EXPORT VALIDATION =============== */
  const exportBtn = $("#export_to_square_button");
  if (exportBtn.length) {
    const productId = exportBtn.data("product-id");
    const exportErr = $("<div>", { id: "export-validation-errors", css: { color: "red", "margin-top": "10px" } });
    exportBtn.after(exportErr);

    function validateExport() {
      const exportFields = $(".sws-export-field:checked").map((_, el) => $(el).val()).get();

      exportBtn.prop("disabled", true).text("Checking…");
      $.post(
        ajaxUrl,
        { action: "check_export_validation", nonce, product_id: productId, export_fields: exportFields },
        (res) => {
          console.log(res)
          const isSuccess = res.success === true;
          exportBtn.prop("disabled", !isSuccess).text(isSuccess ? "Export to Square" : "Not Exportable");

          if (!isSuccess && res.data?.reasons?.length) {
            exportErr.html(`<p><strong>Export blocked due to the following issues:</strong></p><ul>${res.data.reasons.map(r => `<li>${r}</li>`).join("")}</ul>`);
          } else if (isSuccess && res.data?.reasons?.length) {
            exportErr.html(`<p><strong>Note:</strong> Some images will be skipped during export:</p><ul>${res.data.reasons.map(r => `<li>${r}</li>`).join("")}</ul>`);
          } else {
            exportErr.empty();
          }
        },
        "json"
      ).fail(() => {
        exportBtn.prop("disabled", true).text("Validation Error");
        exportErr.html('<p><strong>Error:</strong> Failed to validate export conditions.</p>');
      });
    }

    validateExport();
    $(document).on("change", ".sws-export-field", validateExport);
  }

  /* =============== SYNC VALIDATION =============== */
  const syncBtn = $("#sync_to_square_button");
  if (syncBtn.length) {
    const productId = syncBtn.data("product-id");
    const syncWarn  = $("<div>", { id: "sync-validation-errors", css: { color: "red", "margin-top": "10px" } });
    syncBtn.after(syncWarn);

    function validateSync() {
      const syncFields = $(".sws-data-field:checked").map((_, el) => $(el).val()).get();
      syncBtn.prop("disabled", true).text("Checking…");

      $.post(
        ajaxUrl,
        { action: "check_sync_validation", nonce, product_id: productId, sync_fields: syncFields },
        (res) => {
          syncBtn.prop("disabled", false).text("Sync to Square");

          if (res.success && (!res.data?.reasons || res.data.reasons.length === 0)) {
            syncWarn.empty();
          } else {
            const reasons = res.data?.reasons || [];
            const html = `<p><strong>The following data will be skipped during sync:</strong></p><ul>${reasons.map(r => `<li>${r}</li>`).join("")}</ul>`;
            syncWarn.html(html);
          }
        },
        "json"
      ).fail(() => {
        syncBtn.prop("disabled", false).text("Sync to Square");
        $("#post").prepend('<div class="notice notice-error is-dismissible"><p>Sync validation failed unexpectedly.</p></div>');
      });
    }

    validateSync();
    $(document).on("change", ".sws-data-field", validateSync);
  }

  /* =============== EXPORT CLICK =============== */
  $(document).on("click", "#export_to_square_button", function (e) {
    e.preventDefault();
    const productId = $(this).data("product-id");
    const exportFields = $(".sws-export-field:checked").map((_, el) => $(el).val()).get();

    $(this).prop("disabled", true).text("Exporting…");
    $.post(
      ajaxUrl,
      { action: "export_to_square", nonce, product_id: productId, export_fields: exportFields },
      (res) => {
        const cls = res.success ? "notice-success" : "notice-error";
        $("#post").prepend(`<div class="notice ${cls} is-dismissible"><p>${res.data.message}</p></div>`);
        $(this).text(res.success ? "Successfully Exported" : "Failed")
               .prop("disabled", !res.success)
               .toggleClass("success-button", res.success);

        if (res.success) {
          $('#export_to_square_button').prop('disabled', true)
        }
      },
      "json"
    ).fail(() => {
      $("#post").prepend('<div class="notice notice-error is-dismissible"><p>Error occurred while exporting.</p></div>');
      $(this).prop("disabled", true).text("Failed");
    });
  });

  /* =============== SYNC CLICK =============== */
  $(document).on("click", "#sync_to_square_button", function (e) {
    e.preventDefault();
    const productId = $(this).data("product-id");
    const syncFields = $(".sws-data-field:checked").map((_, el) => $(el).val()).get();

    $(this).prop("disabled", true).text("Updating…");
    $.post(
      ajaxUrl,
      { action: "sync_to_square", nonce, product_id: productId, sync_fields: syncFields },
      (res) => {
        const cls = res.success ? "notice-success" : "notice-error";
        $("#post").prepend(`<div class="notice ${cls} is-dismissible"><p>${res.data.message}</p></div>`);
        $(this).text(res.success ? "Successfully Updated" : "Failed")
               .prop("disabled", !res.success)
               .toggleClass("success-button", res.success);
      },
      "json"
    ).fail(() => {
      $("#post").prepend('<div class="notice notice-error is-dismissible"><p>Error occurred while syncing.</p></div>');
      $(this).prop("disabled", true).text("Failed");
    });
  });
});
