// Lazy-loaded collapsible file tree on overlay detail pages.
//
// One delegated click handler on document. Each `.file-tree-toggle` button
// carries `data-files-url`. First expand fires a fetch and innerHTMLs the
// returned partial into the next `.file-tree-children`; subsequent clicks
// just toggle visibility — no re-fetch.
//
// Children-div lookup goes through the row's <li> rather than the button's
// nextElementSibling so the files-overlay variant — where a per-row action
// column sits between the toggle button and the children div — works too.
(function () {
  document.addEventListener("click", function (event) {
    const button = event.target.closest(".file-tree-toggle");
    if (!button) return;

    const row = button.closest(".file-tree-row");
    const children = row ? row.querySelector(":scope > .file-tree-children") : null;
    if (!children) return;

    const wasExpanded = button.getAttribute("aria-expanded") === "true";
    button.setAttribute("aria-expanded", wasExpanded ? "false" : "true");
    children.hidden = wasExpanded;

    if (wasExpanded) return; // collapsing — nothing to fetch
    if (button.dataset.loaded === "1") return; // already populated
    const url = button.dataset.filesUrl;
    if (!url) return;

    button.dataset.loaded = "1"; // optimistic — prevents duplicate fetches on rapid clicks
    fetch(url, { headers: { Accept: "text/html" }, credentials: "same-origin" })
      .then(function (response) {
        if (!response.ok) throw new Error("HTTP " + response.status);
        return response.text();
      })
      .then(function (html) {
        children.innerHTML = html;
      })
      .catch(function (err) {
        delete button.dataset.loaded; // allow retry
        children.innerHTML =
          '<p class="muted">Failed to load directory contents.</p>';
        console.error("file-tree:", err);
      });
  });
})();
