const L = (h, k) => {
  const v = (n) => {
    const t = [], e = (o) => {
      for (const r of o)
        if (r.children?.length)
          e(r.children);
        else {
          const i = r.width ? Math.round(r.width * 0.12) : 15;
          t.push({
            key: String(r.key),
            width: i,
            align: r.align
          });
        }
    };
    return e(n), t;
  }, E = (n) => {
    let t = 1;
    const e = (o, r) => {
      for (const i of o)
        i.children?.length && (t = Math.max(t, r + 1), e(i.children, r + 1));
    };
    return e(n, 1), t;
  }, x = (n) => {
    if (!n.children?.length) return 1;
    let t = 0;
    for (const e of n.children)
      t += x(e);
    return t;
  }, T = (n, t, e, o) => {
    const r = (a) => a.align ? a.align : a.children?.length ? "center" : "left", i = (a, f, m) => {
      let l = m;
      for (const c of a) {
        const s = o?.[c.key] ?? (typeof c.title == "string" ? c.title : ""), u = n.getCell(f, l);
        if (u.value = s, u.alignment = {
          vertical: "middle",
          horizontal: r(c)
        }, c.children?.length) {
          const d = x(c);
          d > 1 && n.mergeCells(
            f,
            l,
            f,
            l + d - 1
          ), i(c.children, f + 1, l), l += d;
        } else
          e > 1 && n.mergeCells(f, l, e, l), l += 1;
      }
    };
    i(t, 1, 1);
  }, C = async (n) => {
    const t = await import("exceljs").catch(() => {
      throw new Error(
        `[AgGrid] exportToExcel requires exceljs.
Run: npm install exceljs`
      );
    }), e = typeof n == "string" ? { fileName: n } : n, o = new t.Workbook(), r = o.addWorksheet(e.sheetName ?? "Sheet1"), i = v(h.value), a = E(h.value);
    r.columns = i.map((s) => ({
      key: s.key,
      width: s.width,
      alignment: {
        vertical: "middle",
        horizontal: s.align || "left"
      }
    })), T(r, h.value, a, e.titleMap), k.value.forEach((s) => {
      const u = {};
      i.forEach((d) => {
        const g = y(h.value, d.key), p = w(s, g?.dataIndex);
        g?.renderText ? u[d.key] = g.renderText({
          value: p,
          text: p,
          record: s,
          column: g
        }) : u[d.key] = p;
      }), r.addRow(u);
    });
    const f = await o.xlsx.writeBuffer(), m = new Blob([f], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    }), l = URL.createObjectURL(m), c = document.createElement("a");
    c.href = l, c.download = e.fileName, c.click(), URL.revokeObjectURL(l);
  }, y = (n, t) => {
    for (const e of n) {
      if (e.key === t)
        return e;
      if (e.children) {
        const o = y(e.children, t);
        if (o) return o;
      }
    }
  }, w = (n, t = []) => {
    const e = Array.isArray(t) ? t : [t];
    let o = n;
    for (const r of e) {
      if (o == null) return;
      o = o[r];
    }
    return o;
  };
  return { exportToExcel: C };
};
export {
  L as useExportToExcel
};
