<script>
  (function (JSON, Response) {
    const djDebug = document.getElementById("djDebug");
    function update(data) {
      if (data === null || !data.hasOwnProperty("debugToolbar")) return data;

      Object.entries(data.debugToolbar.panels).map(([id, panel]) => {
        if (panel.title) {
          const content = djDebug.querySelector(`#${id}`);

          content
            .querySelector(".djDebugPanelTitle")
            .querySelector("h3").textContent = panel.title;

          content.querySelector(".djdt-scroll").innerHTML = "";

          if (content.querySelector(".djdt-loader") === null) {
            const loader = document.createElement("div");
            loader.className = "djdt-loader";
            content.querySelector(".djDebugPanelContent").prepend(loader);
          }
        }
        if (panel.subtitle) {
          document
            .getElementById(`djdt-${id}`)
            .querySelector("small").textContent = panel.subtitle;
        }
      });
      djDebug.setAttribute("data-request-id", data.debugToolbar.requestId);

      delete data.debugToolbar;
      return data;
    }

    const origParse = JSON.parse;
    JSON.parse = function (text) {
      return update(origParse(text));
    };

    const origJson = Response.prototype.json
    Response.prototype.json = function () {
      return origJson.apply(this, arguments).then((data) => update(data));
    };

  })(JSON, Response);
</script>
