/*
 * Sentinel WordPress Dashboard Memory Widget
 */
(function ($) {
  function renderInsights($container, insights) {
    if (!insights || (insights.message && !insights.top_memory_hogs)) {
      $container.html(
        "<p>" +
          (insights && insights.message
            ? insights.message
            : "No insights available yet.") +
          "</p>"
      );
      return;
    }

    var html = "";
    html += '<div class="sentinel-memory-summary">';
    if (typeof insights.high_memory_percentage !== "undefined") {
      var labelThreshold =
        typeof insights.threshold_percent !== "undefined"
          ? insights.threshold_percent + "% threshold"
          : "threshold";
      html +=
        "<p><strong>Above " +
        labelThreshold +
        ":</strong> " +
        insights.high_memory_percentage +
        "% (" +
        insights.high_memory_requests +
        "/" +
        insights.total_requests_analyzed +
        ")</p>";
    }
    html += "</div>";

    if (insights.top_memory_hogs && insights.top_memory_hogs.length) {
      html +=
        '<div class="sentinel-memory-hogs"><p><strong>Top memory hogs</strong></p><ul>';
      insights.top_memory_hogs.forEach(function (hog) {
        html +=
          "<li>" +
          (hog.operation || "operation") +
          " — " +
          (hog.memory_formatted || "") +
          "</li>";
      });
      html += "</ul></div>";
    }

    if (insights.recommendations && insights.recommendations.length) {
      html +=
        '<div class="sentinel-memory-recos"><p><strong>Recommendations</strong></p><ul>';
      insights.recommendations.forEach(function (rec) {
        html +=
          "<li>" +
          rec.title +
          (rec.description ? ": " + rec.description : "") +
          "</li>";
      });
      html += "</ul></div>";
    }

    $container.html(html);
  }

  function fetchInsights($container) {
    $container.html("<p>Loading insights…</p>");
    $.post(ajaxurl, {
      action: "sentinel_memory_insights",
      _ajax_nonce: "",
    })
      .done(function (response) {
        if (response && response.success) {
          renderInsights($container, response.data);
        } else {
          $container.html("<p>Could not load insights.</p>");
        }
      })
      .fail(function () {
        $container.html("<p>Could not load insights.</p>");
      });
  }

  $(function () {
    var $widget = $("#sentinel-memory-widget");
    if (!$widget.length) return;

    var $insights = $("#sentinel-memory-insights");
    fetchInsights($insights);

    $("#sentinel-memory-refresh").on("click", function () {
      fetchInsights($insights);
    });
  });
})(jQuery);
