/**
 * Sentinel Admin JavaScript
 *
 * General JavaScript for the Sentinel admin interface functionality.
 * Settings page functionality is handled separately by sentinel-settings.js
 */

(function ($) {
  "use strict";

  $(document).ready(function () {
    // General admin functionality that applies to all Sentinel pages

    // Auto-dismiss admin notices after 5 seconds
    $(".notice.is-dismissible").each(function () {
      var notice = $(this);
      setTimeout(function () {
        notice.fadeOut();
      }, 5000);
    });

    // Confirmation dialogs for destructive actions
    $(".sentinel-confirm-action").on("click", function (e) {
      var message =
        $(this).data("confirm") ||
        "Are you sure you want to perform this action?";
      if (!confirm(message)) {
        e.preventDefault();
        return false;
      }
    });

    // Loading states for async actions
    $(".sentinel-async-action").on("click", function () {
      var button = $(this);
      var originalText = button.text();

      button.text("Loading...").prop("disabled", true);

      // Re-enable after 30 seconds as a failsafe
      setTimeout(function () {
        button.text(originalText).prop("disabled", false);
      }, 30000);
    });

    // Copy to clipboard functionality
    $(".sentinel-copy-to-clipboard").on("click", function (e) {
      e.preventDefault();

      var target = $(this).data("target");
      var text = $(target).text() || $(target).val();

      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(function () {
          // Show temporary success message
          var button = $(e.target);
          var originalText = button.text();
          button.text("Copied!");
          setTimeout(function () {
            button.text(originalText);
          }, 2000);
        });
      }
    });

    // Toggle visibility for collapsible sections
    $(".sentinel-toggle-section").on("click", function (e) {
      e.preventDefault();

      var target = $(this).data("target");
      var section = $(target);
      var icon = $(this).find(".dashicons");

      section.slideToggle();

      // Toggle icon between down and up arrows
      if (icon.hasClass("dashicons-arrow-down")) {
        icon.removeClass("dashicons-arrow-down").addClass("dashicons-arrow-up");
      } else {
        icon.removeClass("dashicons-arrow-up").addClass("dashicons-arrow-down");
      }
    });
  });

  // BEGIN: Email Notification Settings Toggle Logic (with fade-in)
  jQuery(document).ready(function ($) {
    var mainToggle = document.getElementById(
      "sentinel_email_notifications_enabled"
    );
    var optionsDiv = document.getElementById(
      "sentinel_email_notification_options"
    );
    if (mainToggle && optionsDiv) {
      // Set initial state
      if (mainToggle.checked) {
        optionsDiv.classList.add("is-visible");
      } else {
        optionsDiv.classList.remove("is-visible");
      }
      mainToggle.addEventListener("change", function () {
        if (this.checked) {
          optionsDiv.classList.add("is-visible");
        } else {
          optionsDiv.classList.remove("is-visible");
        }
      });
    }
  });
  // END: Email Notification Settings Toggle Logic (with fade-in)

  // BEGIN: Security Controls Action Mode Toggle Logic
  $(document).ready(function () {
    // Action Mode Segmented Toggle
    var actionModeToggle = document.getElementById('action_mode_toggle');
    if (actionModeToggle) {
      var buttons = actionModeToggle.querySelectorAll('.sentinel-segmented-btn');
      var slider = actionModeToggle.querySelector('.slider');
      var hiddenInput = document.getElementById('action_mode');
      var descSpan = document.getElementById('action_mode_desc');

      var descriptions = {
        'observe': 'Log security incidents without taking any automated action',
        'throttle': 'Add delays to suspicious login attempts to slow down attacks',
        'block': 'Temporarily block attackers when thresholds are exceeded (recommended)'
      };

      buttons.forEach(function (btn, index) {
        btn.addEventListener('click', function () {
          var value = btn.getAttribute('data-value');

          // 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 and resize slider to match clicked button
          if (slider) {
            var btnRect = btn.getBoundingClientRect();
            var containerRect = actionModeToggle.getBoundingClientRect();

            // Calculate position relative to container
            var leftOffset = btnRect.left - containerRect.left - 4; // Subtract container padding
            var btnWidth = btnRect.width;

            slider.style.left = leftOffset + 'px';
            slider.style.width = btnWidth + 'px';
            slider.style.transform = 'none'; // Remove any transforms
          }

          // Update hidden input
          if (hiddenInput) {
            hiddenInput.value = value;
          }

          // Update description text
          if (descSpan) {
            descSpan.textContent = descriptions[value];
          }
        });
      });

      // Function to initialize slider position
      function initializeSliderPosition() {
        var activeBtn = actionModeToggle.querySelector('.sentinel-segmented-btn.active');
        if (activeBtn && slider) {
          // Small delay to ensure elements are fully rendered
          setTimeout(function () {
            var btnRect = activeBtn.getBoundingClientRect();
            var containerRect = actionModeToggle.getBoundingClientRect();

            // Only initialize if elements have actual dimensions
            if (btnRect.width > 0 && containerRect.width > 0) {
              var leftOffset = btnRect.left - containerRect.left - 4;
              var btnWidth = btnRect.width;

              slider.style.left = leftOffset + 'px';
              slider.style.width = btnWidth + 'px';
            }
          }, 50);
        }
      }

      // Initialize on page load
      initializeSliderPosition();

      // Re-initialize when tab becomes visible (for hidden tabs)
      var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
          if (mutation.type === 'attributes' &&
            mutation.attributeName === 'style' &&
            actionModeToggle.offsetParent !== null) {
            initializeSliderPosition();
          }
        });
      });

      // Observe the toggle container for visibility changes
      if (actionModeToggle.closest('.sentinel-tab-content')) {
        observer.observe(actionModeToggle.closest('.sentinel-tab-content'), {
          attributes: true,
          attributeFilter: ['style']
        });
      }
    }
  });
  // END: Security Controls Action Mode Toggle Logic

  // BEGIN: File Monitor Diff Viewer (Premium)
  $(document).on('click', '.sentinel-diff-btn', function (e) {
    e.preventDefault();

    const button = $(this);
    const baselineId = button.data('baseline-id');
    const filename = button.data('filename');

    if (!baselineId) {
      alert('Invalid baseline ID');
      return;
    }

    // Check if diff viewer already exists for this item
    const activityItem = button.closest('.sentinel-activity-item, .sentinel-log-card');
    let diffViewer = activityItem.find('.sentinel-diff-viewer');

    // If viewer exists, toggle it
    if (diffViewer.length > 0) {
      diffViewer.slideToggle();
      // Update button title for icon buttons, or text for text buttons
      if (button.find('i').length > 0) {
        button.attr('title', diffViewer.is(':visible') ? 'Hide Changes' : 'View Changes');
      } else {
        button.text(diffViewer.is(':visible') ? 'Hide Changes' : 'View Changes');
      }
      return;
    }

    // Show loading state
    button.prop('disabled', true);
    if (button.find('i').length > 0) {
      // Icon button - change the icon and title
      button.find('i').removeClass().addClass('dashicons dashicons-update-alt sentinel-spin');
      button.attr('title', 'Loading...');
    } else {
      // Text button
      button.text('Loading...');
    }

    // Fetch diff data via AJAX
    $.ajax({
      url: ajaxurl,
      method: 'POST',
      data: {
        action: 'sentinel_get_file_diff',
        baseline_id: baselineId,
        nonce: sentinel_admin_vars.nonce || ''
      },
      success: function (response) {
        if (response.success && response.data) {
          const data = response.data;

          // Create diff viewer HTML
          const diffHtml = `
            <div class="sentinel-diff-viewer" style="display: none;">
              <div class="sentinel-diff-header">
                <h4>Changes detected in ${data.filename}</h4>
                <p class="sentinel-diff-meta">
                  Detected: ${data.detected_at} |
                  Summary: ${data.summary}
                </p>
              </div>
              <div class="sentinel-diff-tabs">
                <button class="sentinel-diff-tab active" data-tab="unified">Unified Diff</button>
              </div>
              <div class="sentinel-diff-content">
                <div class="sentinel-diff-pane active" id="unified">
                  <pre class="sentinel-diff-code">${formatDiff(data.diff)}</pre>
                </div>
              </div>
            </div>
          `;

          // Insert diff viewer after the appropriate target
          let insertTarget;
          if (activityItem.hasClass('sentinel-activity-item')) {
            // Dashboard activity item
            insertTarget = activityItem.find('.sentinel-activity-content');
          } else {
            // Log card
            insertTarget = activityItem.find('.sentinel-log-header');
          }
          insertTarget.after(diffHtml);

          // Show the diff viewer
          activityItem.find('.sentinel-diff-viewer').slideDown();

          // Update button state
          if (button.find('i').length > 0) {
            button.attr('title', 'Hide Changes');
          } else {
            button.text('Hide Changes');
          }
        } else {
          alert('Failed to load diff data: ' + (response.data || 'Unknown error'));
        }
      },
      error: function () {
        alert('Failed to load diff data. Please try again.');
      },
      complete: function () {
        button.prop('disabled', false);

        // Reset button to original state
        if (button.find('i').length > 0) {
          // Icon button - reset icon and title
          const isSpinning = button.find('i').hasClass('sentinel-spin');
          if (isSpinning) {
            button.find('i').removeClass('dashicons-update-alt sentinel-spin').addClass('dashicons-editor-code');
            button.attr('title', 'View Changes');
          }
        } else {
          // Text button
          if (button.text() === 'Loading...') {
            button.text('View Changes');
          }
        }
      }
    });
  });

  // Tab switching for diff viewer
  $(document).on('click', '.sentinel-diff-tab', function () {
    const tab = $(this);
    const tabContainer = tab.closest('.sentinel-diff-tabs');
    const contentContainer = tabContainer.next('.sentinel-diff-content');
    const targetTab = tab.data('tab');

    // Switch active tab
    tabContainer.find('.sentinel-diff-tab').removeClass('active');
    tab.addClass('active');

    // Switch active content
    contentContainer.find('.sentinel-diff-pane').removeClass('active');
    contentContainer.find('#' + targetTab).addClass('active');
  });

  // Helper function to escape HTML
  function escapeHtml(text) {
    const map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function (m) { return map[m]; });
  }

  // Helper function to format diff with proper syntax highlighting
  function formatDiff(diffText) {
    if (!diffText) return '';

    const lines = diffText.split('\n');
    const formattedLines = lines.map(function (line, index) {
      const escapedLine = escapeHtml(line);

      if (line.startsWith('+++') || line.startsWith('---')) {
        return `<span class="diff-header">${escapedLine}</span>`;
      } else if (line.startsWith('+')) {
        return `<span class="diff-line-added">${escapedLine}</span>`;
      } else if (line.startsWith('-')) {
        return `<span class="diff-line-removed">${escapedLine}</span>`;
      } else if (line.startsWith('@@')) {
        return `<span class="diff-header">${escapedLine}</span>`;
      } else {
        return `<span class="diff-line-context">${escapedLine}</span>`;
      }
    });

    return formattedLines.join('\n');
  }
  // END: File Monitor Diff Viewer (Premium)

})(jQuery);
