import { ref as c, computed as f, watch as g } from "vue";
import { getStringKey as a, runPipelineHooks as C } from "../utils.mjs";
const w = (r) => {
  const o = c([]), i = c([]);
  function u(t = []) {
    return t.filter((e) => !e.hideInTable).map((e) => {
      if (e.children?.length) {
        const n = u(e.children);
        return n?.length ? {
          ...e,
          children: n
        } : null;
      }
      return e;
    }).filter(Boolean);
  }
  function d(t) {
    return o.value.find((e) => a(e.key) === t);
  }
  function l(t) {
    const e = [];
    for (const n of t)
      n.children?.length ? e.push(...l(n.children)) : e.push(a(n.key));
    return e.filter(Boolean);
  }
  const m = f(() => l(o.value));
  async function h(t, e) {
    return await C(
      r.plugins,
      t,
      (n) => n.beforeColumnsChange?.bind(n),
      e
    );
  }
  g(
    () => r.columns,
    async () => {
      const t = u(r.columns), e = await h(t, o.value);
      o.value = e, i.value = e, r.onShownColumnsChange?.(e);
    },
    {
      deep: !0,
      immediate: !0
    }
  );
  function s(t) {
    for (const e of t)
      if (e.children) {
        const n = s(e.children);
        if (n)
          return n;
      } else if (e.defaultSortOrder) {
        const n = e.field ?? e.dataIndex ?? e.key;
        return {
          colKey: e.key,
          field: n,
          order: e.defaultSortOrder
        };
      }
  }
  const y = f(() => s(u(r.columns)));
  return {
    columns: o,
    shownColumns: i,
    columnKeys: m,
    getTargetColumnByKey: d,
    defaultSortOrder: y,
    getColKeys: l
  };
};
export {
  w as useColumns
};
