(function nativeObservabilityCacheRuntimeRecordsBehavior(Drupal) {
  Drupal.behaviors.nativeObservabilityCacheRuntimeRecords = {
    attach(context) {
      const root = context.querySelector(".no-cache-records");
      if (!root || root.dataset.noCacheRecordsBound === "true") {
        return;
      }
      root.dataset.noCacheRecordsBound = "true";

      const searchInput = root.querySelector("[data-no-cache-record-search]");
      const rows = Array.from(
        root.querySelectorAll("[data-no-cache-record-row]"),
      );
      const resultsTarget = root.querySelector(
        "[data-no-cache-record-results]",
      );
      const pageStatusTarget = root.querySelector(
        "[data-no-cache-record-page-status]",
      );
      const prevButton = root.querySelector("[data-no-cache-record-prev]");
      const nextButton = root.querySelector("[data-no-cache-record-next]");

      const modal = root.querySelector("[data-no-cache-record-modal]");
      const closeButton = root.querySelector(
        "[data-no-cache-record-modal-close]",
      );
      const timeTarget = root.querySelector("[data-record-time]");
      const typeTarget = root.querySelector("[data-record-type]");
      const layerTarget = root.querySelector("[data-record-layer]");
      const methodTarget = root.querySelector("[data-record-method]");
      const contextTarget = root.querySelector("[data-record-context]");
      const statusTarget = root.querySelector("[data-record-status]");
      const payloadTarget = root.querySelector("[data-record-payload]");

      const pageSize = 10;
      let currentPage = 1;
      let filteredRows = [...rows];
      let lastActiveButton = null;

      function openModal(record, triggerButton) {
        if (!modal) {
          return;
        }

        lastActiveButton = triggerButton || null;

        timeTarget.textContent = record.time || "";
        typeTarget.textContent = record.event_type || "";
        layerTarget.textContent = record.cache_layer || "";
        methodTarget.textContent = record.method || "";
        contextTarget.textContent = record.context || "";
        statusTarget.textContent = record.status || "";
        payloadTarget.textContent = JSON.stringify(
          record.payload || {},
          null,
          2,
        );

        modal.hidden = false;
        modal.setAttribute("aria-hidden", "false");
        document.body.classList.add("no-cache-records-modal-open");
      }

      function closeModal() {
        if (!modal) {
          return;
        }

        modal.hidden = true;
        modal.setAttribute("aria-hidden", "true");
        document.body.classList.remove("no-cache-records-modal-open");

        if (lastActiveButton) {
          lastActiveButton.focus();
        }
      }

      function renderTable() {
        const totalRows = filteredRows.length;
        const totalPages = Math.max(1, Math.ceil(totalRows / pageSize));
        currentPage = Math.min(currentPage, totalPages);

        const start = (currentPage - 1) * pageSize;
        const end = start + pageSize;

        rows.forEach((row) => {
          row.hidden = true;
        });

        filteredRows.slice(start, end).forEach((row) => {
          row.hidden = false;
        });

        if (resultsTarget) {
          resultsTarget.textContent = Drupal.t("@count records", {
            "@count": totalRows,
          });
        }

        if (pageStatusTarget) {
          pageStatusTarget.textContent = Drupal.t("Page @current of @total", {
            "@current": currentPage,
            "@total": totalPages,
          });
        }

        if (prevButton) {
          prevButton.disabled = currentPage <= 1;
        }

        if (nextButton) {
          nextButton.disabled = currentPage >= totalPages;
        }
      }

      function applySearch() {
        const query = (searchInput?.value || "").trim().toLowerCase();

        filteredRows = rows.filter((row) => {
          const haystack = row.getAttribute("data-search-text") || "";
          return haystack.includes(query);
        });

        currentPage = 1;
        renderTable();
      }

      if (searchInput) {
        searchInput.addEventListener("input", applySearch);
      }

      if (prevButton) {
        prevButton.addEventListener("click", () => {
          if (currentPage > 1) {
            currentPage -= 1;
            renderTable();
          }
        });
      }

      if (nextButton) {
        nextButton.addEventListener("click", () => {
          const totalPages = Math.max(
            1,
            Math.ceil(filteredRows.length / pageSize),
          );
          if (currentPage < totalPages) {
            currentPage += 1;
            renderTable();
          }
        });
      }

      root
        .querySelectorAll("[data-no-cache-record-details]")
        .forEach((button) => {
          button.addEventListener("click", () => {
            let record = {};

            try {
              record = JSON.parse(button.getAttribute("data-record") || "{}");
            } catch (e) {
              record = {};
            }

            openModal(record, button);
          });
        });

      if (closeButton) {
        closeButton.addEventListener("click", closeModal);
      }

      if (modal) {
        modal.addEventListener("click", (event) => {
          if (event.target === modal) {
            closeModal();
          }
        });

        document.addEventListener("keydown", (event) => {
          if (event.key === "Escape" && !modal.hidden) {
            closeModal();
          }
        });
      }

      renderTable();
    },
  };
})(Drupal);
