jQuery(document).ready(function () {
  /**
   * Handle access code submission and verify integration via AJAX.
   *
   * - Shows loading indicator
   * - Sends access code and nonce to server
   * - Displays success or error message based on response
   * - Redirects on successful authorization
   */

  jQuery(document).on("click", "#gshfjf-save-code", function () {
    var $this = jQuery(this);
    jQuery(".loading-sign").addClass("loading");
    $this.prop("disabled", true).addClass("common-disable");

    var data = {
      action: "gshfjf_verify_integration",
      code: jQuery("#gshfjf-code").val(),
      security: jQuery("#gshfjf-ajax-nonce").val(),
    };
    jQuery.post(ajaxurl, data, function (response) {
      if (!response.success) {
        jQuery(".loading-sign").removeClass("loading");
        jQuery("#gsc-validation-message").empty();
        jQuery(
          "<span class='gsc-msg gsc-error fw-400 text-dark text-center pt-10 pb-10 manual-margin'>Access code Can't be blank</span>",
        ).appendTo("#gsc-validation-message");
      } else {
        jQuery(".loading-sign").removeClass("loading");
        jQuery("#gsc-validation-message").empty();
        jQuery(
          "<div class='gsc-msg gsc-success fw-400 text-dark text-center pt-10 pb-10 manual-margin'>Your Google Access Code is Authorized and Saved.</div>",
        ).appendTo("#gsc-validation-message");
        setTimeout(function () {
          window.location.href = jQuery("#redirect_auth_jettform").val();
        }, 1000);
      }
    });
  });

  /**
   * Save JetForm feed via AJAX on submit button click.
   *
   * - Validates input fields
   * - Sends feed name and form ID to server
   * - Displays success or error messages
   * - Optionally reloads page after successful creation
   */

  jQuery(document).on("input", "#feed_name", function () {
    jQuery(this).next(".input-msg").addClass("d-none");
  });

  jQuery(document).on("change", "#gsc-jetform_form_select", function () {
    jQuery(this).next(".input-msg").addClass("d-none");
  });

  jQuery(document).on("click", ".gshfjf-jetform-sub-btn", function (e) {
    e.preventDefault();

    var feed_name = jQuery(".feedName").val().trim();
    var form_id = jQuery(".gsc-jetforms").val();

    // Hide old messages
    jQuery(".feed-success-message").hide().html("");
    jQuery(".feed-error-message").hide().html("");

    if (feed_name !== "" && form_id !== "") {
      // Show loader
      jQuery(".gshfjf-fetch-load").addClass("loading");

      jQuery.post(
        ajaxurl,
        {
          action: "gshfjf_save_feed",
          security: jQuery("#gshfjf-ajax-nonce").val(),
          feed_name: feed_name,
          form_id: form_id,
        },
        function (response) {
          // Hide loader
          jQuery(".gshfjf-fetch-load").removeClass("loading");

          if (response.success) {
            //   SUCCESS MESSAGE SHOW
            jQuery(".feed-success-message").html(response.data).fadeIn(200);

            // Reset fields
            jQuery(".feedName").val("");
            jQuery(".gsc-jetforms").val("");

            // Optional reload
            setTimeout(function () {
              location.reload();
            }, 1000);
          } else {
            // ❌ ERROR MESSAGE SHOW
            jQuery(".feed-error-message").html(response.data).fadeIn(200);

            setTimeout(function () {
              jQuery(".feed-error-message").fadeOut(300);
            }, 2000);
          }
        },
        "json",
      );
    } else {
      jQuery(".feed-error-message")
        .html("Please enter Feed Name and select Form.")
        .fadeIn(200);
    }
  });
});

/**
 * Delete a JetForm feed via AJAX on delete button click.
 *
 * - Asks for confirmation before deletion
 * - Sends feed ID to server
 * - Shows success message and reloads page on success
 */

jQuery(document).ready(function ($) {
  let deleteFeedId = null;

  // Open popup
  $(document).on("click", ".delete-feed", function (e) {
    e.preventDefault();

    deleteFeedId = $(this).data("feed-id");
    $("#gshfjf-confirm-delete-popup-free").removeClass("d-none");
  });

  // Cancel delete
  $("#gshfjf-delete-popup-cancel-free").on("click", function () {
    deleteFeedId = null;
    $("#gshfjf-confirm-delete-popup-free").addClass("d-none");
  });

  // Confirm delete
  $("#gshfjf-delete-popup-confirm-free").on("click", function () {
    if (!deleteFeedId) return;

    $.post(
      ajaxurl,
      {
        action: "gshfjf_delete_feed",
        feed_id: deleteFeedId,
        security: $("#gshfjf-ajax-nonce").val(),
      },
      function (response) {
        if (response.success) {
          // Remove row from table
          $("#feed-" + deleteFeedId).fadeOut(200, function () {
            $(this).remove();
          });
        }

        $("#gshfjf-confirm-delete-popup-free").addClass("d-none");
        deleteFeedId = null;
      },
    );
  });
});

/**
 * Toggle visibility of the add-feed form and buttons on click.
 *
 * @since 1.0.0
 */

jQuery(document).ready(function ($) {
  // Ensure $ alias is used within this function scope

  // Hide the close-feed button initially
  $("#close-feed").hide();
  $(".gsc-jet-feed").hide();

  // Show the add-feed form and toggle buttons
  $(document).on("click", "#add-new-feed", function () {
    $(".gsc-jet-feed").show();
    $("#add-new-feed").hide();
    $("#close-feed").show();
  });

  // Hide the add-feed form and toggle buttons
  $(document).on("click", "#close-feed", function (event) {
    event.preventDefault(); // Prevent default link behavior
    $("#add-new-feed").show();
    $("#close-feed").hide();
    $(".gsc-jet-feed").hide();
  });

  /**
   * Display Error logs
   */

  jQuery(document).on("click", ".closejetformgscView", function () {
    jQuery("button.closejetformgscView").addClass("gshfjf-logs");
    jQuery(".gshfjf-logs").text("View").removeClass("closejetformgscView");
    jQuery(".gshfjf-system-error-logs").toggle(); // Close the div
  });

  jQuery(document).on("click", ".gshfjf-logs", function () {
    jQuery(".gshfjf-logs").text("Close").addClass("closejetformgscView");
    jQuery("button.gshfjf-logs").removeClass("gshfjf-logs");
    jQuery(".gshfjf-system-error-logs").toggle(); // Open the div
  });
});

jQuery(document).ready(function ($) {
  $(".gshfjf-jetform-sub-btn").on("click", function () {
    let isValid = true;

    // Feed name validation
    let feedName = $("#feed_name").val().trim();
    if (feedName === "") {
      $("#feed_name").next(".input-msg").removeClass("d-none");
      isValid = false;
    } else {
      $("#feed_name").next(".input-msg").addClass("d-none");
    }

    // Form select validation
    let selectedForm = $("#gsc-jetform_form_select").val();
    if (selectedForm === "") {
      $("#gsc-jetform_form_select").next(".input-msg").removeClass("d-none");
      isValid = false;
    } else {
      $("#gsc-jetform_form_select").next(".input-msg").addClass("d-none");
    }

    // Stop submit if invalid
    if (!isValid) {
      return false;
    }
  });
});

jQuery(document).ready(function ($) {
  $(document).on("change", ".check-toggle", function () {
    const feedId = this.id.replace("gshfjf_jetform_status_", "");
    const isChecked = this.checked;

    const $row = $("#feed-" + feedId);

    // 🔥 Correct class toggle
    if (isChecked) {
      $row.removeClass("gshfjfrow-disabled");
    } else {
      $row.addClass("gshfjfrow-disabled");
    }

    // AJAX Save
    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "gshfjf_toggle_feed_status",
        feed_id: feedId,
        status: isChecked ? 1 : 0,
        security: $("#gshfjf-ajax-nonce").val(),
      },
    });
  });
});

jQuery(document).ready(function ($) {
  const $saveBtn = $("#gshfjf-execute-save");

  const $inputs = [
    $('input[name="gshf-jf[sheet-name-custom]"]'),
    $('input[name="gshf-jf[sheet-id-custom]"]'),
    $('input[name="gshf-jf[sheet-tab-name-custom]"]'),
    $('input[name="gshf-jf[tab-id-custom]"]'),
  ];

  function toggleSaveButton() {
    let allFilled = true;

    $inputs.forEach(function ($input) {
      //   Skip if input does not exist
      if (!$input.length) {
        return;
      }

      const value = $input.val();

      if (!value || value.trim() === "") {
        allFilled = false;
      }
    });

    $saveBtn.prop("disabled", !allFilled);
  }

  // Initial check
  toggleSaveButton();

  // Attach listeners safely
  $inputs.forEach(function ($input) {
    if ($input.length) {
      $input.on("keyup change paste", toggleSaveButton);
    }
  });
});
jQuery(document).ready(function ($) {
  $("#gshfjf_jetform_auth_method").on("change", function () {
    const value = $(this).val();

    if (value === "1") {
      $("#gshfjf-confirm-manual-popup-pro").removeClass("d-none");
    }
  });

  // Close popup (Cancel button)
  $(document).on("click", ".gshfjf-popup-close-pro", function () {
    $("#gshfjf-confirm-manual-popup-pro").addClass("d-none");
    $("#gshfjf_jetform_auth_method").val("0");
  });

  // Close popup on overlay click
  $(document).on("click", "#gshfjf-confirm-manual-popup-pro", function (e) {
    if ($(e.target).is(this)) {
      $(this).addClass("d-none");
      $("#gshfjf_jetform_auth_method").val("0");
    }
  });
});
jQuery(document).ready(function ($) {
  $("#gshfjf_jetform_auth_method").on("change", function () {
    const value = $(this).val();

    if (value === "2") {
      $("#gshfjf-confirm-service-popup-pro").removeClass("d-none");
    }
  });

  // Close popup (Cancel button)
  $(document).on("click", ".gshfjf-popup-service-close-pro", function () {
    $("#gshfjf-confirm-service-popup-pro").addClass("d-none");
    $("#gshfjf_jetform_auth_method").val("0");
  });

  // Close popup on overlay click
  $(document).on("click", "#gshfjf-confirm-service-popup-pro", function (e) {
    if ($(e.target).is(this)) {
      $(this).addClass("d-none");
      $("#gshfjf_jetform_auth_method").val("0");
    }
  });
});
jQuery(document).ready(function ($) {
  // Open popup instead of alert
  $(document).on("click", "#gshfjf-deactivate-log", function (e) {
    e.preventDefault();
    $("#gshfjf-confirm-deactive-popup-free").removeClass("d-none");
  });

  // Cancel button
  $(document).on("click", "#gshfjf-deactive-popup-free-cancel", function () {
    $("#gshfjf-confirm-deactive-popup-free").addClass("d-none");
  });

  // Click outside popup to close
  $(document).on("click", "#gshfjf-confirm-deactive-popup-free", function (e) {
    if ($(e.target).is(this)) {
      $(this).addClass("d-none");
    }
  });

  // Confirm Deactivate
  $(document).on("click", "#gshfjf-deactive-popup-free-confirm", function () {
    $("#gshfjf-confirm-deactive-popup-free").addClass("d-none");
    $(".loading-sign-deactive").addClass("loading");

    var data = {
      action: "gshfjf_deactivate_integration",
      security: $("#gshfjf-ajax-nonce").val(),
    };

    $.post(ajaxurl, data, function (response) {
      $(".loading-sign-deactive").removeClass("loading");
      $("#gsc-validation-deactivate-message").empty();

      if (response === -1) {
        return false; // Invalid nonce
      }

      if (!response.success) {
        return;
      }

      $(
        "<div class='gsc-msg gsc-success fw-400 text-dark text-center pt-10 pb-10 manual-margin'>Your account is removed. Reauthenticate again to integrate Jet Form with Google Sheet.</div>",
      ).appendTo("#gsc-validation-deactivate-message");

      setTimeout(function () {
        location.reload();
      }, 1000);
    });
  });
});
jQuery(document).ready(function ($) {
  const noticeKey = "gshfjf_notice_hidden_until";
  const oneDay = 24 * 60 * 60 * 1000;
  //  const oneDay = 2 * 60 * 1000;

  // ❌ Close click ONLY
  $("#pro-dismiss-header-notice").on("click", function () {
    const now = new Date().getTime();

    // Hide notice
    $("#pro-notice-bar").slideUp(200);

    // Save hide time for 1 day
    localStorage.setItem(noticeKey, now + oneDay);
  });

  // ⏳ On page load: check if 1 day passed
  const hideUntil = localStorage.getItem(noticeKey);
  const now = new Date().getTime();

  if (hideUntil && now < hideUntil) {
    $("#pro-notice-bar").hide();
  }

  function gshfjfHandleResetResponse(response) {
    var $success = jQuery(".feed-success-message");
    var $error = jQuery(".feed-error-message");

    // Hide both first
    $success.addClass("d-none").text("");
    $error.addClass("d-none").text("");

    if (!response || !response.success) {
      $error.removeClass("d-none").text("Reset failed");

      return;
    }

    $success.removeClass("d-none").text("Feed reset successfully");

    setTimeout(function () {
      location.reload();
    }, 2000);
  }
  jQuery(document).on("click", "#execute-reset-free", function (e) {
    e.preventDefault();

    var $loader = jQuery(".loading-sign-reset");
    var $success = jQuery(".gsc-success");
    var $error = jQuery(".gsc-error");

    // Hide old messages
    $success.addClass("d-none");
    $error.addClass("d-none");

    // 👉 Add loading class
    $loader.addClass("loading");

    let data = {
      action: "gshfjf_reset_feed",
      security: jQuery("#gshfjf-ajax-nonce").val(),
      feed_id: jQuery("#feed-id").val(),
      form_id: jQuery("#form-id").val(),
    };

    jQuery.post(ajaxurl, data, function (response) {
      gshfjfHandleResetResponse(response);
    });
  });
});

document.addEventListener("DOMContentLoaded", function () {
  var el = document.querySelector(".gshfjf-selected-method");

  if (el && el.dataset.value && el.dataset.value.trim() !== "") {
    var badgeText = el.dataset.value.trim();

    document
      .querySelectorAll(".nav-tab-wrapper .nav-tab")
      .forEach(function (tab) {
        var href = tab.getAttribute("href") || "";

        if (href.indexOf("tab=integration") !== -1) {
          tab.style.position = "relative";

          // prevent duplicate badge
          if (tab.querySelector(".gshfjf-selected-badge")) return;

          var badge = document.createElement("div");
          badge.className = "gshfjf-selected-badge"; //   IMPORTANT
          badge.textContent = badgeText;

          tab.appendChild(badge);
        }
      });
  }
});

jQuery(document).ready(function ($) {
  const $checkbox = $("#gshfjf_jetform_uninstall_settings_free");
  const $saveBtn = $(".uninstall-settings-save-free");
  const $msg = $("#gshfjf-uninstall-msg-free");
  const $loader = $(".loading-uninstall-free");

  // Page load → disable button
  $saveBtn.prop("disabled", true).addClass("common-disable");

  // Enable button when toggle changes
  $checkbox.on("change", function () {
    $saveBtn.prop("disabled", false).removeClass("common-disable");
  });

  // Save click
  $saveBtn.on("click", function (e) {
    e.preventDefault();

    var isChecked = $checkbox.is(":checked");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      dataType: "json",
      data: {
        action: "gshfjf_save_uninstall_settings_ajax_free",
        uninstall_setting: isChecked ? 1 : 0,
        security: $("#gshfjf-jetform-setting-ajax-nonce").val(),
      },

      beforeSend: function () {
        // 🔥 Loader ON
        $loader.addClass("loading");

        $saveBtn.prop("disabled", true).addClass("common-disable");
      },

      success: function (response) {
        if (!response.success) return;

        $msg.removeClass("gsc-success gsc-error d-none");

        $msg
          .addClass("gsc-success")
          .text("Plugin preferences updated successfully");

        setTimeout(function () {
          $msg.addClass("d-none").text("");
        }, 2000);
      },

      error: function () {
        $msg
          .removeClass("d-none")
          .addClass("gsc-error")
          .text("Something went wrong");

        $saveBtn.prop("disabled", false).removeClass("common-disable");
      },

      complete: function () {
        // 🔥 Loader OFF (always run)
        $loader.removeClass("loading");
      },
    });
  });
});

document.addEventListener("DOMContentLoaded", function () {
  const copyBtn = document.getElementById("gshfjf-copy-logs");
  const msgDiv = document.querySelector(".gshfjf-copy-msg");

  if (!copyBtn || !msgDiv) return;

  copyBtn.addEventListener("click", function (e) {
    e.preventDefault();

    const tbody = document.querySelector(".error-log-table tbody");
    if (!tbody) return;

    const rows = tbody.querySelectorAll("tr");
    if (!rows.length) {
      showMessage("No logs found to copy.", "error");
      return;
    }

    let output = "";

    rows.forEach((tr) => {
      const cols = tr.querySelectorAll("td");
      if (cols.length < 5) return;

      const date = (cols[0].innerText || "").trim();
      const errorId = (cols[1].innerText || "").trim();
      const code = (cols[2].innerText || "").trim();
      const message = (cols[3].innerText || "").trim();

      // 🔥 Proper details extraction
      const detailsCell = cols[4];
      const details = detailsCell.querySelector("pre")
        ? detailsCell.querySelector("pre").innerText.trim()
        : (detailsCell.innerText || "").trim();

      output += `Date: ${date}\n`;
      output += `Error ID: ${errorId}\n`;
      output += `Code: ${code}\n`;
      output += `Message: ${message}\n`;
      output += `Details: ${details}\n`;
      output += `\n==========================\n\n`;
    });

    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(output)
        .then(function () {
          showMessage("Copied successfully", "success");
        })
        .catch(function () {
          fallbackCopy(output);
        });
    } else {
      fallbackCopy(output);
    }

    function fallbackCopy(text) {
      const ta = document.createElement("textarea");
      ta.value = text;
      document.body.appendChild(ta);
      ta.select();
      try {
        document.execCommand("copy");
        showMessage("Copied successfully", "success");
      } catch (err) {
        showMessage("Copy failed. Please copy manually.", "error");
      }
      document.body.removeChild(ta);
    }

    function showMessage(text, type) {
      msgDiv.innerText = text;

      msgDiv.classList.remove("d-none");
      setTimeout(function () {
        msgDiv.classList.add("d-none");
      }, 2000);
    }
  });
});

/* Select box JS Mitesh */
document.addEventListener("DOMContentLoaded", function () {
  // ONLY select with class "gsc-select"
  document.querySelectorAll("select.gsc-select").forEach((select) => {
    // skip already processed
    if (select.classList.contains("auto-processed")) return;
    select.classList.add("auto-processed");

    // hide original select
    select.style.display = "none";

    const wrapper = document.createElement("div");
    wrapper.className = "auto-select";

    const display = document.createElement("div");
    display.className = "auto-select-display";
    display.innerText = select.options[select.selectedIndex]?.text || "Select";

    const optionsBox = document.createElement("div");
    optionsBox.className = "auto-select-options";

    [...select.options].forEach((opt, index) => {
      const item = document.createElement("div");
      item.className = "auto-select-option";
      item.innerText = opt.text;

      item.addEventListener("click", () => {
        select.selectedIndex = index;
        display.innerText = opt.text;
        optionsBox.style.display = "none";

        // trigger change event (WordPress + plugins compatible)
        select.dispatchEvent(new Event("change", { bubbles: true }));
      });

      optionsBox.appendChild(item);
    });

    display.addEventListener("click", (e) => {
      e.stopPropagation();
      optionsBox.style.display =
        optionsBox.style.display === "block" ? "none" : "block";
    });

    wrapper.appendChild(display);
    wrapper.appendChild(optionsBox);

    // insert before select & move select inside
    select.parentNode.insertBefore(wrapper, select);
    wrapper.appendChild(select);
  });

  // close dropdown on outside click
  document.addEventListener("click", function (e) {
    document.querySelectorAll(".auto-select-options").forEach((box) => {
      if (!box.parentElement.contains(e.target)) {
        box.style.display = "none";
      }
    });
  });
});
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll(".gsc-slider-wrapper").forEach(function (wrapper) {
    const slider = wrapper.querySelector(".gsc-slider");
    const slides = wrapper.querySelectorAll(".gsc-slide");
    const prevBtn = wrapper.querySelector(".gsc-nav.prev");
    const nextBtn = wrapper.querySelector(".gsc-nav.next");

    let current = 0;

    function updateSlider() {
      slider.style.transform = "translateX(" + -current * 100 + "%)";
    }

    nextBtn.addEventListener("click", function () {
      current = (current + 1) % slides.length;
      updateSlider();
    });

    prevBtn.addEventListener("click", function () {
      current = (current - 1 + slides.length) % slides.length;
      updateSlider();
    });
  });
});

jQuery(document).ready(function ($) {
  function checkTableEmpty() {
    var rowCount = $("#gsc-jetformformtable tbody tr").length;
    if (rowCount === 0) {
      $(".gshfjf-jetform-feeds-list").removeClass("mt-30");
    }
  }
  checkTableEmpty();

  const btn = document.getElementById("assistantBtn");
  const menu = document.getElementById("assistantMenu");

  btn.addEventListener("click", function () {
    menu.classList.toggle("active");
  });

  // Close when clicking outside
  document.addEventListener("click", function (e) {
    if (!btn.contains(e.target) && !menu.contains(e.target)) {
      menu.classList.remove("active");
    }
  });
});

jQuery(document).ready(function ($) {
  var debugStateKey = "debug_log_state";

  // ---------- More info toggle (UNCHANGED) ----------
  $(".more-error-display").each(function () {
    var box = $(this);
    var maxHeight = 75;

    box.css({
      "max-height": maxHeight + "px",
      overflow: "hidden",
    });

    var clone = box.clone();
    clone.css({
      "max-height": "none",
      height: "auto",
      position: "absolute",
      visibility: "hidden",
      overflow: "visible",
    });

    $("body").append(clone);

    if (clone.outerHeight() > maxHeight) {
      if (box.next(".more-error-toggle").length === 0) {
        var link = $('<a href="#" class="more-error-toggle">More info</a>');
        box.after(link);
      }
    }

    clone.remove();
  });

  $(document).on("click", ".more-error-toggle", function (e) {
    e.preventDefault();

    var link = $(this);
    var box = link.prev(".more-error-display");

    if (box.hasClass("expanded")) {
      box.removeClass("expanded").css("max-height", "75px");
      link.text("More info");
    } else {
      box.addClass("expanded").css("max-height", "none");
      link.text("Less info");
    }
  });
});

/**
 * Export error logs table data to CSV file for download
 * @since 1.0.0
 */

jQuery(document).ready(function ($) {
  $("#gshfjf-csv-info").on("click", function (e) {
    e.preventDefault();

    var rows = $("table.widefat tr");
    var csvContent = "";

    if (rows.length === 0) {
      alert("No error logs found.");
      return;
    }

    rows.each(function () {
      var cols = $(this).find("th, td");
      var rowData = [];

      cols.each(function () {
        var text = $(this).text().trim();

        // Escape quotes
        text = text.replace(/"/g, '""');

        rowData.push('"' + text + '"');
      });

      csvContent += rowData.join(",") + "\n";
    });

    // Create Blob
    var blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });

    var link = document.createElement("a");
    var url = URL.createObjectURL(blob);

    link.setAttribute("href", url);
    link.setAttribute("download", "error-log.csv");
    link.style.visibility = "hidden";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
});

/**
 * Clear debug logs via AJAX on button click.
 *
 * - Shows loading spinner
 * - Sends request to clear logs
 * - Displays success message and reloads the page
 */

jQuery(document).on("click", ".gshfjf-clear-content-logs", function () {
  alert(
    "Are you sure you want to clear the logs? This action cannot be undone.",
  );
  jQuery(".gshfjf-clear-loading-sign-logs").addClass("loading");
  var data = {
    action: "gshfjf_clear_logs",
    security: jQuery("#gshfjf-ajax-nonce").val(),
  };
  jQuery.post(ajaxurl, data, function (response) {
    if (response == -1) {
      return false; // Invalid nonce
    }

    if (response.success) {
      jQuery(".gshfjf-clear-loading-sign-logs").removeClass("loading");
      jQuery(".gshfjf-clear-content-logs-msg").html("Logs are cleared");
      setTimeout(function () {
        location.reload();
      }, 1000);
    }
  });
});

/**
 * Copy error logs table data to clipboard with formatted output
 * @since 1.0.0
 */

jQuery(document).ready(function ($) {
  $("#gshfjf-copy-logs-info").on("click", function (e) {
    e.preventDefault();

    var rows = $("table tbody tr");
    var copyText = "";

    if (!rows.length) {
      alert("No error logs found.");
      return;
    }

    rows.each(function () {
      var cols = $(this).find("td");

      if (cols.length >= 4) {
        copyText += $(cols[0]).text().trim() + "\n"; // Date
        copyText += $(cols[1]).text().trim() + "\n"; // Type
        copyText += $(cols[2]).text().trim() + "\n"; // Message
        copyText += $(cols[3]).text().trim() + "\n"; // File
        copyText += "----------------------------------------\n\n";
      }
    });

    // Temporary textarea copy
    var tempTextarea = $("<textarea>");
    $("body").append(tempTextarea);
    tempTextarea.val(copyText).select();
    document.execCommand("copy");
    tempTextarea.remove();

    // Show success message
    var $msg = $(".gshfjf-copy-msg");

    $msg.text("Copied successfully").removeClass("d-none");

    setTimeout(function () {
      $msg.addClass("d-none");
    }, 3000);
  });
});
