import { jsx as ho } from "@emotion/react/jsx-runtime";
import { createContext as po, useState as b, useEffect as x, useMemo as yo } from "react";
import { useFirstRender as Vo } from "@m4l/graphics";
import { getComponentClasses as Ro } from "../../../../utils/getComponentSlotRoot.js";
import { DATAGRID_ROW_HEIGHTS as So, DATAGRID_ROW_HEADER_HEIGHTS as vo, DATAGRID_PREFIX_NAME as Ho } from "../../constants.js";
import { ControlNavigateSlots as xo, ColumnsConfigSlots as Do, TextEditorSlots as Eo, TableSlots as To, RowsCountSlots as bo, ActionsSlots as ko, DataGridSlots as Go } from "../../slots/DataGridEnum.js";
import { deepEqual as Ko } from "fast-equals";
import { useViewMode as Io } from "../../hooks/useViewMode/useViewMode.js";
import { useRowHeight as Fo } from "../../hooks/useRowHeight/useRowHeight.js";
import { useColumnsWidth as $o } from "../../hooks/useColumnsWidth/useColumnsWidth.js";
import { getColumnsWidth as k } from "../../helpers/persistence/getColumnsWidth/getColumnsWidth.js";
import { useViewConfig as Ao } from "../../hooks/useViewConfig/useViewConfig.js";
import { useChangeColumnsConfig as Oo } from "../../hooks/useChangeColumnsConfig/useChangeColumnsConfig.js";
import { useChangeColumnsOrder as Wo } from "../../hooks/useChangeColumnsOrder/useChangeColumnsOrder.js";
import { getViewMode as G } from "../../helpers/persistence/getViewMode/getViewMode.js";
import { getInitialColumnsConfig as y } from "../../helpers/shared/getInitialColumnsConfig/getInitialColumnsConfig.js";
import { getAllViewModes as V } from "../../helpers/shared/getAllViewModes/getAllViewModes.js";
import { getViewSpecificConfig as K } from "../../helpers/shared/getViewSpecificConfig/getViewSpecificConfig.js";
const Mo = po(null);
function re(I) {
  const {
    id: r,
    children: F,
    columns: n,
    defaultConfig: $,
    onChangeConfig: A,
    defaultUserColumns: O,
    // deprecated
    onChangeUserColumns: W,
    // deprecated
    rows: M,
    rowsCount: z,
    rowActionsGetter: _,
    rowHeights: R = So,
    rowHeaderHeights: L = vo,
    initialRowHeightVariant: j = "standard",
    checkedRows: U,
    onCheckedRowsChange: q,
    checkedRowsMultiple: N,
    rowKeyGetter: P,
    externalSortSettings: h,
    externalFilterSettings: p,
    size: X,
    viewMode: B,
    onViewModeChange: J,
    defaultViewMode: m,
    cardsViewConfig: s,
    listViewConfig: c,
    reorderable: Q = !0
  } = I, l = $ ?? O, g = A ?? W, D = Vo([n, r]), { viewModeState: Y, setViewModeState: E, handleViewModeChange: Z } = Io(
    {
      id: r,
      viewMode: B,
      defaultViewMode: m,
      onViewModeChange: J,
      onChangeConfig: g
    }
  ), { currentRowHeightVariant: S, setRowHeightVariant: oo } = Fo({
    rowHeights: R,
    rowHeaderHeights: L,
    initialRowHeightVariant: j
  }), { columnsWidths: eo, setColumnsWidths: no, onChangeColumnWidth: io } = $o({
    id: r,
    onChangeConfig: g,
    initialWidths: k(r, n, l)
  }), { getConfigColumns: d, updateConfigColumns: C } = Ao(), { onChangeColumnsConfig: T } = Oo({
    id: r,
    onChangeConfig: g,
    updateConfigColumns: C
  }), { onChangeColumnsOrder: to } = Wo({
    getConfigColumns: d,
    onChangeColumnsConfig: T
  }), ro = Ro(Ho, {
    ...Go,
    ...ko,
    ...bo,
    ...To,
    ...Eo,
    ...Do,
    ...xo
  }), [so, lo] = b(z), [ao, uo] = b([]);
  x(() => {
    const i = new Set(n.map((o) => o.key));
    if (m === "cards" && s === void 0)
      throw new Error(
        `DataGridProvider: When defaultViewMode="cards", you must provide cardsViewConfig.

        Valid example with columnsConfig:
          defaultViewMode="cards"
          cardsViewConfig={{
            columnsConfig: [
              { columnKey: 'name', showTitle: false },
              { columnKey: 'email', showTitle: true }
            ]
          }}

        Valid example with customRender:
          defaultViewMode="cards"
          cardsViewConfig={{
            customRender: {
              renderContent: (row) => <CustomCard row={row} />,
              minHeight: 200
            }
          }}`
      );
    if (m === "list" && c === void 0)
      throw new Error(
        `DataGridProvider: When defaultViewMode="list", you must provide listViewConfig.

        Valid example with columnsConfig:
          defaultViewMode="list"
          listViewConfig={{
            columnsConfig: [
              { columnKey: 'name', showTitle: true },
              { columnKey: 'email', showTitle: true }
            ]
          }}

        Valid example with customRender:
          defaultViewMode="list"
          listViewConfig={{
            customRender: {
              renderContent: (row) => <CustomRow row={row} />
            }
          }}`
      );
    if (h?.sortsColumns) {
      for (const o of h.sortsColumns)
        if (typeof o == "string") {
          if (!i.has(o))
            throw new Error(
              `DataGridProvider: Sorts incluye "${o}", pero no existe ninguna columna con key="${o}".`
            );
        } else if (!o.skipColumnValidation && !i.has(o.name))
          throw new Error(
            `DataGridProvider: Sorts incluye "${o.name}", pero no existe ninguna columna con key="${o.name}".`
          );
    }
    if (p?.filterColumns) {
      for (const o of p.filterColumns)
        if (!o.skipColumnValidation && !i.has(o.name))
          throw new Error(
            `DataGridProvider: Fields incluye "${o.name}", pero no existe ninguna columna con key="${o.name}".`
          );
    }
    if (s !== void 0) {
      const o = s.customRender !== void 0, e = s.columnsConfig !== void 0 && s.columnsConfig.length > 0;
      if (!o && !e)
        throw new Error(
          `DataGridProvider: cardsViewConfig.enabled=true requiere configurar al menos una de estas opciones:
          - cardsViewConfig.customRender (renderizado personalizado)
          - cardsViewConfig.columnsConfig (configuración de columnas con al menos 1 elemento)

          Configuración actual:
          - customRender: ${o ? "definido" : "undefined"}
          - columnsConfig: ${s.columnsConfig?.length || 0} columnas

          Ejemplo válido con columnsConfig:
            cardsViewConfig={{
              enabled: true,
              columnsConfig: [
                { columnKey: 'name', showTitle: false },
                { columnKey: 'email', showTitle: true }
              ]
            }}

          Ejemplo válido con customRender:
            cardsViewConfig={{
              enabled: true,
              customRender: {
                renderContent: (row) => <CustomCard row={row} />,
                minHeight: 200
              }
            }}
          `
        );
      if (e && s.columnsConfig) {
        for (const t of s.columnsConfig)
          if (!i.has(t.columnKey))
            throw new Error(
              `DataGridProvider: cardsViewConfig.columnsConfig incluye columnKey="${t.columnKey}", pero no existe ninguna columna con key="${t.columnKey}".`
            );
      }
    }
    if (c?.columnsConfig) {
      for (const o of c.columnsConfig)
        if (!i.has(o.columnKey))
          throw new Error(
            `DataGridProvider: listViewConfig.columnsConfig includes columnKey="${o.columnKey}", but no column with key="${o.columnKey}" exists.`
          );
    }
  }, [n, h, p, s, c, m]);
  const fo = yo(() => R, [R]);
  x(() => {
    if (D) {
      no(k(r, n, l)), E(
        G(r, l, m) ?? "table"
      ), E(
        G(r, l, m) ?? "table"
      ), C(
        "table",
        y(
          r,
          n,
          "table",
          l?.columnsConfig,
          { frozen: !1, grouped: !1, groupOrder: 0 },
          { originalFrozen: !1, originalGrouped: !1, originalGroupOrder: 0 }
        )
      );
      const i = (() => {
        if (l?.columnsConfigCards && l.columnsConfigCards.length > 0)
          return l.columnsConfigCards;
        if (s?.columnsConfig)
          return s.columnsConfig.map((o, e) => {
            const t = n.find(
              (u) => u.key === o.columnKey
            );
            return {
              key: o.columnKey,
              visible: t?.visible === void 0 ? !0 : t?.visible,
              index: e,
              showTitle: o.showTitle
            };
          });
      })();
      if (C(
        "cards",
        y(
          r,
          n,
          "cards",
          i,
          { showTitle: !1 },
          { originalShowTitle: !1 }
        )
      ), c) {
        const o = (() => {
          if (l?.columnsConfigList && l.columnsConfigList.length > 0)
            return l.columnsConfigList;
          if (c.columnsConfig)
            return c.columnsConfig.map((e, t) => {
              const u = n.find(
                (a) => a.key === e.columnKey
              );
              return {
                key: e.columnKey,
                visible: u?.visible === void 0 ? !0 : u?.visible,
                index: t,
                showTitle: e.showTitle
              };
            });
        })();
        C(
          "list",
          y(
            r,
            n,
            "list",
            o,
            { showTitle: !1 },
            { originalShowTitle: !1 }
          )
        );
      }
    }
  }, [l]), x(() => {
    if (!D) {
      const i = {
        table: [],
        cards: [],
        list: []
      };
      V().forEach((e) => {
        const t = d(e), u = [];
        for (let a = 0; a < t.length; a++) {
          const f = n.findIndex(
            (w) => w.key === t[a]?.key
          );
          if (f !== -1) {
            const w = n[f];
            u.push({
              ...t[a],
              originalIndex: f,
              // Propiedades específicas por vista dinámicamente
              ...K(e).dynamicOriginalProperty(
                t[a] || w
              ),
              originalVisible: w.visible ?? !0
            });
          }
        }
        i[e] = u;
      }), V().forEach((e) => {
        const t = i[e], u = new Set(
          d(e).map((f) => f.key)
        ), a = n.filter(
          (f) => !u.has(f.key)
        );
        if (a.length > 0) {
          const f = t.length, mo = y(
            r,
            a,
            e,
            void 0,
            e === "cards" || e === "list" ? { showTitle: !1 } : {
              frozen: !1,
              grouped: !1,
              groupOrder: 0
            },
            e === "cards" || e === "list" ? {
              originalShowTitle: !1
            } : {
              originalFrozen: !1,
              originalGrouped: !1,
              originalGroupOrder: 0
            }
          ).map((go, v) => {
            const Co = n.findIndex(
              (wo) => wo.key === a[v].key
            ), H = a[v];
            return {
              ...go,
              index: v + f,
              name: H.name,
              originalIndex: Co,
              originalVisible: H.visible ?? !0,
              // Propiedades específicas por vista dinámicamente
              ...K(e).dynamicOriginalProperty(
                H
              )
            };
          });
          i[e].push(...mo);
        }
      });
      let o = !1;
      if (V().forEach((e) => {
        Ko(
          d(e),
          i[e]
        ) || (o = !0);
      }), !o)
        return;
      V().forEach((e) => {
        C(e, i[e]);
      });
    }
  }, [n, r]);
  const co = (i) => {
    lo(i);
  };
  return /* @__PURE__ */ ho(
    Mo.Provider,
    {
      value: {
        getConfigColumns: d,
        onChangeColumnsConfig: T,
        columnsConfig: d("table"),
        columnsWidths: eo,
        rowsCount: so,
        currentRowHeightVariant: S.rowHVariant,
        currentRowHeight: S.rowHeight,
        currentRowHeaderHeight: S.rowHeaderHeight,
        rows: M,
        rowHeights: fo,
        checkedRows: U,
        reorderable: Q,
        onChangeColumnsOrder: to,
        onChangeColumnWidth: io,
        setRowsCount: co,
        rowActionsGetter: _,
        setRowHeightVariant: oo,
        onCheckedRowsChange: q,
        checkedRowsMultiple: N,
        rowKeyGetter: P,
        onChangeConfig: g,
        onChangeUserColumns: g,
        // deprecated alias
        sortColumns: ao,
        setSortColumns: uo,
        externalSortSettings: h,
        externalFilterSettings: p,
        classes: ro,
        size: X,
        viewMode: Y,
        onViewModeChange: Z,
        cardsViewConfig: s,
        listViewConfig: c
      },
      children: F
    }
  );
}
export {
  Mo as DataGridContext,
  re as DataGridProvider
};
