function isElementVisible(element) {
  if (!(element instanceof Element)) return false;
  if (element instanceof HTMLOptionElement) {
    const select = element.closest("select");
    return select ? isElementVisible(select) : false;
  }
  const style = window.getComputedStyle(element);
  const rect = element.getBoundingClientRect();
  return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0" && rect.width > 0 && rect.height > 0;
}

export function collectUiAuditSnapshot(root = document) {
  const normalize = (value) => String(value || "").trim().replace(/\s+/g, " ");
  const tables = Array.from(root.querySelectorAll("table")).map((table, index) => {
    const rect = table.getBoundingClientRect();
    const wrap = table.closest(".table-wrap, .drawer-data-table-wrap, .finance-sheet-wrap") || table.parentElement;
    const wrapRect = wrap?.getBoundingClientRect();
    return {
      index,
      width: Math.round(rect.width),
      wrapWidth: Math.round(wrapRect?.width || rect.width),
      hasRawSortText: Array.from(table.querySelectorAll("th")).some((th) => normalize(th.textContent).includes("↕")),
      headerCount: table.querySelectorAll("th").length
    };
  });

  const visibleEnglishStatuses = Array.from(root.querySelectorAll("td, option, span, button"))
    .filter((element) => isElementVisible(element))
    .map((element) => normalize(element.textContent))
    .filter((text) => /\b(ACTIVE|INACTIVE|PENDING|LOCKED|OPEN|CLOSED|DONE|PASS|REJECT|SETTLED)\b/.test(text));

  const longHelperBlocks = Array.from(root.querySelectorAll("small, .workflow-tip, .feedback-banner"))
    .map((element) => normalize(element.textContent))
    .filter((text) => text.length > 48);

  return {
    path: window.location.pathname,
    viewport: { width: window.innerWidth, height: window.innerHeight },
    tables,
    visibleEnglishStatuses,
    longHelperBlocks
  };
}

export function printUiAuditSnapshot(root = document) {
  const snapshot = collectUiAuditSnapshot(root);
  console.table(snapshot.tables);
  console.log("visibleEnglishStatuses", snapshot.visibleEnglishStatuses);
  console.log("longHelperBlocks", snapshot.longHelperBlocks);
  return snapshot;
}
