/* minitrail viewer — client-side interactivity */

// Track state
const expandedSpans = new Set();
const collapsedNodes = new Set();
let currentViewMode = "pretty";

// --- Toggle span detail panel ---
function toggleDetail(spanId) {
  const detail = document.querySelector(`[data-detail="${spanId}"]`);
  const bar = document.querySelector(`[data-row-bar="${spanId}"]`);
  if (!detail) return;

  if (expandedSpans.has(spanId)) {
    expandedSpans.delete(spanId);
    detail.classList.add("hidden");
    if (bar) bar.classList.remove("bg-gray-50", "dark:bg-gray-900");
  } else {
    expandedSpans.add(spanId);
    detail.classList.remove("hidden");
    if (bar) bar.classList.add("bg-gray-50", "dark:bg-gray-900");
  }
}

// --- Toggle collapse/expand children ---
function toggleCollapse(spanId, event) {
  if (event) event.stopPropagation();

  const toggle = document.querySelector(`[data-collapse="${spanId}"]`);
  const row = document.querySelector(`[data-span-id="${spanId}"]`);
  if (!row) return;

  if (collapsedNodes.has(spanId)) {
    collapsedNodes.delete(spanId);
    if (toggle) toggle.innerHTML = "&#9660;"; // down arrow
  } else {
    collapsedNodes.add(spanId);
    if (toggle) toggle.innerHTML = "&#9654;"; // right arrow
  }

  updateChildVisibility();
}

function updateChildVisibility() {
  const rows = document.querySelectorAll(".span-row");
  // Build a map of span_id -> parent_span_id by reading data from span_rows_json
  // Instead, we use a simpler approach: walk the DOM and track ancestor collapse state

  // We need the parent info. Let's use the span_rows data embedded in the page.
  // Since we don't have parent info in DOM, we rely on depth + order.
  // Track which spans should be hidden because an ancestor is collapsed.

  const hidden = new Set();
  const depthStack = []; // stack of {spanId, depth, collapsed}

  rows.forEach(row => {
    const spanId = row.dataset.spanId;
    const bar = row.querySelector("[data-row-bar]");
    if (!bar) return;

    // Get depth from the first child div's padding
    const nameDiv = bar.querySelector(".shrink-0");
    if (!nameDiv) return;
    const pl = parseInt(nameDiv.style.paddingLeft) || 0;
    const depth = pl / 20;

    // Pop stack entries that are at same or deeper depth
    while (depthStack.length > 0 && depthStack[depthStack.length - 1].depth >= depth) {
      depthStack.pop();
    }

    // Check if any ancestor on the stack is collapsed
    const ancestorHidden = depthStack.some(e => e.collapsed);

    if (ancestorHidden) {
      row.classList.add("hidden");
    } else {
      row.classList.remove("hidden");
    }

    depthStack.push({
      spanId: spanId,
      depth: depth,
      collapsed: collapsedNodes.has(spanId),
    });
  });
}

// --- Pretty / Raw mode toggle ---
function setViewMode(mode) {
  currentViewMode = mode;
  const btnPretty = document.getElementById("btn-pretty");
  const btnRaw = document.getElementById("btn-raw");

  const activeClasses = "bg-blue-600 text-white border-blue-600";
  const inactiveClasses = "bg-white dark:bg-gray-900 text-gray-600 dark:text-gray-300 border-gray-300 dark:border-gray-700";

  if (mode === "pretty") {
    btnPretty.className = `px-3 py-1 text-xs font-medium rounded-l border ${activeClasses}`;
    btnRaw.className = `px-3 py-1 text-xs font-medium rounded-r border border-l-0 ${inactiveClasses}`;
  } else {
    btnPretty.className = `px-3 py-1 text-xs font-medium rounded-l border ${inactiveClasses}`;
    btnRaw.className = `px-3 py-1 text-xs font-medium rounded-r border border-l-0 ${activeClasses}`;
  }

  // Toggle content visibility in all detail panels
  document.querySelectorAll(".pretty-content").forEach(el => {
    el.classList.toggle("hidden", mode !== "pretty");
  });
  document.querySelectorAll(".raw-content").forEach(el => {
    el.classList.toggle("hidden", mode !== "raw");
  });
}

// --- Collapsible text toggle ---
function toggleCollapsibleText(btn) {
  const container = btn.closest(".collapsible-text");
  if (!container) return;
  const collapsed = container.dataset.collapsed === "true";
  const collapsiblePre = container.querySelector(".collapsible-pre");
  const fullPre = container.querySelector(".full-pre");

  if (collapsed) {
    container.dataset.collapsed = "false";
    btn.innerHTML = "&#9660; " + btn.textContent.trim().replace(/^[^\s]+\s/, "");
    if (collapsiblePre) collapsiblePre.classList.add("hidden");
    if (fullPre) fullPre.classList.remove("hidden");
  } else {
    container.dataset.collapsed = "true";
    btn.innerHTML = "&#9654; " + btn.textContent.trim().replace(/^[^\s]+\s/, "");
    if (collapsiblePre) collapsiblePre.classList.remove("hidden");
    if (fullPre) fullPre.classList.add("hidden");
  }
}
