import React, { useContext, useMemo } from "react";
import { RicosContext, RicosNodeContextProvider } from "./../../ricos-context/index.js";
import { calculateBorderPadding } from "../borders/resolve-cell-borders.js";
import { TableBordersProvider } from "../borders/table-borders-context.js";
import { CELL_AUTO_MIN_WIDTH } from "../consts.js";
import { ROOT } from "../data-hooks.js";
import { TABLE_DEFAULTS, getMinColumnWidthForPadding, normalizePadding } from "../defaults.js";
import styles from "../statics/styles/table-viewer-scss.js";
function calculateTableColumnCount(cells) {
  if (!cells || cells.length === 0) {
    return 0;
  }
  return cells.reduce((sum, cell) => sum + (cell.tableCellData?.colspan || 1), 0);
}
function normalizeColumnWidths(colsMinWidths, colsRelativeWidths, paddingMinWidth) {
  const colsWithDefaults = colsRelativeWidths.map((originalWidth, i) => {
    const minWidth = Math.max(colsMinWidths[i] || CELL_AUTO_MIN_WIDTH, paddingMinWidth);
    const width = originalWidth < minWidth ? minWidth : originalWidth;
    return {
      width,
      minWidth
    };
  });
  const ratios = colsWithDefaults.map((c) => c.width / c.minWidth);
  const smallestRatio = Math.min(...ratios);
  return colsWithDefaults.map(({ minWidth, width }) => ({
    minWidth,
    width: width / smallestRatio
  }));
}
const TABLE_VERTICAL_PADDING = 16;
const TableSections = ({ hasRowHeader, node, nodeIndex, RicosNodesRenderer }) => {
  const rows = node.nodes ?? [];
  const headerRowHasRowspan = hasRowHeader && rows[0]?.nodes?.some((cell) => (cell.tableCellData?.rowspan || 1) > 1);
  if (!hasRowHeader || headerRowHasRowspan || rows.length === 0) {
    return /* @__PURE__ */ React.createElement("tbody", null, /* @__PURE__ */ React.createElement(RicosNodeContextProvider, { parentNode: node, parentIndex: nodeIndex }, /* @__PURE__ */ React.createElement(RicosNodesRenderer, { nodes: rows })));
  }
  const headerRows = rows.slice(0, 1);
  const bodyRows = rows.slice(1);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement(RicosNodeContextProvider, { parentNode: node, parentIndex: nodeIndex }, /* @__PURE__ */ React.createElement(RicosNodesRenderer, { nodes: headerRows }))), bodyRows.length > 0 && /* @__PURE__ */ React.createElement("tbody", null, /* @__PURE__ */ React.createElement(RicosNodeContextProvider, { parentNode: node, parentIndex: nodeIndex }, /* @__PURE__ */ React.createElement(RicosNodesRenderer, { nodes: bodyRows }))));
};
const Table = ({
  node,
  nodeIndex,
  RicosNodesRenderer,
  NodeViewContainer
}) => {
  const borderPadding = useMemo(() => calculateBorderPadding(node), [node]);
  const { languageDir } = useContext(RicosContext);
  const isRTL = languageDir === "rtl";
  const { dimensions: { colsMinWidth = [], colsWidthRatio = [] } = {} } = node.tableData || {};
  const cellSpacing = node.tableData?.cellSpacing ?? 0;
  const cellPadding = normalizePadding(node.tableData?.cellPadding, [
    ...TABLE_DEFAULTS.cellPadding
  ]);
  const actualColumnCount = node.nodes ? Math.max(0, ...node.nodes.map((row) => calculateTableColumnCount(row.nodes))) : 0;
  const paddingMinWidth = getMinColumnWidthForPadding(node.tableData?.cellPadding);
  const colStyles = normalizeColumnWidths(colsMinWidth, colsWidthRatio, paddingMinWidth);
  const columnsToRender = Array.from({ length: actualColumnCount }, (_, index) => {
    if (index < colStyles.length) {
      return colStyles[index];
    }
    return {
      minWidth: paddingMinWidth,
      width: paddingMinWidth
    };
  });
  const viewportStyle = {
    "--table-border-top": `${borderPadding.top}px`,
    "--table-border-bottom": `${borderPadding.bottom}px`,
    "--table-border-start": `${borderPadding.start}px`,
    "--table-border-end": `${borderPadding.end}px`,
    "--table-vertical-padding": `${TABLE_VERTICAL_PADDING}px`,
    ...cellPadding && cellPadding.length > 0 ? {
      "--ricos-internal-table-cell-padding-top": `${cellPadding[0]}px`,
      "--ricos-internal-table-cell-padding-right": `${cellPadding[1] ?? cellPadding[0]}px`,
      "--ricos-internal-table-cell-padding-bottom": `${cellPadding[2] ?? cellPadding[0]}px`,
      "--ricos-internal-table-cell-padding-left": `${cellPadding[3] ?? cellPadding[1] ?? cellPadding[0]}px`
    } : {},
    "--ricos-internal-table-gap": `${cellSpacing}px`
  };
  const hasRowHeader = !!node.tableData?.rowHeader;
  const altText = node.tableData?.altText;
  return /* @__PURE__ */ React.createElement(NodeViewContainer, { node, nodeIndex }, /* @__PURE__ */ React.createElement(TableBordersProvider, { tableNode: node, isRTL }, /* @__PURE__ */ React.createElement("div", { className: styles.tableViewport, style: viewportStyle }, /* @__PURE__ */ React.createElement(
    "table",
    {
      className: styles.container,
      "data-hook": ROOT,
      "aria-label": altText || void 0,
      style: {
        borderSpacing: "0",
        borderCollapse: "separate"
      }
    },
    /* @__PURE__ */ React.createElement("colgroup", null, columnsToRender.map((colStyle, index) => {
      const width = index > 0 && cellSpacing > 0 ? colStyle.width + cellSpacing : colStyle.width;
      return /* @__PURE__ */ React.createElement("col", { key: index, style: { width, minWidth: colStyle.minWidth } });
    })),
    /* @__PURE__ */ React.createElement(
      TableSections,
      {
        hasRowHeader,
        node,
        nodeIndex,
        RicosNodesRenderer
      }
    )
  ))));
};
const TableRenderer = ({ node, ...props }) => {
  return /* @__PURE__ */ React.createElement("div", { className: styles.root, key: node.id }, /* @__PURE__ */ React.createElement(Table, { node, ...props }));
};
var table_default = TableRenderer;
export {
  table_default as default
};
//# sourceMappingURL=table.js.map
