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