import {
  fail
} from "../chunk-ZPT2ZR5B.js";

// src/utils/rtlUtils.tsx
import {
  blur as _blur,
  change as _change,
  click as _click,
  clickAndWait as _clickAndWait,
  focus as _focus,
  input as _input,
  type as _type,
  typeAndWait as _typeAndWait,
  wait as _wait,
  allowAndWaitForAsyncBehavior
} from "@homebound/rtl-utils";
import { prettyDOM } from "@testing-library/react";
function cell(r, row2, column) {
  return cellOf(r, "gridTable", row2, column);
}
function cellOf(r, tableTestId, rowNum, column) {
  return row(r, rowNum, tableTestId).childNodes[column];
}
function cellAnd(r, row2, column, testId) {
  return cell(r, row2, column).querySelector(`[data-testid="${testId}"]`) || fail(`Element not found ${prettyDOM(cell(r, row2, column))}`);
}
function row(r, row2, tableTestId = "gridTable") {
  const dataRows = Array.from(r.getByTestId(tableTestId).querySelectorAll("[data-gridrow]"));
  return dataRows[row2];
}
function rowAnd(r, rowNum, testId) {
  const e = row(r, rowNum);
  return e.querySelector(`[data-testid="${testId}"]`) || fail(`Element not found ${prettyDOM(e)}`);
}
function tableSnapshot(r, columnNames = [], tableTestId = "gridTable") {
  const tableEl = r.getByTestId(tableTestId);
  const dataRows = Array.from(tableEl.querySelectorAll("[data-gridrow]"));
  const hasExpandableHeader = !!tableEl.querySelector(`[data-testid="expandableColumn"]`);
  let tableDataAsStrings = dataRows.map((row2) => {
    return Array.from(row2.childNodes).map(getTextFromTableCellNode);
  });
  if (columnNames.length > 0) {
    const headerCells = tableDataAsStrings[0];
    if (headerCells) {
      const columnIndices = columnNames.map((name) => {
        const i = headerCells.indexOf(name);
        if (i === -1) throw new Error(`Could not find header '${name}' in ${headerCells.join(", ")}`);
        return i;
      });
      tableDataAsStrings = tableDataAsStrings.map((row2) => columnIndices.map((index) => row2[index]));
    }
  }
  return toMarkupTableString(tableDataAsStrings, hasExpandableHeader);
}
function toMarkupTableString(tableRows, hasExpandableHeader) {
  const columnWidths = tableRows.reduce((acc, row2) => {
    row2.forEach((cell2, columnIndex) => {
      const cellWidth = cell2?.length ?? 0;
      const currentMaxWidth = acc.get(columnIndex) ?? 0;
      if (cellWidth > currentMaxWidth || !currentMaxWidth) acc.set(columnIndex, cellWidth);
    });
    return acc;
  }, /* @__PURE__ */ new Map());
  const wrapTableRowEnds = (str) => `| ${str} |`;
  const rowsWithPaddingAndDividers = tableRows.map((tableCells) => {
    const formattedRow = tableCells.map((cell2, columnIndex) => {
      const cellWidth = columnWidths.get(columnIndex) ?? 0;
      return cell2?.padEnd(cellWidth, " ") || "";
    }).join(" | ");
    return wrapTableRowEnds(formattedRow);
  });
  const headerDivider = Array.from(columnWidths.values()).map((width) => "-".repeat(width) ?? "").join(" | ");
  const headerDividerRowNumber = hasExpandableHeader ? 2 : 1;
  rowsWithPaddingAndDividers.splice(headerDividerRowNumber, 0, wrapTableRowEnds(headerDivider));
  return `
${rowsWithPaddingAndDividers.join("\n")}
`;
}
function getTextFromTableCellNode(node) {
  if (node.nodeType === Node.ELEMENT_NODE) {
    const element = node;
    const maybeInput = element.getElementsByTagName("input")[0];
    if (maybeInput) return maybeInput.value;
    const maybeTextarea = element.getElementsByTagName("textarea")[0];
    if (maybeTextarea) return maybeTextarea.value;
    const maybeSelect = element.getElementsByTagName("select")[0];
    if (maybeSelect) return maybeSelect.value;
  }
  return node.textContent;
}
function select(select2, value) {
  assertListBoxInput(select2);
  ensureListBoxOpen(select2);
  const optionValues = Array.isArray(value) ? value : [value];
  optionValues.forEach((optionValue) => selectOption(select2, optionValue));
}
async function selectAndWait(select2, value) {
  await allowAndWaitForAsyncBehavior(() => ensureListBoxOpen(select2));
  return allowAndWaitForAsyncBehavior(() => {
    const optionValues = Array.isArray(value) ? value : [value];
    optionValues.forEach((optionValue) => selectOption(select2, optionValue));
  });
}
function ensureListBoxOpen(select2) {
  const expanded = select2.getAttribute("aria-expanded") === "true";
  if (!expanded) {
    _click(select2);
  }
}
function selectOption(select2, optionValue) {
  const listbox = findListBox(select2);
  const options = listbox.querySelectorAll("[role=option]");
  const optionToSelect = Array.from(options).find(
    (o) => o.dataset.key === optionValue || o.dataset.label === optionValue
  );
  if (!optionToSelect) {
    throw new Error(`Could not find option with value or text content of ${optionValue}`);
  }
  if (optionToSelect.getAttribute("aria-disabled")) {
    throw new Error(`Cannot select disabled option ${optionValue}`);
  }
  _click(optionToSelect);
}
function getSelected(select2) {
  if (isSelectElement(select2)) {
    throw new Error("Beam getSelected helper does not support <select> elements");
  }
  if (!isInputOrTextAreaElement(select2) && select2.dataset.readonly === "true") {
    return select2.textContent ?? void 0;
  }
  ensureListBoxOpen(select2);
  const listbox = findListBox(select2);
  const options = listbox.querySelectorAll("[role=option]");
  const selections = Array.from(options).filter((o) => o.getAttribute("aria-selected") === "true").map((o) => o.dataset.label ?? o.dataset.key ?? "").filter((o) => !!o);
  return selections.length > 0 ? selections.length > 1 ? selections : selections[0] : void 0;
}
function getOptions(select2) {
  assertListBoxInput(select2);
  ensureListBoxOpen(select2);
  const listbox = findListBox(select2);
  const options = listbox.querySelectorAll("[role=option]");
  return Array.from(options).map((o) => o.dataset.label ?? o.dataset.key ?? "").filter((o) => !!o);
}
function findListBox(select2) {
  if (select2.tagName === "DIV") fail("SelectField is readOnly");
  const listboxId = select2.getAttribute("aria-controls") || fail("aria-controls attribute not found, the SelectField is probably readOnly");
  return document.getElementById(listboxId) || fail("listbox not found");
}
function assertListBoxInput(select2) {
  if (isSelectElement(select2)) {
    throw new Error("Beam getOptions helper does not support <select> elements");
  }
  if (!isInputOrTextAreaElement(select2)) {
    throw new Error(
      `Expected element to be INPUT or TEXTAREA, but got ${select2.nodeName}. This field may be read-only. In that case we cannot get the list of options`
    );
  }
  return true;
}
function isSelectElement(element) {
  return element.nodeName === "SELECT";
}
function isInputOrTextAreaElement(element) {
  return element.nodeName === "INPUT" || element.nodeName === "TEXTAREA";
}
export {
  _blur as blur,
  cell,
  cellAnd,
  cellOf,
  _change as change,
  _click as click,
  _clickAndWait as clickAndWait,
  _focus as focus,
  getOptions,
  getSelected,
  _input as input,
  row,
  rowAnd,
  select,
  selectAndWait,
  tableSnapshot,
  _type as type,
  _typeAndWait as typeAndWait,
  _wait as wait
};
//# sourceMappingURL=rtlUtils.js.map