jQuery(document).ready(($) => {
  // Debug function to log messages if debug mode is enabled
  function debugLog(message) {
    if (typeof moesec_ajax !== "undefined" && moesec_ajax.debug_mode) {
      console.log("MoeSec Debug:", message)
    }
  }

  // Set global AJAX defaults for CORS support
  $.ajaxSetup({
    xhrFields: {
      withCredentials: true,
    },
    crossDomain: true,
    beforeSend: (xhr) => {
      xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
    },
    error: (xhr, status, error) => {
      debugLog("AJAX Error - Status: " + status + ", Error: " + error)
      debugLog("Response: " + xhr.responseText)
    },
  })

  // Handle scan mode selection
  $("#moesec-scan-mode-select").on("change", function () {
    debugLog("Scan mode changed to: " + $(this).val())
    if ($(this).val() === "custom") {
      $("#moesec-custom-path-input").show()
    } else {
      $("#moesec-custom-path-input").hide()
    }
  })

  // File scan button click handler
  $("#moesec-file-scan-button").on("click", (e) => {
    e.preventDefault()
    debugLog("File scan initiated")

    var scanMode = $("#moesec-scan-mode-select").val()
    var customPath = ""

    if (scanMode === "custom") {
      customPath = $("#moesec-custom-path").val().trim()
      if (!customPath) {
        var errorMsg = moesec_ajax.enter_path_text || "Please enter a custom path for scanning."
        alert(errorMsg)
        debugLog("Validation error: " + errorMsg)
        return
      }

      // Validate custom path format
      if (!customPath.startsWith("/")) {
        var formatError = moesec_ajax.path_format_error || "Path must start with /"
        alert(formatError)
        debugLog("Path format error: " + formatError)
        return
      }
    }

    // UI updates
    $("#file-scan-progress").show().find(".moesec-progress").css("width", "0%")
    $("#file-scan-status").text(moesec_ajax.scanning_text || "Scanning...")

    // Start the scan via AJAX
    $.ajax({
      url: moesec_ajax.ajax_url,
      type: "POST",
      data: {
        action: "moesec_start_file_scan",
        nonce: moesec_ajax.nonce,
        scan_mode: scanMode,
        custom_path: customPath,
      },
      dataType: "json",
      success: (response) => {
        debugLog("File scan start response:", response)
        if (response && response.success) {
          trackFileScanProgress()
        } else {
          var errorMsg = response && response.data ? response.data.message : "Unknown error"
          $("#file-scan-status").text("Error: " + errorMsg)
          debugLog("Scan start failed: " + errorMsg)
        }
      },
      error: (xhr, status, error) => {
        var errorText = "Error connecting to server. Status: " + xhr.status
        $("#file-scan-status").text(errorText)
        debugLog("AJAX Error: " + status + " - " + error)
        debugLog("Full error: ", xhr)
      },
    })
  })

  // Database scan button click handler
  $("#moesec-db-scan-button").on("click", (e) => {
    e.preventDefault()
    debugLog("Database scan initiated")

    // UI updates
    $("#db-scan-progress").show().find(".moesec-progress").css("width", "0%")
    $("#db-scan-status").text(moesec_ajax.scanning_text || "Scanning...")

    // Start the scan via AJAX
    $.ajax({
      url: moesec_ajax.ajax_url,
      type: "POST",
      data: {
        action: "moesec_start_db_scan",
        nonce: moesec_ajax.nonce,
      },
      dataType: "json",
      success: (response) => {
        debugLog("DB scan start response:", response)
        if (response && response.success) {
          trackDbScanProgress()
        } else {
          var errorMsg = response && response.data ? response.data.message : "Unknown error"
          $("#db-scan-status").text("Error: " + errorMsg)
          debugLog("DB scan start failed: " + errorMsg)
        }
      },
      error: (xhr, status, error) => {
        var errorText = "Error connecting to server. Status: " + xhr.status
        $("#db-scan-status").text(errorText)
        debugLog("AJAX Error: " + status + " - " + error)
      },
    })
  })

  // Refresh quarantine button click handler
  $("#moesec-refresh-quarantine").on("click", (e) => {
    e.preventDefault()
    debugLog("Refreshing quarantine list")

    $.ajax({
      url: moesec_ajax.ajax_url,
      type: "POST",
      data: {
        action: "moesec_refresh_scan_results",
        nonce: moesec_ajax.nonce,
        scan_type: "quarantine",
      },
      dataType: "json",
      success: (response) => {
        debugLog("Quarantine refresh response:", response)
        if (response && response.success) {
          $("#quarantine-results").html(response.data.html)
        } else {
          var errorMsg = response && response.data ? response.data.message : "Unknown error"
          alert("Error: " + errorMsg)
          debugLog("Quarantine refresh failed: " + errorMsg)
        }
      },
      error: (xhr, status, error) => {
        debugLog("AJAX Error refreshing quarantine: " + status + " - " + error)
        alert("Error connecting to server. Status: " + xhr.status)
      },
    })
  })

  // Restore quarantined file handler
  $(document).on("click", ".moesec-restore-file", function (e) {
    e.preventDefault()
    debugLog("Restore quarantined file initiated")

    var fileElement = $(this)
    var quarantineFile = fileElement.data("file")
    var originalPath = fileElement.data("original-path")

    var confirmMsg =
      moesec_ajax.confirm_restore_text ||
      "Are you sure you want to restore this file? This will place it back in its original location."
    if (confirm(confirmMsg)) {
      // Disable button during operation
      fileElement.prop("disabled", true).text("Restoring...")

      $.ajax({
        url: moesec_ajax.ajax_url,
        type: "POST",
        data: {
          action: "moesec_restore_quarantined_file",
          nonce: moesec_ajax.nonce,
          file: quarantineFile,
          original_path: originalPath,
        },
        dataType: "json",
        success: (response) => {
          debugLog("Restore response:", response)
          if (response && response.success) {
            alert(response.data.message)
            // Refresh the quarantine list
            $("#moesec-refresh-quarantine").trigger("click")
          } else {
            var errorMsg = response && response.data ? response.data.message : "Unknown error"
            alert("Error: " + errorMsg)
            debugLog("Restore failed: " + errorMsg)
          }
        },
        error: (xhr, status, error) => {
          debugLog("AJAX Error restoring file: " + status + " - " + error)
          alert("Error connecting to server. Status: " + xhr.status)
        },
        complete: () => {
          // Re-enable button
          fileElement.prop("disabled", false).text("Restore")
        },
      })
    }
  })

  // Delete quarantined file handler
  $(document).on("click", ".moesec-delete-quarantined-file", function (e) {
    e.preventDefault()
    debugLog("Delete quarantined file initiated")

    var fileElement = $(this)
    var quarantineFile = fileElement.data("file")

    var confirmMsg =
      moesec_ajax.confirm_delete_text || "Are you sure you want to permanently delete this quarantined file?"
    if (confirm(confirmMsg)) {
      // Disable button during operation
      fileElement.prop("disabled", true).text("Deleting...")

      $.ajax({
        url: moesec_ajax.ajax_url,
        type: "POST",
        data: {
          action: "moesec_delete_quarantined_file",
          nonce: moesec_ajax.nonce,
          file: quarantineFile,
        },
        dataType: "json",
        success: (response) => {
          debugLog("Delete response:", response)
          if (response && response.success) {
            alert(response.data.message)
            // Refresh the quarantine list
            $("#moesec-refresh-quarantine").trigger("click")
          } else {
            var errorMsg = response && response.data ? response.data.message : "Unknown error"
            alert("Error: " + errorMsg)
            debugLog("Delete failed: " + errorMsg)
          }
        },
        error: (xhr, status, error) => {
          debugLog("AJAX Error deleting file: " + status + " - " + error)
          alert("Error connecting to server. Status: " + xhr.status)
        },
        complete: () => {
          // Re-enable button
          fileElement.prop("disabled", false).text("Delete")
        },
      })
    }
  })

  // Function to track file scan progress
  function trackFileScanProgress() {
    debugLog("Starting file scan progress tracking")
    var progressInterval = setInterval(() => {
      $.ajax({
        url: moesec_ajax.ajax_url,
        type: "POST",
        data: {
          action: "moesec_scan_progress",
          nonce: moesec_ajax.nonce,
          scan_type: "file",
        },
        dataType: "json",
        success: (response) => {
          debugLog("File progress response:", response)
          if (response && response.success) {
            var progress = response.data.progress
            debugLog("File scan progress: " + progress + "%")
            $("#file-scan-progress .moesec-progress").css("width", progress + "%")
            $("#file-scan-status").text(response.data.message + " " + progress + "%")

            // If scan is complete
            if (progress >= 100) {
              clearInterval(progressInterval)
              $("#file-scan-status").text(moesec_ajax.completed_text || "Completed")
              debugLog("File scan completed")
              refreshScanResults("file")
            }
          } else {
            clearInterval(progressInterval)
            var errorMsg = response && response.data ? response.data.message : "Unknown error"
            $("#file-scan-status").text("Error: " + errorMsg)
            debugLog("Progress check error: " + errorMsg)
          }
        },
        error: (xhr, status, error) => {
          debugLog("AJAX Progress Error: " + status + " - " + error)

          // After 3 failed attempts, stop trying
          if (xhr.retryCount && xhr.retryCount >= 3) {
            clearInterval(progressInterval)
            $("#file-scan-status").text("Failed to get progress updates")
            debugLog("Giving up after 3 failed attempts")
          }

          // Set retry count
          xhr.retryCount = xhr.retryCount ? xhr.retryCount + 1 : 1
        },
      })
    }, 1500) // Check every 1.5 seconds
  }

  // Function to track database scan progress
  function trackDbScanProgress() {
    debugLog("Starting DB scan progress tracking")
    var progressInterval = setInterval(() => {
      $.ajax({
        url: moesec_ajax.ajax_url,
        type: "POST",
        data: {
          action: "moesec_scan_progress",
          nonce: moesec_ajax.nonce,
          scan_type: "db",
        },
        dataType: "json",
        success: (response) => {
          debugLog("DB progress response:", response)
          if (response && response.success) {
            var progress = response.data.progress
            debugLog("DB scan progress: " + progress + "%")
            $("#db-scan-progress .moesec-progress").css("width", progress + "%")
            $("#db-scan-status").text(response.data.message + " " + progress + "%")

            // If scan is complete
            if (progress >= 100) {
              clearInterval(progressInterval)
              $("#db-scan-status").text(moesec_ajax.completed_text || "Completed")
              debugLog("DB scan completed")
              refreshScanResults("db")
            }
          } else {
            clearInterval(progressInterval)
            var errorMsg = response && response.data ? response.data.message : "Unknown error"
            $("#db-scan-status").text("Error: " + errorMsg)
            debugLog("Progress check error: " + errorMsg)
          }
        },
        error: (xhr, status, error) => {
          debugLog("AJAX Progress Error: " + status + " - " + error)

          // After 3 failed attempts, stop trying
          if (xhr.retryCount && xhr.retryCount >= 3) {
            clearInterval(progressInterval)
            $("#db-scan-status").text("Failed to get progress updates")
            debugLog("Giving up after 3 failed attempts")
          }

          // Set retry count
          xhr.retryCount = xhr.retryCount ? xhr.retryCount + 1 : 1
        },
      })
    }, 1500) // Check every 1.5 seconds
  }

  // Function to refresh scan results
  function refreshScanResults(scanType) {
    debugLog("Refreshing " + scanType + " scan results")
    $.ajax({
      url: moesec_ajax.ajax_url,
      type: "POST",
      data: {
        action: "moesec_refresh_scan_results",
        nonce: moesec_ajax.nonce,
        scan_type: scanType,
      },
      dataType: "json",
      success: (response) => {
        debugLog("Refresh results response:", response)
        if (response && response.success) {
          debugLog("Results refreshed successfully")
          if (scanType === "file") {
            $("#file-scan-results").html(response.data.html)
          } else if (scanType === "db") {
            $("#db-scan-results").html(response.data.html)
          }
        } else {
          var errorMsg = response && response.data ? response.data.message : "Unknown error"
          debugLog("Error refreshing results: " + errorMsg)
        }
      },
      error: (xhr, status, error) => {
        debugLog("AJAX Error refreshing results: " + status + " - " + error)
      },
    })
  }

  // Initial debug information
  debugLog("MoeSec scan script fully loaded")
  debugLog("AJAX URL: " + (moesec_ajax.ajax_url || "Not Defined"))
  debugLog("Nonce: " + (moesec_ajax.nonce ? "Available" : "Missing"))
  debugLog("Debug Mode: " + (moesec_ajax.debug_mode ? "Enabled" : "Disabled"))
})

