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 Script Debug:", message)
    }
  }

  // Set up AJAX defaults for all jQuery AJAX requests
  $.ajaxSetup({
    xhrFields: {
      withCredentials: true,
    },
    crossDomain: true,
  })

  // Tab switching functionality
  $(".nav-tab-wrapper a").on("click", function (e) {
    e.preventDefault()

    // Remove active class from all tabs
    $(".nav-tab-wrapper a").removeClass("nav-tab-active")

    // Add active class to clicked tab
    $(this).addClass("nav-tab-active")

    // Hide all tab contents
    $(".tab-content").hide()

    // Show the selected tab content
    $($(this).attr("href")).show()

    // Update URL hash without scrolling
    const tabId = $(this).attr("href").substring(1)
    history.pushState(null, null, `?page=moesec&tab=${tabId}#${tabId}`)
  })

  // Check for URL hash and activate the corresponding tab
  function activateTabFromHash() {
    const hash = window.location.hash.substring(1)
    if (hash) {
      const $tabLink = $(`.nav-tab-wrapper a[href="#${hash}"]`)
      if ($tabLink.length) {
        // Don't trigger click to avoid double navigation
        $tabLink.addClass("nav-tab-active")
        $(".tab-content").hide()
        $(`#${hash}`).show()
      }
    }
  }

  // Check URL parameters for tab
  const urlParams = new URLSearchParams(window.location.search)
  const tabParam = urlParams.get("tab")
  if (tabParam) {
    const $tabLink = $(`.nav-tab-wrapper a[href="#${tabParam}"]`)
    if ($tabLink.length) {
      // Don't trigger click to avoid double navigation
      $tabLink.addClass("nav-tab-active")
      $(".tab-content").hide()
      $(`#${tabParam}`).show()
    }
  } else {
    // If no tab parameter, check for hash
    activateTabFromHash()
  }

  debugLog("MoeSec script loaded")
})

