/**
 * Sentinel Dashboard JavaScript
 *
 * Handles dashboard charts and interactive elements.
 */

document.addEventListener("DOMContentLoaded", function () {
  // Check if Chart.js is loaded
  if (typeof Chart === "undefined") {
    console.error("Chart.js is not loaded!");
    return;
  }

  // Check if data is available
  if (!window.sentinelDashboardData) {
    console.error("Dashboard data not available");
    return;
  }

  console.log("Dashboard data loaded:", window.sentinelDashboardData);

  // Initialize all charts
  initializeCharts();

  function initializeCharts() {
    // Activity Timeline Chart
    const activityCanvas = document.getElementById("activityChart");
    if (activityCanvas) {
      const activityData = window.sentinelDashboardData.activityData;
      if (activityData && activityData.length > 0) {
        const chart = new Chart(activityCanvas.getContext("2d"), {
          type: "line",
          data: {
            labels: activityData.map((item) => item.date),
            datasets: [
              {
                label: "Activity Count",
                data: activityData.map((item) => item.count),
                borderColor: "#0073aa",
                backgroundColor: "rgba(0, 115, 170, 0.1)",
                tension: 0.4,
                fill: true,
                pointBackgroundColor: "#0073aa",
                pointBorderColor: "#fff",
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                display: false,
              },
              tooltip: {
                backgroundColor: "rgba(0, 0, 0, 0.8)",
                titleColor: "#fff",
                bodyColor: "#fff",
                borderColor: "#0073aa",
                borderWidth: 1,
                cornerRadius: 6,
                displayColors: false,
              },
            },
            scales: {
              y: {
                beginAtZero: true,
                ticks: {
                  stepSize: 1,
                  color: "#666",
                  font: {
                    size: 11,
                  },
                },
                grid: {
                  color: "rgba(0, 0, 0, 0.1)",
                  drawBorder: false,
                },
              },
              x: {
                ticks: {
                  color: "#666",
                  font: {
                    size: 11,
                  },
                },
                grid: {
                  display: false,
                },
              },
            },
            interaction: {
              intersect: false,
              mode: "index",
            },
          },
        });
      }
    }

    // Event Distribution Chart
    const eventCanvas = document.getElementById("eventChart");
    if (eventCanvas) {
      const eventData = window.sentinelDashboardData.eventData;
      if (eventData && eventData.length > 0) {
        const chart = new Chart(eventCanvas.getContext("2d"), {
          type: "doughnut",
          data: {
            labels: eventData.map((item) => item.event_key),
            datasets: [
              {
                data: eventData.map((item) => item.count),
                backgroundColor: [
                  "#0073aa",
                  "#00a32a",
                  "#d63638",
                  "#f56e28",
                  "#8c8f94",
                  "#72aee6",
                  "#00ba9c",
                  "#dba617",
                  "#385df6",
                  "#e65054",
                ],
                borderWidth: 2,
                borderColor: "#fff",
                hoverBorderWidth: 3,
                hoverBorderColor: "#fff",
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: "bottom",
                labels: {
                  boxWidth: 10,
                  padding: 8,
                  usePointStyle: true,
                  pointStyle: "circle",
                  color: "#666",
                  font: {
                    size: 11,
                  },
                },
              },
              tooltip: {
                backgroundColor: "rgba(0, 0, 0, 0.8)",
                titleColor: "#fff",
                bodyColor: "#fff",
                borderColor: "#0073aa",
                borderWidth: 1,
                cornerRadius: 6,
                callbacks: {
                  label: function (context) {
                    const label = context.label || "";
                    const value = context.raw;
                    const total = context.dataset.data.reduce(
                      (a, b) => a + b,
                      0
                    );
                    const percentage =
                      total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                    return `${label}: ${value} (${percentage}%)`;
                  },
                },
              },
            },
            cutout: "60%",
          },
        });
      }
    }

    // Recent Errors Chart
    const errorCanvas = document.getElementById("errorChart");
    if (errorCanvas) {
      const errorData = window.sentinelDashboardData.errorData;
      if (errorData && errorData.length > 0) {
        const chart = new Chart(errorCanvas.getContext("2d"), {
          type: "pie",
          data: {
            labels: errorData.map((item) => item.event_key),
            datasets: [
              {
                data: errorData.map((item) => item.count),
                backgroundColor: [
                  "#d63638",
                  "#f56e28",
                  "#8c8f94",
                  "#385df6",
                  "#e65054",
                  "#0073aa",
                  "#00a32a",
                  "#dba617",
                  "#00ba9c",
                  "#72aee6",
                ],
                borderWidth: 2,
                borderColor: "#fff",
                hoverBorderWidth: 3,
                hoverBorderColor: "#fff",
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: "bottom",
                labels: {
                  boxWidth: 10,
                  padding: 8,
                  usePointStyle: true,
                  pointStyle: "circle",
                  color: "#666",
                  font: {
                    size: 11,
                  },
                },
              },
              tooltip: {
                backgroundColor: "rgba(0, 0, 0, 0.8)",
                titleColor: "#fff",
                bodyColor: "#fff",
                borderColor: "#d63638",
                borderWidth: 1,
                cornerRadius: 6,
                callbacks: {
                  label: function (context) {
                    const label = context.label || "";
                    const value = context.raw;
                    const total = context.dataset.data.reduce(
                      (a, b) => a + b,
                      0
                    );
                    const percentage =
                      total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                    return `${label}: ${value} (${percentage}%)`;
                  },
                },
              },
            },
          },
        });
      }
    }

    // Custom Hourly Activity Heatmap
    const matrixCanvas = document.getElementById("activityHeatmap");
    if (matrixCanvas) {
      const heatmapData = window.sentinelDashboardData.heatmapData;
      if (heatmapData && heatmapData.length > 0) {
        console.log("Creating custom heatmap with data:", heatmapData);

        // Get the chart container (parent of canvas)
        const container = matrixCanvas.parentElement;

        // Preserve the title
        const title = container.querySelector("h3");

        // Clear container but preserve title
        container.innerHTML = "";
        if (title) {
          container.appendChild(title);
        }

        // Create heatmap container
        const heatmapDiv = document.createElement("div");
        heatmapDiv.className = "sentinel-heatmap";

        // Add hour labels (top row)
        const emptyCorner = document.createElement("div");
        emptyCorner.className = "sentinel-heatmap-label";
        heatmapDiv.appendChild(emptyCorner);

        for (let hour = 0; hour < 24; hour++) {
          const hourLabel = document.createElement("div");
          hourLabel.className = "sentinel-heatmap-label";
          hourLabel.textContent = hour % 4 === 0 ? hour + "h" : "";
          heatmapDiv.appendChild(hourLabel);
        }

        // Add day rows
        heatmapData.forEach((dayData, dayIndex) => {
          // Day label
          const dayLabel = document.createElement("div");
          dayLabel.className = "sentinel-heatmap-label";
          dayLabel.textContent = dayData.date.substring(5); // MM-DD format
          heatmapDiv.appendChild(dayLabel);

          // Hour cells
          dayData.hours.forEach((count, hour) => {
            const cell = document.createElement("div");
            cell.className = "sentinel-heatmap-cell";
            cell.style.backgroundColor = getHeatmapColor(count);

            // Add hover effect and tooltip
            cell.addEventListener("mouseenter", function () {
              // Clear any existing tooltips first
              const existingTooltips = heatmapDiv.querySelectorAll(
                ".sentinel-heatmap-tooltip"
              );
              existingTooltips.forEach((tooltip) => {
                tooltip.remove();
              });

              // Create tooltip
              const tooltip = document.createElement("div");
              tooltip.className = "sentinel-heatmap-tooltip";
              tooltip.textContent = `${dayData.date} at ${hour
                .toString()
                .padStart(2, "0")}:00 - ${count} events`;
              this.appendChild(tooltip);

              // Trigger fade-in animation
              setTimeout(() => {
                if (tooltip.parentNode) {
                  tooltip.classList.add("show");
                }
              }, 10);
            });

            cell.addEventListener("mouseleave", function () {
              // Remove tooltip with fade-out
              const tooltip = this.querySelector(".sentinel-heatmap-tooltip");
              if (tooltip) {
                tooltip.classList.remove("show");
                setTimeout(() => {
                  if (tooltip && tooltip.parentNode) {
                    tooltip.remove();
                  }
                }, 300); // Match CSS transition duration
              }
            });

            heatmapDiv.appendChild(cell);
          });
        });

        container.appendChild(heatmapDiv);

        // Add global cleanup for any stray tooltips
        heatmapDiv.addEventListener("mouseleave", function () {
          // Clean up any remaining tooltips when mouse leaves the heatmap
          setTimeout(() => {
            const strayTooltips = heatmapDiv.querySelectorAll(
              ".sentinel-heatmap-tooltip"
            );
            strayTooltips.forEach((tooltip) => {
              tooltip.remove();
            });
          }, 50);
        });

        // GitHub-style color function
        function getHeatmapColor(value) {
          if (value === 0) return "#ebedf0";
          if (value <= 2) return "#9be9a8";
          if (value <= 5) return "#40c463";
          if (value <= 10) return "#30a14e";
          return "#216e39";
        }

        console.log("Custom heatmap created successfully");
      } else {
        console.log("No heatmap data available");
      }
    }
  }

  // Activity feed interactions
  const activityItems = document.querySelectorAll(".sentinel-activity-item");
  activityItems.forEach((item) => {
    item.addEventListener("click", function () {
      // Add subtle hover effect
      this.style.backgroundColor = "#f8f9fa";
      setTimeout(() => {
        this.style.backgroundColor = "";
      }, 200);
    });
  });

  // Chart container hover effects
  const chartContainers = document.querySelectorAll(
    ".sentinel-chart-container"
  );
  chartContainers.forEach((container) => {
    container.addEventListener("mouseenter", function () {
      this.style.transform = "translateY(-2px)";
      this.style.boxShadow = "0 4px 16px rgba(0,0,0,0.10)";
    });

    container.addEventListener("mouseleave", function () {
      this.style.transform = "translateY(0)";
      this.style.boxShadow = "0 2px 8px rgba(0,0,0,0.06)";
    });
  });

  // Performance Monitor Modal Functionality
  function initializePerformanceModals() {
    // Use jQuery if available, otherwise use vanilla JS
    const $ = window.jQuery;

    if ($) {
      const modalOverlay = $("#sentinel-modal-overlay");
      const modalTitle = $("#sentinel-modal-title");
      const modalContent = $("#sentinel-modal-content");
      const closeButton = $("#sentinel-modal-close");

      // Monitor card click handlers (only for enabled cards)
      const jqueryCards = $(".sentinel-monitor-card.enabled");

      jqueryCards.on("click", function () {
        const monitorType = $(this).data("monitor");
        openPerformanceModal(monitorType);
      });

      // Close modal handlers
      closeButton.on("click", closePerformanceModal);

      modalOverlay.on("click", function (e) {
        if (e.target === this) {
          closePerformanceModal();
        }
      });

      // ESC key handler
      $(document).on("keydown", function (e) {
        if (e.key === "Escape" && modalOverlay.hasClass("active")) {
          closePerformanceModal();
        }
      });

      function openPerformanceModal(monitorType) {
        // Set modal title and show loading
        const titles = {
          "rate-limiting": "Rate Limiting Status",
          "memory-insights": "Memory Insights & Optimization",
          "performance-status": "Performance Status",
        };

        modalTitle.text(titles[monitorType] || "Monitor Details");

        // Show loading state
        modalContent.html(`
                    <div class="sentinel-modal-loading">
                        <div class="sentinel-loading-spinner"></div>
                        <p>Loading monitor data...</p>
                    </div>
                `);

        // Show modal with animation
        modalOverlay.addClass("active");
        $("body").addClass("modal-open");

        // Load monitor content
        loadMonitorContent(monitorType);
      }

      function closePerformanceModal() {
        modalOverlay.removeClass("active");
        $("body").removeClass("modal-open");

        // Clear content after animation
        setTimeout(() => {
          modalContent.html(`
                        <div class="sentinel-modal-loading">
                            <div class="sentinel-loading-spinner"></div>
                            <p>Loading monitor data...</p>
                        </div>
                    `);
        }, 300);
      }

      function loadMonitorContent(monitorType) {
        // Simulate loading delay for better UX
        setTimeout(() => {
          const content = getMonitorContent(monitorType);
          modalContent.html(content);
        }, 500);
      }

      function getMonitorContent(monitorType) {
        // Get the content from hidden divs that contain the real PHP-generated data
        const contentId = monitorType + "-modal-content";
        let hiddenContent = document.getElementById(contentId);

        if (hiddenContent && hiddenContent.innerHTML.trim().length > 0) {
          return hiddenContent.innerHTML;
        }
        return `
                    <div style="text-align: center; padding: 40px 20px;">
                        <h4>Monitor Not Available</h4>
                        <p>The requested monitor content could not be loaded. The monitor may be disabled in settings.</p>
                    </div>
                `;
      }
    } else {
      // Vanilla JS fallback if jQuery is not available
      console.log("jQuery not available, using vanilla JS fallback");

      const modalOverlay = document.getElementById("sentinel-modal-overlay");
      const modalTitle = document.getElementById("sentinel-modal-title");
      const modalContent = document.getElementById("sentinel-modal-content");
      const closeButton = document.getElementById("sentinel-modal-close");
      const monitorCards = document.querySelectorAll(
        ".sentinel-monitor-card.enabled"
      );

      if (modalOverlay && monitorCards.length > 0) {
        // Add click handlers to enabled monitor cards only
        monitorCards.forEach((card) => {
          card.addEventListener("click", function () {
            const monitorType = this.getAttribute("data-monitor");
            openPerformanceModalVanilla(monitorType);
          });
        });

        // Close button handler
        if (closeButton) {
          closeButton.addEventListener("click", closePerformanceModalVanilla);
        }

        // Backdrop click handler
        modalOverlay.addEventListener("click", function (e) {
          if (e.target === this) {
            closePerformanceModalVanilla();
          }
        });

        // ESC key handler
        document.addEventListener("keydown", function (e) {
          if (e.key === "Escape" && modalOverlay.classList.contains("active")) {
            closePerformanceModalVanilla();
          }
        });

        function openPerformanceModalVanilla(monitorType) {
          const titles = {
            "rate-limiting": "Rate Limiting Status",
            "memory-insights": "Memory Insights & Optimization",
            "performance-status": "Performance Status",
          };

          if (modalTitle) {
            modalTitle.textContent = titles[monitorType] || "Monitor Details";
          }

          // Show loading state
          if (modalContent) {
            modalContent.innerHTML = `
              <div class="sentinel-modal-loading">
                <div class="sentinel-loading-spinner"></div>
                <p>Loading monitor data...</p>
              </div>
            `;
          }

          // Show modal with animation
          modalOverlay.classList.add("active");
          document.body.classList.add("modal-open");

          // Load monitor content
          setTimeout(() => {
            loadMonitorContentVanilla(monitorType);
          }, 500);
        }

        function closePerformanceModalVanilla() {
          console.log("Closing modal");
          modalOverlay.classList.remove("active");
          document.body.classList.remove("modal-open");

          // Clear content after animation
          setTimeout(() => {
            if (modalContent) {
              modalContent.innerHTML = `
                <div class="sentinel-modal-loading">
                  <div class="sentinel-loading-spinner"></div>
                  <p>Loading monitor data...</p>
                </div>
              `;
            }
          }, 300);
        }

        function loadMonitorContentVanilla(monitorType) {
          const contentId = monitorType + "-modal-content";
          const hiddenContent = document.getElementById(contentId);

          console.log(
            "Loading content for:",
            monitorType,
            "Found content:",
            !!hiddenContent
          );

          let content;
          if (hiddenContent) {
            content = hiddenContent.innerHTML;
          } else {
            content = `
              <div style="text-align: center; padding: 40px 20px;">
                <h4>Monitor Not Available</h4>
                <p>The requested monitor content could not be loaded. The monitor may be disabled in settings.</p>
              </div>
            `;
          }

          if (modalContent) {
            modalContent.innerHTML = content;
          }
        }
      }
    }
  }

  // Initialize modal functionality if enabled monitor cards exist
  const monitorCards = document.querySelectorAll(
    ".sentinel-monitor-card.enabled"
  );

  if (monitorCards.length > 0) {
    initializePerformanceModals();
  }

  // Initialize tooltip functionality for disabled monitor cards
  initializeMonitorTooltips();

  function initializeMonitorTooltips() {
    const disabledCards = document.querySelectorAll(
      ".sentinel-monitor-card.disabled[data-tooltip]"
    );

    disabledCards.forEach((card) => {
      let tooltip = null;
      let hideTimeout = null;

      // Mouse enter handler
      card.addEventListener("mouseenter", function (e) {
        // Clear any existing timeouts
        if (hideTimeout) {
          clearTimeout(hideTimeout);
          hideTimeout = null;
        }

        // Show tooltip immediately for real-time cursor following
        showTooltip(this, e);
      });

      // Mouse move handler (update tooltip position as cursor moves)
      card.addEventListener("mousemove", function (e) {
        if (tooltip && tooltip.classList.contains("show")) {
          positionTooltipFromCursor(tooltip, e);
        }
      });

      // Mouse leave handler
      card.addEventListener("mouseleave", function (e) {
        // Hide tooltip with slight delay to prevent flickering
        hideTimeout = setTimeout(() => {
          hideTooltip();
        }, 100);
      });

      // Show tooltip function
      function showTooltip(element, mouseEvent) {
        const message = element.getAttribute("data-tooltip");
        if (!message) return;

        // Remove any existing tooltip
        hideTooltip();

        // Create tooltip element
        tooltip = document.createElement("div");
        tooltip.className = "sentinel-tooltip";
        tooltip.textContent = message;

        // Add to body
        document.body.appendChild(tooltip);

        // Position tooltip based on cursor position
        positionTooltipFromCursor(tooltip, mouseEvent);

        // Show with animation
        requestAnimationFrame(() => {
          tooltip.classList.add("show");
        });
      }

      // Hide tooltip function
      function hideTooltip() {
        if (tooltip) {
          tooltip.classList.remove("show");
          setTimeout(() => {
            if (tooltip && tooltip.parentNode) {
              tooltip.parentNode.removeChild(tooltip);
            }
            tooltip = null;
          }, 300); // Match CSS transition duration
        }
      }

      // Position tooltip function based on cursor position
      function positionTooltipFromCursor(tooltipEl, mouseEvent) {
        const tooltipRect = tooltipEl.getBoundingClientRect();
        const scrollTop =
          window.pageYOffset || document.documentElement.scrollTop;
        const scrollLeft =
          window.pageXOffset || document.documentElement.scrollLeft;

        // Get cursor position
        const cursorX = mouseEvent.clientX;
        const cursorY = mouseEvent.clientY;

        // Calculate initial position (below and centered on cursor)
        let top = cursorY + scrollTop + 15; // 15px gap below cursor
        let left = cursorX + scrollLeft - tooltipRect.width / 2;

        // Adjust for screen edges
        const padding = 20;
        const maxLeft = window.innerWidth - tooltipRect.width - padding;
        const minLeft = padding;

        left = Math.max(minLeft, Math.min(maxLeft, left));

        // Check if tooltip would go below viewport
        if (top + tooltipRect.height > window.innerHeight + scrollTop) {
          // Position above the cursor instead
          top = cursorY + scrollTop - tooltipRect.height - 15;
          tooltipEl.classList.add("tooltip-above");
        } else {
          // Remove tooltip-above class if it was previously added
          tooltipEl.classList.remove("tooltip-above");
        }

        // Ensure tooltip doesn't go above viewport
        if (top < scrollTop + padding) {
          top = cursorY + scrollTop + 15; // Fall back to below cursor
          tooltipEl.classList.remove("tooltip-above");
        }

        tooltipEl.style.top = top + "px";
        tooltipEl.style.left = left + "px";
      }
    });

    // Clean up any stray tooltips on page unload
    window.addEventListener("beforeunload", function () {
      const strayTooltips = document.querySelectorAll(".sentinel-tooltip");
      strayTooltips.forEach((tooltip) => {
        if (tooltip.parentNode) {
          tooltip.parentNode.removeChild(tooltip);
        }
      });
    });

    // Clean up tooltips on scroll (optional, for better UX)
    window.addEventListener("scroll", function () {
      const activeTooltips = document.querySelectorAll(
        ".sentinel-tooltip.show"
      );
      activeTooltips.forEach((tooltip) => {
        tooltip.classList.remove("show");
        setTimeout(() => {
          if (tooltip && tooltip.parentNode) {
            tooltip.parentNode.removeChild(tooltip);
          }
        }, 300);
      });
    });
  }

  // Simple API key button test
  (function ($) {
    $(document).ready(function () {
      console.log('Dashboard JS loaded');

      // Generate API Key button
      $('#generate-api-key').on('click', function () {
        alert('Generate API Key button clicked! JavaScript is working.');
      });

      // Regenerate API Key button
      $('#regenerate-api-key').on('click', function () {
        alert('Regenerate API Key button clicked! JavaScript is working.');
      });

      // Copy API Key button
      $('#copy-api-key').on('click', function () {
        alert('Copy API Key button clicked! JavaScript is working.');
      });
    });
  })(jQuery);
});

