/**
 * Sentinel Settings Page JavaScript
 *
 * JavaScript for the settings page functionality including tab switching,
 * dynamic form controls, and post-submission handling.
 */

(function ($) {
  "use strict";

  $(document).ready(function () {
    // Tab switching functionality
    const tabs = document.querySelectorAll(".sentinel-tab");
    const tabContents = document.querySelectorAll(".sentinel-tab-content");

    tabs.forEach((tab) => {
      tab.addEventListener("click", function (e) {
        e.preventDefault();

        // Remove active class from all tabs
        tabs.forEach((t) => t.classList.remove("sentinel-tab-active"));

        // Add active class to clicked tab
        this.classList.add("sentinel-tab-active");

        // Hide all tab contents
        tabContents.forEach((content) => {
          content.style.display = "none";
        });

        // Show the selected tab content
        const targetTab = this.getAttribute("data-tab");
        const targetContent = document.getElementById(targetTab + "-tab");
        if (targetContent) {
          targetContent.style.display = "block";
        }

        // Update hidden tab field for form submission
        const tabField = document.getElementById("sentinel_current_tab");
        if (tabField) {
          tabField.value = targetTab;
        }
      });
    });

    // Archive retention settings
    const archiveSelect = document.getElementById("archive_retention_type");
    const customDiv = document.getElementById("custom_archive_days");

    if (archiveSelect) {
      archiveSelect.addEventListener("change", function () {
        if (this.value === "custom") {
          customDiv.style.display = "block";
        } else {
          customDiv.style.display = "none";
        }
      });
    }

    // Performance & Resource Control settings
    const batchLoggingCheckbox = document.getElementById(
      "batch_logging_enabled"
    );
    const batchSizeRow = document.getElementById("batch_size_row");
    const batchFrequencyRow = document.getElementById("batch_frequency_row");

    if (batchLoggingCheckbox) {
      batchLoggingCheckbox.addEventListener("change", function () {
        if (this.checked) {
          batchSizeRow.style.display = "table-row";
          batchFrequencyRow.style.display = "table-row";
        } else {
          batchSizeRow.style.display = "none";
          batchFrequencyRow.style.display = "none";
        }
      });
    }

    const rateLimitingCheckbox = document.getElementById(
      "rate_limiting_enabled"
    );
    const rateLimitMinuteRow = document.getElementById("rate_limit_minute_row");
    const rateLimitHourRow = document.getElementById("rate_limit_hour_row");
    const rateLimitBehaviorRow = document.getElementById(
      "rate_limit_behavior_row"
    );

    if (rateLimitingCheckbox) {
      rateLimitingCheckbox.addEventListener("change", function () {
        if (this.checked) {
          rateLimitMinuteRow.style.display = "table-row";
          rateLimitHourRow.style.display = "table-row";
          if (rateLimitBehaviorRow) {
            rateLimitBehaviorRow.style.display = "table-row";
          }
        } else {
          rateLimitMinuteRow.style.display = "none";
          rateLimitHourRow.style.display = "none";
          if (rateLimitBehaviorRow) {
            rateLimitBehaviorRow.style.display = "none";
          }
        }
      });
    }

    const memoryMonitoringCheckbox = document.getElementById(
      "memory_monitoring_enabled"
    );
    const memoryThresholdRow = document.getElementById("memory_threshold_row");
    const memoryLeakDetectionRow = document.getElementById("memory_leak_detection_row");

    if (memoryMonitoringCheckbox) {
      memoryMonitoringCheckbox.addEventListener("change", function () {
        if (this.checked) {
          memoryThresholdRow.style.display = "table-row";
          if (memoryLeakDetectionRow) {
            memoryLeakDetectionRow.style.display = "table-row";
          }
        } else {
          memoryThresholdRow.style.display = "none";
          if (memoryLeakDetectionRow) {
            memoryLeakDetectionRow.style.display = "none";
          }
        }
      });
    }

    // Handle custom toggle switches for ALL checkboxes
    // This makes the visual toggles actually work with hidden checkboxes
    $(document).on(
      "click",
      '.sentinel-settings-card-content .form-table td label:has(input[type="checkbox"])',
      function (e) {
        e.preventDefault(); // Prevent default label click behavior

        // Find the checkbox within this label
        const checkbox = $(this).find('input[type="checkbox"]')[0];
        if (checkbox) {
          // Toggle the checkbox state (use jQuery to ensure proper DOM update)
          const newState = !checkbox.checked;
          $(checkbox).prop("checked", newState);

          // Set the HTML checked attribute for form submission
          if (newState) {
            checkbox.setAttribute("checked", "checked");
          } else {
            checkbox.removeAttribute("checked");
          }

          // Trigger change event for any existing handlers
          $(checkbox).trigger("change");
        }
      }
    );

    // Handle post-submission redirect if needed
    if (
      typeof sentinelSettingsData !== "undefined" &&
      sentinelSettingsData.needsRedirect
    ) {
      setTimeout(function () {
        const currentTab = sentinelSettingsData.currentTab;
        const newUrl = new URL(window.location);
        newUrl.searchParams.set("tab", currentTab);
        newUrl.searchParams.set("settings-updated", "true");
        newUrl.searchParams.delete("message"); // Remove any existing message param

        // Use replaceState to update URL without refreshing the page
        window.history.replaceState({}, "", newUrl.toString());

        // Update the hidden tab field to match the current state
        const tabField = document.getElementById("sentinel_current_tab");
        if (tabField) {
          tabField.value = currentTab;
        }

        // Scroll to top to ensure user sees success message
        window.scrollTo(0, 0);
      }, 100);
    }

    // Export button (uses selected options)
    var exportBtn = document.getElementById("sentinel-export-btn");
    if (exportBtn) {
      exportBtn.addEventListener("click", function (e) {
        e.preventDefault();
        var nonce = document.getElementById(
          "sentinel-export-logs-json-nonce"
        ).value;
        var dateRange = document.getElementById("export_date_range")
          ? document.getElementById("export_date_range").value
          : "30";
        var format = document.getElementById("export_format")
          ? document.getElementById("export_format").value
          : "json";
        var source = getSelectedExportSource();
        var formData = new FormData();
        formData.append("action", "sentinel_export_logs_json");
        formData.append("nonce", nonce);
        formData.append("date_range", dateRange);
        formData.append("format", format);
        formData.append("export_source", source);
        exportBtn.classList.add("disabled");
        var originalText = exportBtn.textContent;
        exportBtn.textContent = "Exporting...";
        fetch(ajaxurl, {
          method: "POST",
          credentials: "same-origin",
          body: formData,
        })
          .then((response) => {
            if (!response.ok) throw new Error("Network response was not ok");
            return response.blob();
          })
          .then((blob) => {
            var ext =
              format === "csv" ? "csv" : format === "xml" ? "xml" : "json";
            var src = source === "both" ? "all" : source;
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = url;
            a.download =
              "sentinel-logs-" + src + "-" + dateRange + "-days." + ext;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
            exportBtn.classList.remove("disabled");
            exportBtn.textContent = originalText;
          })
          .catch((error) => {
            alert("Export failed: " + error.message);
            exportBtn.classList.remove("disabled");
            exportBtn.textContent = originalText;
          });
      });
    }

    // Quick Export Last 30 Days button (always main logs, JSON)
    var quickBtn = document.getElementById("sentinel-export-quick-btn");
    if (quickBtn) {
      quickBtn.addEventListener("click", function (e) {
        e.preventDefault();
        var nonce = document.getElementById(
          "sentinel-export-logs-json-nonce"
        ).value;
        var formData = new FormData();
        formData.append("action", "sentinel_export_logs_json");
        formData.append("nonce", nonce);
        formData.append("date_range", "30");
        formData.append("format", "json");
        formData.append("export_source", "main");
        quickBtn.classList.add("disabled");
        var originalText = quickBtn.textContent;
        quickBtn.textContent = "Exporting...";
        fetch(ajaxurl, {
          method: "POST",
          credentials: "same-origin",
          body: formData,
        })
          .then((response) => {
            if (!response.ok) throw new Error("Network response was not ok");
            return response.blob();
          })
          .then((blob) => {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = url;
            a.download = "sentinel-logs-main-30-days.json";
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
            quickBtn.classList.remove("disabled");
            quickBtn.textContent = originalText;
          })
          .catch((error) => {
            alert("Export failed: " + error.message);
            quickBtn.classList.remove("disabled");
            quickBtn.textContent = originalText;
          });
      });
    }

    // Sentinel 3-way segmented toggle logic
    var segmentedToggle = document.getElementById("export_source_toggle");
    if (segmentedToggle) {
      var buttons = segmentedToggle.querySelectorAll(".sentinel-segmented-btn");
      var slider = segmentedToggle.querySelector(".slider");

      buttons.forEach(function (btn, index) {
        btn.addEventListener("click", function () {
          // Remove active state from all buttons
          buttons.forEach(function (b) {
            b.classList.remove("active");
            b.setAttribute("aria-pressed", "false");
          });

          // Add active state to clicked button
          btn.classList.add("active");
          btn.setAttribute("aria-pressed", "true");

          // Move slider to correct position
          if (slider) {
            slider.setAttribute("data-position", index);
            slider.style.transform = `translateX(${index * 100}px)`;
          }
        });
      });
    }

    // Initialize tab state on page load
    initializeTabState();

    // API Key Management
    initializeApiKeyManagement();
  });

  /**
   * Initialize the correct tab state on page load
   */
  function initializeTabState() {
    // Check URL parameters for tab
    const urlParams = new URLSearchParams(window.location.search);
    const urlTab = urlParams.get("tab");

    // Check hidden field for tab
    const tabField = document.getElementById("sentinel_current_tab");
    const fieldTab = tabField ? tabField.value : null;

    // Determine which tab to show (URL takes precedence)
    const activeTab = urlTab || fieldTab || "database";

    // Update the hidden field
    if (tabField) {
      tabField.value = activeTab;
    }

    // Activate the correct tab
    const targetTabLink = document.querySelector(
      '.sentinel-tab[data-tab="' + activeTab + '"]'
    );
    const targetTabContent = document.getElementById(activeTab + "-tab");

    if (targetTabLink && targetTabContent) {
      // Remove active class from all tabs
      document.querySelectorAll(".sentinel-tab").forEach((tab) => {
        tab.classList.remove("sentinel-tab-active");
      });

      // Hide all tab contents
      document.querySelectorAll(".sentinel-tab-content").forEach((content) => {
        content.style.display = "none";
      });

      // Activate the target tab
      targetTabLink.classList.add("sentinel-tab-active");
      targetTabContent.style.display = "block";
    }
  }

  // Update export logic to read the selected export source value
  function getSelectedExportSource() {
    var segmented = document.getElementById("export_source_toggle");
    if (!segmented) return "main";
    var activeBtn = segmented.querySelector(".sentinel-segmented-btn.active");
    return activeBtn ? activeBtn.getAttribute("data-value") : "main";
  }

  // File monitoring test button
  $("#test-file-check").on("click", function () {
    var $button = $(this);
    var $result = $("#test-file-result");

    $button.prop("disabled", true).text("Testing...");
    $result.text("");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "sentinel_test_file_check",
        nonce: $("#test-file-check").data("nonce"),
      },
      success: function (response) {
        if (response.success) {
          $result.html(
            '<span style="color: green;">✓ ' + response.data + "</span>"
          );
        } else {
          $result.html(
            '<span style="color: red;">✗ Error: ' + response.data + "</span>"
          );
        }
      },
      error: function () {
        $result.html('<span style="color: red;">✗ AJAX Error</span>');
      },
      complete: function () {
        $button.prop("disabled", false).text("Test File Check Now");
      },
    });
  });

  // =======================
  // Custom Events Management (Premium)
  // =======================

  // Load custom events when the custom events tab is activated
  $(document).on(
    "click",
    '.sentinel-tab[data-tab="custom-events"]',
    function () {
      setTimeout(function () {
        loadCustomEvents();
      }, 100);
    }
  );

  // Load custom events on Event Registry page (if custom events section exists)
  if ($("#sentinel-events-container").length > 0) {
    setTimeout(function () {
      loadCustomEvents();
    }, 100);
  }

  // Add new custom event
  $("#sentinel-add-custom-event").on("click", function () {
    const eventKey = $("#custom_event_key").val().trim();
    const label = $("#custom_event_label").val().trim();
    const category = $("#custom_event_category").val();
    const priority = $("#custom_event_priority").val();
    const description = $("#custom_event_description").val().trim();
    const statusSpan = $("#sentinel-add-event-status");
    const button = $(this);

    // Validation
    if (!eventKey || !label) {
      statusSpan.html(
        '<span style="color: #dc2626;">❌ Event key and label are required</span>'
      );
      return;
    }

    // Validate event key format
    if (!/^[a-zA-Z0-9_]+$/.test(eventKey)) {
      statusSpan.html(
        '<span style="color: #dc2626;">❌ Event key can only contain letters, numbers, and underscores</span>'
      );
      return;
    }

    // Show loading state
    button.prop("disabled", true).text("Adding...");
    statusSpan.html(
      '<span style="color: #6b7280;">Adding custom event...</span>'
    );

    // Make AJAX request
    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "sentinel_add_custom_event",
        event_key: eventKey,
        label: label,
        category: category,
        priority: priority,
        description: description,
        nonce: $("#sentinel_ajax_nonce").val(),
      },
      success: function (response) {
        const result = JSON.parse(response);

        if (result.success) {
          statusSpan.html(
            '<span style="color: #059669;">✅ ' + result.message + "</span>"
          );

          // Clear form
          $("#custom_event_key").val("");
          $("#custom_event_label").val("");
          $("#custom_event_category").val("general");
          $("#custom_event_priority").val("medium");
          $("#custom_event_description").val("");

          // Reload events list
          loadCustomEvents();

          // Clear status after 3 seconds
          setTimeout(function () {
            statusSpan.html("");
          }, 3000);
        } else {
          statusSpan.html(
            '<span style="color: #dc2626;">❌ ' + result.error + "</span>"
          );
        }
      },
      error: function () {
        statusSpan.html(
          '<span style="color: #dc2626;">❌ Network error occurred</span>'
        );
      },
      complete: function () {
        button
          .prop("disabled", false)
          .html(
            '<i class="dashicons dashicons-plus-alt"></i> Add Custom Event'
          );
      },
    });
  });

  // Toggle custom event status
  $(document).on("change", ".sentinel-custom-event-toggle", function () {
    const checkbox = $(this);
    const eventKey = checkbox.data("event-key");
    const isEnabled = checkbox.is(":checked");
    const row = checkbox.closest("tr");

    // Disable checkbox during request
    checkbox.prop("disabled", true);

    // Add loading state to row
    row.addClass("sentinel-updating");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "sentinel_toggle_custom_event",
        event_key: eventKey,
        enabled: isEnabled ? 1 : 0,
        nonce: $("#sentinel_ajax_nonce").val(),
      },
      success: function (response) {
        const result = JSON.parse(response);

        if (!result.success) {
          // Revert checkbox on error
          checkbox.prop("checked", !isEnabled);
          alert("Error: " + result.error);
        }

        // Remove loading state and re-enable
        row.removeClass("sentinel-updating");
        checkbox.prop("disabled", false);
      },
      error: function () {
        // Revert checkbox on error
        checkbox.prop("checked", !isEnabled);
        row.removeClass("sentinel-updating");
        checkbox.prop("disabled", false);
        alert("Network error occurred while toggling event.");
      },
    });
  });

  // Remove custom event (delegated event handler)
  $(document).on("click", ".sentinel-remove-custom-event", function () {
    const eventKey = $(this).data("event-key");
    const eventLabel = $(this).data("event-label");

    if (
      !confirm(
        `Are you sure you want to remove the custom event "${eventLabel}" (${eventKey})?\n\nThis action cannot be undone.`
      )
    ) {
      return;
    }

    const button = $(this);
    const row = button.closest(".sentinel-custom-event-row");

    // Show loading state
    button.prop("disabled", true).text("Removing...");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "sentinel_remove_custom_event",
        event_key: eventKey,
        nonce: $("#sentinel_ajax_nonce").val(),
      },
      success: function (response) {
        const result = JSON.parse(response);

        if (result.success) {
          // Fade out and remove the row
          row.fadeOut(300, function () {
            $(this).remove();

            // Check if no events left
            if ($(".sentinel-custom-event-row").length === 0) {
              $("#sentinel-events-container").html(
                '<p style="color: #6b7280; font-style: italic;">No custom events registered yet.</p>'
              );
            }
          });
        } else {
          alert("Error: " + result.error);
          button.prop("disabled", false).text("Remove");
        }
      },
      error: function () {
        alert("Network error occurred");
        button.prop("disabled", false).text("Remove");
      },
    });
  });

  // Load custom events function
  function loadCustomEvents() {
    const container = $("#sentinel-events-container");

    // Show loading
    container.html(
      '<p id="sentinel-loading-events" style="color: #6b7280; font-style: italic;">Loading custom events...</p>'
    );

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "sentinel_get_custom_events",
        nonce: $("#sentinel_ajax_nonce").val(),
      },
      success: function (response) {
        const result = JSON.parse(response);

        if (result.success) {
          const events = result.events;

          if (Object.keys(events).length === 0) {
            container.html(
              '<p style="color: #6b7280; font-style: italic;">No custom events registered yet.</p>'
            );
          } else {
            let html = `
              <div class="sentinel-events-table">
                <table class="wp-list-table widefat fixed striped">
                  <thead>
                    <tr>
                      <th style="width: 50px;">Status</th>
                      <th>Event Key</th>
                      <th>Category</th>
                      <th>Priority</th>
                      <th>Description</th>
                      <th>Usage Count</th>
                      <th>Last Triggered</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
            `;

            for (const [eventKey, config] of Object.entries(events)) {
              const isEnabled = config.enabled !== false; // Default to enabled unless explicitly disabled
              const rowClass = isEnabled ? "" : " sentinel-event-disabled";

              html += `
                <tr class="sentinel-custom-event-row${rowClass}">
                  <td>
                    <label class="sentinel-toggle-switch">
                      <input type="checkbox" class="sentinel-custom-event-toggle"
                             data-event-key="${eventKey}" ${isEnabled ? "checked" : ""
                }>
                      <span class="sentinel-toggle-slider"></span>
                    </label>
                  </td>
                  <td>
                    <code class="sentinel-event-key">${eventKey}</code>
                  </td>
                  <td>
                    <span class="sentinel-category sentinel-category-${config.category
                }">
                      ${config.category.charAt(0).toUpperCase() +
                config.category.slice(1)
                }
                    </span>
                  </td>
                  <td>
                    <span class="sentinel-priority sentinel-priority-${config.priority
                }">
                      ${config.priority.charAt(0).toUpperCase() +
                config.priority.slice(1)
                }
                    </span>
                  </td>
                  <td>${config.description || ""}</td>
                  <td>
                    <span class="sentinel-no-usage">Never triggered</span>
                  </td>
                  <td>
                    <span class="sentinel-no-usage">Never triggered</span>
                  </td>
                  <td>
                    <button class="button button-small"
                            onclick="showCustomEventDetails('${eventKey}')">
                      View Details
                    </button>
                    <button type="button" class="sentinel-remove-custom-event button button-small"
                            data-event-key="${eventKey}" data-event-label="${config.label
                }"
                            style="color: #dc2626; border-color: #dc2626; margin-left: 5px;">
                      Remove
                    </button>
                  </td>
                </tr>
                <tr id="custom-event-details-${eventKey}" style="display: none;">
                  <td colspan="8">
                    <div class="sentinel-event-details">
                      <h4>Event Details: ${eventKey}</h4>
                      <div class="sentinel-detail-grid">
                        <div class="sentinel-detail-column">
                          <div class="sentinel-detail-row">
                            <strong>Event Key:</strong>
                            <code>${eventKey}</code>
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Label:</strong>
                            ${config.label}
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Category:</strong>
                            <span class="sentinel-category sentinel-category-${config.category
                }">
                              ${config.category.charAt(0).toUpperCase() +
                config.category.slice(1)
                }
                            </span>
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Priority:</strong>
                            <span class="sentinel-priority sentinel-priority-${config.priority
                }">
                              ${config.priority.charAt(0).toUpperCase() +
                config.priority.slice(1)
                }
                            </span>
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Status:</strong>
                            <span class="sentinel-status-${isEnabled ? "enabled" : "disabled"
                }">
                              ${isEnabled ? "Enabled" : "Disabled"}
                            </span>
                          </div>
                        </div>
                        <div class="sentinel-detail-column">
                          <div class="sentinel-detail-row">
                            <strong>Total Triggers:</strong>
                            0
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>First Triggered:</strong>
                            Never
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Last Triggered:</strong>
                            Never
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Event Type:</strong>
                            Custom Event
                          </div>
                          <div class="sentinel-detail-row">
                            <strong>Description:</strong>
                            ${config.description || "No description provided"}
                          </div>
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
              `;
            }

            html += `
                  </tbody>
                </table>
              </div>
            `;

            container.html(html);
          }
        } else {
          container.html(
            '<p style="color: #dc2626;">Error loading custom events: ' +
            result.error +
            "</p>"
          );
        }
      },
      error: function () {
        container.html(
          '<p style="color: #dc2626;">Network error occurred while loading custom events.</p>'
        );
      },
    });
  }

  // Template setup button handler
  $(document).on("click", ".sentinel-setup-template", function () {
    const button = $(this);
    const template = button.data("template");
    const statusDiv = $(`#template-status-${template}`);

    // Clear previous status and show loading
    statusDiv
      .removeClass("success error")
      .addClass("loading")
      .text("Setting up events...");

    // Disable button and show loading state
    button.prop("disabled", true).text("Setting up...");

    $.ajax({
      url: ajaxurl,
      type: "POST",
      data: {
        action: "sentinel_setup_template",
        template: template,
        nonce: $("#sentinel_ajax_nonce").val(),
      },
      success: function (response) {
        const result = JSON.parse(response);

        if (result.success) {
          // Show success message in status div
          statusDiv
            .removeClass("loading")
            .addClass("success")
            .text(
              `Successfully created ${result.events_created} custom events`
            );

          // Update button to success state
          button.text("✓ Events Created").css({
            background: "#059669",
            cursor: "default",
          });

          // Refresh the custom events list
          setTimeout(function () {
            loadCustomEvents();
          }, 500);
        } else {
          // Show error in status div
          statusDiv.removeClass("loading").addClass("error").text(result.error);

          // Restore button
          button
            .prop("disabled", false)
            .text(
              `Setup ${template.charAt(0).toUpperCase() + template.slice(1)
              } Events`
            );
        }
      },
      error: function () {
        // Show network error in status div
        statusDiv
          .removeClass("loading")
          .addClass("error")
          .text("Network error occurred while setting up template");

        // Restore button
        button
          .prop("disabled", false)
          .text(
            `Setup ${template.charAt(0).toUpperCase() + template.slice(1)
            } Events`
          );
      },
    });
  });

  // Show/hide custom event details (global function for onclick)
  window.showCustomEventDetails = function (eventKey) {
    const detailsRow = document.getElementById(
      "custom-event-details-" + eventKey
    );
    if (detailsRow) {
      if (detailsRow.style.display === "none") {
        detailsRow.style.display = "table-row";
      } else {
        detailsRow.style.display = "none";
      }
    }
  };

  // Helper functions for custom events display
  function getPriorityColor(priority) {
    switch (priority) {
      case "critical":
        return "#dc2626";
      case "high":
        return "#ea580c";
      case "medium":
        return "#0891b2";
      case "low":
        return "#059669";
      default:
        return "#6b7280";
    }
  }

  function getCategoryIcon(category) {
    switch (category) {
      case "authentication":
        return "🔐";
      case "content":
        return "📝";
      case "system":
        return "⚙️";
      case "security":
        return "🛡️";
      case "user":
        return "👤";
      case "admin":
        return "👨‍💼";
      case "audit":
        return "📋";
      case "ecommerce":
        return "🛒";
      case "custom":
        return "🎯";
      default:
        return "📊";
    }
  }

  // =======================
  // API Key Management
  // =======================

  /**
   * Initialize API Key Management
   */
  function initializeApiKeyManagement() {
    // Generate API Key
    $('#generate-api-key').on('click', function () {
      handleApiKeyGeneration(false);
    });

    // Regenerate API Key
    $('#regenerate-api-key').on('click', function () {
      showConfirm(
        'Are you sure you want to regenerate your API key? This will invalidate the current key and any applications using it will need to be updated.',
        'Regenerate API Key',
        function (confirmed) {
          if (confirmed) {
            handleApiKeyGeneration(true);
          }
        }
      );
    });

    // Copy API Key
    $('#copy-api-key').on('click', function () {
      const apiKey = $(this).data('key');
      if (apiKey) {
        copyToClipboard(apiKey);
      }
    });

  }

  /**
   * Handle API Key Generation/Regeneration
   */
  function handleApiKeyGeneration(isRegenerate) {
    const $button = isRegenerate ? $('#regenerate-api-key') : $('#generate-api-key');
    const $status = $('#api-key-status');
    const $input = $('#sentinel_api_key');

    // Show loading state
    $button.prop('disabled', true);
    $status.removeClass('success error info').addClass('loading').text('Generating secure API key...');

    // Generate secure API key
    const apiKey = generateSecureApiKey();

    // Save via AJAX
    $.ajax({
      url: ajaxurl,
      type: 'POST',
      data: {
        action: 'sentinel_save_api_key',
        api_key: apiKey,
        nonce: $('#sentinel_settings_nonce').val()
      },
      success: function (response) {
        if (response.success) {
          // Update UI
          const maskedKey = 'sent_' + '*'.repeat(20) + apiKey.slice(-4);
          $input.val(maskedKey);

          // Update buttons
          if (!isRegenerate) {
            // Switch from Generate to Copy/Regenerate buttons
            const $container = $('.sentinel-api-key-actions');
            $container.html(`
              <button type="button" id="copy-api-key" class="button button-secondary" data-key="${apiKey}">
                <i class="dashicons dashicons-clipboard"></i>
                Copy
              </button>
              <button type="button" id="regenerate-api-key" class="button button-secondary">
                <i class="dashicons dashicons-update"></i>
                Regenerate
              </button>
            `);

            // Reinitialize event handlers
            initializeApiKeyManagement();
          } else {
            // Update copy button with new key
            $('#copy-api-key').data('key', apiKey);
          }

          $status.removeClass('loading error').addClass('success').text('API key generated successfully!');

          // Auto-copy to clipboard
          copyToClipboard(apiKey);

        } else {
          const errorMsg = response.data || 'Unknown error';
          $status.removeClass('loading success').addClass('error').text('Failed to save API key: ' + errorMsg);
          showAlert('Failed to save API key: ' + errorMsg, 'Error');
        }
      },
      error: function () {
        $status.removeClass('loading success').addClass('error').text('Network error occurred while saving API key.');
        showAlert('Network error occurred while saving API key.', 'Connection Error');
      },
      complete: function () {
        $button.prop('disabled', false);

        // Clear status after 5 seconds
        setTimeout(function () {
          $status.removeClass('success error loading info').text('');
        }, 5000);
      }
    });
  }

  /**
   * Generate a secure API key
   */
  function generateSecureApiKey() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = 'sent_';

    // Generate 32 random characters
    for (let i = 0; i < 32; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }

    return result;
  }

  /**
   * Copy text to clipboard with visual feedback
   */
  function copyToClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
      // Modern clipboard API
      navigator.clipboard.writeText(text).then(function () {
        showCopySuccess();
      }).catch(function () {
        fallbackCopyToClipboard(text);
      });
    } else {
      // Fallback for older browsers
      fallbackCopyToClipboard(text);
    }
  }

  /**
   * Fallback clipboard copy for older browsers
   */
  function fallbackCopyToClipboard(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      document.execCommand('copy');
      showCopySuccess();
    } catch (err) {
      $('#api-key-status').removeClass('success loading').addClass('error').text('Failed to copy to clipboard');
    }

    document.body.removeChild(textArea);
  }

  /**
   * Show copy success feedback
   */
  function showCopySuccess() {
    const $copyBtn = $('#copy-api-key');
    const $status = $('#api-key-status');

    // Update button temporarily
    $copyBtn.addClass('copied');
    const originalText = $copyBtn.find('i').next().length ? $copyBtn.find('i').next().text() : 'Copy';
    $copyBtn.contents().filter(function () {
      return this.nodeType === 3; // Text nodes
    }).remove();
    $copyBtn.append(' Copied!');

    // Update status
    $status.removeClass('error loading').addClass('success').text('API key copied to clipboard!');

    // Reset after 2 seconds
    setTimeout(function () {
      $copyBtn.removeClass('copied');
      $copyBtn.contents().filter(function () {
        return this.nodeType === 3; // Text nodes
      }).remove();
      $copyBtn.append(' ' + originalText);

      $status.removeClass('success error loading info').text('');
    }, 2000);
  }

  // =======================
  // Custom Alert & Confirm Modals
  // =======================

  /**
   * Show custom alert modal
   */
  function showAlert(message, title = 'Alert') {
    const modalHtml = `
      <div class="sentinel-modal-overlay sentinel-alert-modal" id="sentinel-alert-modal">
        <div class="sentinel-modal">
          <div class="sentinel-modal-header">
            <h3>${title}</h3>
            <button class="sentinel-modal-close" type="button">&times;</button>
          </div>
          <div class="sentinel-modal-content">
            <p>${message}</p>
          </div>
          <div class="sentinel-modal-footer">
            <button class="sentinel-modal-btn sentinel-btn-primary" type="button" id="alert-ok-btn">
              OK
            </button>
          </div>
        </div>
      </div>
    `;

    // Remove any existing alert modal
    $('#sentinel-alert-modal').remove();

    // Add modal to page
    $('body').append(modalHtml);

    // Show modal
    const $modal = $('#sentinel-alert-modal');
    setTimeout(() => $modal.addClass('sentinel-modal-active'), 10);

    // Prevent body scroll
    $('body').addClass('modal-open');

    // Handle close events
    $modal.find('.sentinel-modal-close, #alert-ok-btn').on('click', function () {
      closeAlert();
    });

    // Close on overlay click
    $modal.on('click', function (e) {
      if (e.target === this) {
        closeAlert();
      }
    });

    // Close on ESC key
    $(document).on('keydown.alert', function (e) {
      if (e.key === 'Escape') {
        closeAlert();
      }
    });
  }

  /**
   * Show custom confirm modal
   */
  function showConfirm(message, title = 'Confirm', callback = null) {
    const modalHtml = `
      <div class="sentinel-modal-overlay sentinel-confirm-modal" id="sentinel-confirm-modal">
        <div class="sentinel-modal">
          <div class="sentinel-modal-header">
            <h3>${title}</h3>
            <button class="sentinel-modal-close" type="button">&times;</button>
          </div>
          <div class="sentinel-modal-content">
            <p>${message}</p>
          </div>
          <div class="sentinel-modal-footer">
            <button class="sentinel-modal-btn sentinel-btn-secondary" type="button" id="confirm-cancel-btn">
              Cancel
            </button>
            <button class="sentinel-modal-btn sentinel-btn-danger" type="button" id="confirm-ok-btn">
              Confirm
            </button>
          </div>
        </div>
      </div>
    `;

    // Remove any existing confirm modal
    $('#sentinel-confirm-modal').remove();

    // Add modal to page
    $('body').append(modalHtml);

    // Show modal
    const $modal = $('#sentinel-confirm-modal');
    setTimeout(() => $modal.addClass('sentinel-modal-active'), 10);

    // Prevent body scroll
    $('body').addClass('modal-open');

    // Handle confirm
    $modal.find('#confirm-ok-btn').on('click', function () {
      closeConfirm();
      if (callback) callback(true);
    });

    // Handle cancel
    $modal.find('.sentinel-modal-close, #confirm-cancel-btn').on('click', function () {
      closeConfirm();
      if (callback) callback(false);
    });

    // Close on overlay click (counts as cancel)
    $modal.on('click', function (e) {
      if (e.target === this) {
        closeConfirm();
        if (callback) callback(false);
      }
    });

    // Close on ESC key (counts as cancel)
    $(document).on('keydown.confirm', function (e) {
      if (e.key === 'Escape') {
        closeConfirm();
        if (callback) callback(false);
      }
    });
  }

  /**
   * Close alert modal
   */
  function closeAlert() {
    const $modal = $('#sentinel-alert-modal');
    $modal.removeClass('sentinel-modal-active');
    $('body').removeClass('modal-open');
    $(document).off('keydown.alert');

    setTimeout(() => {
      $modal.remove();
    }, 300);
  }

  /**
   * Close confirm modal
   */
  function closeConfirm() {
    const $modal = $('#sentinel-confirm-modal');
    $modal.removeClass('sentinel-modal-active');
    $('body').removeClass('modal-open');
    $(document).off('keydown.confirm');

    setTimeout(() => {
      $modal.remove();
    }, 300);
  }

})(jQuery);
