import { jsx as n, jsxs as E, Fragment as se } from "react/jsx-runtime";
import { ab as gn, ac as de, ad as fn, ae as Ct, af as yn, ag as Le, ah as bn, ai as Cn, aj as vt, X as vn, Y as wn, ak as ke, al as En, _ as In, am as Tn, an as Sn, ao as Z, ap as Mn, aq as Dn, ar as kn, as as xn, at as pe, au as Vn, av as An, aw as Be, ax as wt, m as he, ay as ve, az as On, aA as _n, aB as Nn, aC as Rn, aD as Fn, aE as Pn, aF as $n, aG as Ln, aH as Oe, S as J, aI as Et, aJ as oe, aK as _e, z as I, aL as It, aM as jn, T as G, aN as zn, U as ge, aO as B, aP as Tt, V as $, aQ as Bn, aR as St, aS as Ie, aT as Ge, aU as Mt, aV as Gn, aW as Un, E as ie, aX as qn, aY as je, B as Hn, aZ as Wn, a_ as Qn, a$ as Dt, b0 as Kn, b1 as kt, b2 as tt, b3 as ye, b4 as Yn, b5 as Ne, v as ee, b6 as Jn, b7 as Xn, b8 as be, b9 as fe, ba as U, bb as ne, bc as ue, bd as me, be as Zn, q as Ue, o as qe, bf as Re, bg as He, bh as xt, bi as Vt, bj as We, bk as Me, A as De, bl as Q, bm as ae, bn as es, a1 as le, a2 as ts, bo as re, bp as Ce, e as ns, bq as xe, br as ss, bs as is, bt as rs, bu as nt, y as O, bv as At, bw as Ot, bx as st, I as it, by as Ve, bz as os, $ as rt, bA as ot, bB as as, bC as ls, bD as cs, bE as ds, bF as at, bG as us, bH as ms, bI as ps, bJ as te, bK as _t, bL as hs, bM as gs, bN as Nt, bO as lt, bP as fs, bQ as ys, bR as bs, bS as ct, bT as Cs, bU as vs, bV as ws, bW as Es, bX as Is, bY as Ts, bZ as Ss, b_ as Ms, b$ as Ds, c0 as ks, c1 as xs, c2 as Vs, c3 as As, c4 as Os, c5 as _s, c6 as Ns, c7 as Rs, c8 as Fs, c9 as Ps, ca as $s, cb as dt, cc as Ls, C as $e, cd as js } from "./index-Dmwc5xdZ.mjs";
import K, { forwardRef as zs, createContext as Bs, useContext as Gs, useCallback as D, useTransition as Qe, useState as q, Suspense as Us, lazy as qs, useMemo as x, useEffect as Ke, memo as W, useRef as ut } from "react";
import { c as Hs } from "./sqlRunnerSlice-DkRrUHqz.mjs";
import { T as Ws, I as Rt, P as Qs, W as Ks, a as Ys } from "./WarningsHoverCardContent-BU5ho7PT.mjs";
const Js = (e, t, i, r, s) => {
  const a = new yn(r), l = r.getFieldQuoteChar(), m = i.reduce((f, h) => (f[h.reference] = {
    name: h.reference,
    label: de(h.reference),
    type: h.type ?? Ct.STRING,
    table: e,
    fieldType: fn.DIMENSION,
    sql: `${l}${h.reference}${l}`,
    tableLabel: de(e),
    hidden: !1
  }, f), {}), c = {
    name: e,
    label: de(e),
    sqlTable: `(${t})`,
    // Wrap the sql in a subquery to avoid issues with reserved words
    dimensions: m,
    metrics: {},
    lineageGraph: { nodes: [], edges: [] },
    database: r.credentials.type,
    schema: ""
    // TODO: what should this be?
  };
  return {
    ...a.compileExplore({
      name: e,
      label: de(e),
      tags: [],
      baseTable: e,
      joinedTables: [],
      tables: { [e]: c },
      targetDatabase: r.getAdapterType(),
      meta: {}
    }),
    type: Le.VIRTUAL
  };
}, Xs = (e, t, i) => {
  const r = {
    credentials: {
      type: gn.BIGQUERY,
      project: "",
      dataset: "",
      timeoutSeconds: 0,
      priority: "interactive",
      keyfileContents: {},
      retries: 3,
      location: "",
      maximumBytesBilled: 0
    },
    getCatalog: async () => ({}),
    getAsyncQueryResults: async () => ({
      queryId: null,
      queryMetadata: null,
      totalRows: 0,
      durationMs: 0,
      fields: {},
      pageCount: 0,
      rows: []
    }),
    streamQuery: async () => {
    },
    executeAsyncQuery: async () => ({
      queryId: null,
      queryMetadata: null,
      totalRows: 0,
      durationMs: 0
    }),
    runQuery: async () => ({ fields: {}, rows: [] }),
    test: async () => {
    },
    getStartOfWeek: () => Cn.MONDAY,
    getAdapterType: () => bn.BIGQUERY,
    getStringQuoteChar: () => "'",
    getEscapeStringQuoteChar: () => "''",
    getFieldQuoteChar: () => '"',
    getFloatingType: () => "FLOAT",
    getMetricSql: () => "",
    concatString: (...s) => s.join(""),
    getAllTables: async () => [],
    getFields: async () => ({}),
    parseWarehouseCatalog: () => ({}),
    parseError: (s) => s,
    escapeString: (s) => s,
    castToTimestamp: (s) => `CAST('${s.toISOString()}' AS TIMESTAMP)`,
    getIntervalSql: (s, a) => `INTERVAL '${s} ${a}'`,
    getTimestampDiffSeconds: (s, a) => `EXTRACT(EPOCH FROM (${a} - ${s}))`,
    getMedianSql: (s) => `PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ${s})`,
    buildArray: (s) => `ARRAY[${s.join(", ")}]`,
    buildArrayAgg: (s, a) => a ? `ARRAY_AGG(${s} ORDER BY ${a})` : `ARRAY_AGG(${s})`
  };
  return Js(e, t, i, r);
};
var Ft = vt("alert-hexagon", "IconAlertHexagon", [
  [
    "path",
    {
      d: "M19.875 6.27c.7 .398 1.13 1.143 1.125 1.948v7.284c0 .809 -.443 1.555 -1.158 1.948l-6.75 4.27a2.269 2.269 0 0 1 -2.184 0l-6.75 -4.27a2.225 2.225 0 0 1 -1.158 -1.948v-7.285c0 -.809 .443 -1.554 1.158 -1.947l6.75 -3.98a2.33 2.33 0 0 1 2.25 0l6.75 3.98h-.033z",
      key: "svg-0"
    }
  ],
  ["path", { d: "M12 8v4", key: "svg-1" }],
  ["path", { d: "M12 16h.01", key: "svg-2" }]
]), Pt = vt("table-alias", "IconTableAlias", [
  [
    "path",
    {
      d: "M3 12v-7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-7",
      key: "svg-0"
    }
  ],
  ["path", { d: "M3 10h18", key: "svg-1" }],
  ["path", { d: "M10 3v10", key: "svg-2" }],
  [
    "path",
    {
      d: "M2 17a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-4z",
      key: "svg-3"
    }
  ]
]), Zs = Object.defineProperty, ei = Object.defineProperties, ti = Object.getOwnPropertyDescriptors, mt = Object.getOwnPropertySymbols, ni = Object.prototype.hasOwnProperty, si = Object.prototype.propertyIsEnumerable, pt = (e, t, i) => t in e ? Zs(e, t, { enumerable: !0, configurable: !0, writable: !0, value: i }) : e[t] = i, ze = (e, t) => {
  for (var i in t || (t = {}))
    ni.call(t, i) && pt(e, i, t[i]);
  if (mt)
    for (var i of mt(t))
      si.call(t, i) && pt(e, i, t[i]);
  return e;
}, ii = (e, t) => ei(e, ti(t));
const ri = ["filled", "light", "subtle"];
function oi({ theme: e, variant: t, color: i }) {
  if (!ri.includes(t))
    return null;
  const r = e.fn.variant({ variant: t, color: i });
  return {
    "&[data-active]": ze({
      backgroundColor: r.background,
      color: r.color
    }, e.fn.hover({ backgroundColor: r.hover }))
  };
}
var ai = vn((e, { noWrap: t, childrenOffset: i, alignIcon: r, color: s }, { variant: a }) => ({
  root: ii(ze(ze({
    display: "flex",
    alignItems: "center",
    width: "100%",
    padding: `${ke(8)} ${e.spacing.sm}`,
    userSelect: "none"
  }, oi({ theme: e, variant: a, color: s })), e.fn.hover({
    backgroundColor: e.colorScheme === "dark" ? e.colors.dark[6] : e.colors.gray[0]
  })), {
    "&[data-disabled]": {
      opacity: 0.4,
      pointerEvents: "none"
    }
  }),
  icon: {
    marginRight: e.spacing.sm,
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    alignSelf: r === "center" ? "center" : "flex-start",
    paddingTop: r === "center" ? void 0 : ke(4)
  },
  rightSection: {
    marginLeft: e.spacing.sm,
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    transition: `transform 150ms ${e.transitionTimingFunction}`,
    "&[data-rotate]": {
      transform: "rotate(90deg)"
    }
  },
  body: {
    flex: 1,
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: t ? "nowrap" : void 0
  },
  label: {},
  description: {
    display: "block",
    "&[data-active]": {
      color: "inherit"
    }
  },
  children: {
    paddingLeft: wn({ size: i, sizes: e.spacing })
  }
})), li = Object.defineProperty, Ae = Object.getOwnPropertySymbols, $t = Object.prototype.hasOwnProperty, Lt = Object.prototype.propertyIsEnumerable, ht = (e, t, i) => t in e ? li(e, t, { enumerable: !0, configurable: !0, writable: !0, value: i }) : e[t] = i, ci = (e, t) => {
  for (var i in t || (t = {}))
    $t.call(t, i) && ht(e, i, t[i]);
  if (Ae)
    for (var i of Ae(t))
      Lt.call(t, i) && ht(e, i, t[i]);
  return e;
}, di = (e, t) => {
  var i = {};
  for (var r in e)
    $t.call(e, r) && t.indexOf(r) < 0 && (i[r] = e[r]);
  if (e != null && Ae)
    for (var r of Ae(e))
      t.indexOf(r) < 0 && Lt.call(e, r) && (i[r] = e[r]);
  return i;
};
const ui = {
  variant: "light",
  childrenOffset: "lg"
}, jt = zs((e, t) => {
  const i = In("NavLink", ui, e), {
    label: r,
    description: s,
    icon: a,
    rightSection: l,
    className: m,
    classNames: c,
    styles: d,
    unstyled: p,
    active: f,
    color: h,
    variant: v,
    noWrap: b,
    children: y,
    opened: w,
    defaultOpened: g,
    onChange: u,
    disableRightSectionRotation: o,
    childrenOffset: T,
    disabled: V,
    onClick: S
  } = i, z = di(i, [
    "label",
    "description",
    "icon",
    "rightSection",
    "className",
    "classNames",
    "styles",
    "unstyled",
    "active",
    "color",
    "variant",
    "noWrap",
    "children",
    "opened",
    "defaultOpened",
    "onChange",
    "disableRightSectionRotation",
    "childrenOffset",
    "disabled",
    "onClick"
  ]), { classes: R, cx: H } = ai({ color: h, noWrap: b, childrenOffset: T, alignIcon: s ? "top" : "center" }, { name: "NavLink", classNames: c, styles: d, unstyled: p, variant: v }), [M, _] = Tn({
    value: w,
    defaultValue: g,
    finalValue: !1,
    onChange: u
  }), F = !!y, C = (A) => {
    F ? (A.preventDefault(), S?.(A), _(!M)) : S?.(A);
  };
  return /* @__PURE__ */ K.createElement(K.Fragment, null, /* @__PURE__ */ K.createElement(Sn, ci({
    ref: t,
    className: H(R.root, m),
    "data-active": f || void 0,
    onClick: C,
    unstyled: p,
    "data-expanded": M || void 0,
    "data-disabled": V || void 0,
    disabled: V
  }, z), a && /* @__PURE__ */ K.createElement("span", {
    className: R.icon
  }, a), /* @__PURE__ */ K.createElement("span", {
    className: R.body
  }, /* @__PURE__ */ K.createElement(Z, {
    component: "span",
    size: "sm",
    className: R.label
  }, r), /* @__PURE__ */ K.createElement(Z, {
    component: "span",
    color: "dimmed",
    size: "xs",
    "data-active": f || void 0,
    className: R.description
  }, s)), (F || l) && /* @__PURE__ */ K.createElement("span", {
    className: R.rightSection,
    "data-rotate": M && !o || void 0
  }, F ? l || /* @__PURE__ */ K.createElement(Mn, {
    width: ke(14),
    height: ke(14),
    style: { transform: "rotate(-90deg)" }
  }) : l)), /* @__PURE__ */ K.createElement(Dn, {
    in: M
  }, /* @__PURE__ */ K.createElement("div", {
    className: R.children
  }, y)));
});
jt.displayName = "@mantine/core/NavLink";
const Ye = En(jt), mi = {
  isOpen: !1,
  open: () => {
  },
  close: () => {
  },
  toggle: () => {
  },
  projectUuid: null,
  currentBranch: null,
  currentFilePath: null,
  hasUnsavedChanges: !1,
  setProjectUuid: () => {
  },
  setCurrentBranch: () => {
  },
  setCurrentFilePath: () => {
  },
  setHasUnsavedChanges: () => {
  }
}, pi = Bs(mi), hi = () => {
  const e = Gs(pi);
  if (!e)
    throw new Error(
      "useSourceCodeEditor must be used within a SourceCodeEditorProvider"
    );
  return e;
}, gi = async () => pe({
  url: "/github/config",
  method: "GET",
  body: void 0
}), fi = () => {
  const e = kn();
  return xn({
    queryKey: ["git-integration"],
    queryFn: () => gi(),
    retry: !1,
    enabled: e?.can("manage", "Explore")
  });
}, ir = Vn.withTypes(), X = An.withTypes(), yi = async ({
  projectUuid: e,
  name: t,
  sql: i,
  columns: r
}) => pe({
  url: `/projects/${e}/sqlRunner/virtual-view`,
  method: "POST",
  body: JSON.stringify({
    name: t,
    sql: i,
    columns: r
  })
}), bi = ({
  projectUuid: e
}) => {
  const { showToastSuccess: t, showToastApiError: i } = he();
  return ve({
    mutationFn: yi,
    onSuccess: (r) => {
      t({
        title: "Success! Virtual view created",
        action: {
          children: "Query from new virtual view",
          icon: On,
          onClick: () => {
            window.open(
              `/projects/${e}/tables/${r.name}`,
              "_blank"
            );
          }
        }
      });
    },
    onError: ({ error: r }) => {
      i({
        title: "Error creating virtual view",
        apiError: r
      });
    }
  });
}, Ci = async ({
  exploreName: e,
  projectUuid: t,
  name: i,
  sql: r,
  columns: s
}) => pe({
  url: `/projects/${t}/sqlRunner/virtual-view/${e}`,
  method: "PUT",
  body: JSON.stringify({
    name: i,
    sql: r,
    columns: s
  })
}), vi = (e) => {
  const t = wt(), { showToastSuccess: i, showToastError: r } = he();
  return ve({
    mutationFn: Ci,
    onSuccess: async ({ name: s }) => {
      await t.invalidateQueries({
        queryKey: ["tables", e, "filtered"]
      }), await t.invalidateQueries({
        queryKey: ["tables", s, e]
      }), i({
        title: "Success! Virtual view updated"
      });
    },
    onError: () => {
      r({
        title: "Error updating virtual view"
      });
    }
  });
}, wi = async ({
  projectUuid: e,
  name: t
}) => pe({
  url: `/projects/${e}/sqlRunner/virtual-view/${t}`,
  method: "DELETE",
  body: void 0
}), Ei = (e) => {
  const t = Be(), i = wt(), { showToastSuccess: r, showToastError: s } = he();
  return ve({
    mutationFn: wi,
    onSuccess: async () => {
      await i.invalidateQueries({
        queryKey: ["tables", e, "filtered"]
      }), r({
        title: "Success! Virtual view deleted"
      }), t(`/projects/${e}/tables`);
    },
    onError: () => {
      s({
        title: "Error deleting virtual view"
      });
    }
  });
}, Ii = Fn({
  name: jn().min(1)
}), gt = "create-virtual-view-form", rr = ({ opened: e, onClose: t }) => {
  const i = _n(), r = X((w) => w.sqlRunner.projectUuid), s = X((w) => w.sqlRunner.sql), a = X((w) => w.sqlRunner.sqlColumns), l = X((w) => w.sqlRunner.name), {
    mutateAsync: m,
    isLoading: c,
    error: d
  } = bi({
    projectUuid: r
  }), p = Nn({
    initialValues: {
      name: l || ""
    },
    validate: Rn(Ii)
  }), { data: f } = Pn(r), { data: h, isError: v } = fi(), b = !!(i.data?.hasGithub && h?.enabled === !0 && !v && f?.dbtConnection.type === $n.GITHUB), y = D(
    async (w) => {
      a && (await m({
        name: Ln(w.name),
        sql: s,
        columns: a,
        projectUuid: r
      }), t());
    },
    [a, t, r, s, m]
  );
  return /* @__PURE__ */ n(
    Oe,
    {
      opened: e,
      onClose: t,
      title: "Create virtual view",
      icon: Pt,
      size: "md",
      cancelDisabled: c,
      headerActions: /* @__PURE__ */ n(
        _e,
        {
          variant: "xs",
          withinPortal: !0,
          multiline: !0,
          maw: 300,
          label: `Create a virtual view so others can reuse this query in Lightdash. The query won't be saved to or managed in your dbt project. ${b ? "If you're expecting to reuse this query regularly, we suggest writing it back to dbt." : ""} `,
          children: /* @__PURE__ */ n(I, { color: "ldGray.7", icon: It })
        }
      ),
      actions: /* @__PURE__ */ n(
        oe,
        {
          type: "submit",
          form: gt,
          disabled: !p.values.name || !s,
          loading: c,
          children: "Create"
        }
      ),
      children: /* @__PURE__ */ n("form", { id: gt, onSubmit: p.onSubmit(y), children: /* @__PURE__ */ n(J, { children: /* @__PURE__ */ n(
        Et,
        {
          label: "Name",
          required: !0,
          ...p.getInputProps("name"),
          error: !!d?.error
        }
      ) }) })
    }
  );
}, Ti = ({
  opened: e,
  onClose: t,
  virtualViewName: i,
  projectUuid: r
}) => {
  const { mutate: s, isLoading: a } = Ei(r);
  return /* @__PURE__ */ n(
    Oe,
    {
      opened: e,
      onClose: t,
      title: "Delete virtual view",
      variant: "delete",
      resourceType: "virtual view",
      resourceLabel: i,
      onConfirm: () => {
        s({ projectUuid: r, name: i }), t();
      },
      confirmLoading: a,
      children: /* @__PURE__ */ n(G, { fz: "sm", c: "dimmed", children: "This action cannot be undone and charts based on this virtual view will break." })
    }
  );
}, Si = qs(() => import("./SqlRunner-DW6DEAyl.mjs")), Mi = ({
  opened: e,
  onClose: t,
  activeTableName: i,
  explore: r
}) => {
  const s = !!zn("create_saved_chart_version"), [a, l] = Qe(), m = ge(), c = Be(), d = B(Tt), [p, f] = q(s ? "unsavedChanges" : "editVirtualView"), h = D(() => {
    m(
      $.clearQuery({
        defaultState: Bn,
        tableName: d
      })
    ), c({ search: "" }, { replace: !0 });
  }, [m, d, c]), v = () => {
    p === "editVirtualView" && (f(void 0), t());
  };
  return p === "unsavedChanges" ? /* @__PURE__ */ n(
    Oe,
    {
      opened: e,
      onClose: t,
      title: "You have unsaved changes",
      icon: St,
      description: "Are you sure you want to leave this page? Changes you've made to your query will not be saved.",
      actions: /* @__PURE__ */ n(
        oe,
        {
          color: "red",
          onClick: () => {
            l(() => {
              h(), f("editVirtualView");
            });
          },
          loading: a,
          children: "Discard & continue"
        }
      )
    }
  ) : /* @__PURE__ */ E(
    Ie.Root,
    {
      opened: e && p === "editVirtualView",
      onClose: v,
      size: "97vw",
      centered: !1,
      yOffset: "3vh",
      xOffset: "2vw",
      closeOnClickOutside: !1,
      children: [
        /* @__PURE__ */ n(Ie.Overlay, {}),
        /* @__PURE__ */ n(Ie.Content, { children: /* @__PURE__ */ n(Ie.Body, { p: 0, children: /* @__PURE__ */ n(
          Us,
          {
            fallback: /* @__PURE__ */ n(Ge, { h: "95vh", w: "95vw", children: /* @__PURE__ */ E(J, { align: "center", justify: "center", children: [
              /* @__PURE__ */ n(Mt, { type: "bars" }),
              /* @__PURE__ */ n(G, { fw: 500, children: "Loading SQL Runner..." })
            ] }) }),
            children: /* @__PURE__ */ n(
              Si,
              {
                isEditMode: !0,
                virtualViewState: {
                  name: r.name,
                  label: r.label,
                  sql: r.tables[i].sqlTable,
                  onCloseEditVirtualView: t
                }
              }
            )
          }
        ) }) })
      ]
    }
  );
}, Di = async (e, t, i) => pe({
  url: `/projects/${e}/validate?fromSettings=${t.toString()}&${i ? `jobId=${i}` : ""}`,
  method: "GET",
  body: void 0
}), ki = async (e, t = {}) => pe({
  url: `/projects/${e}/validate`,
  method: "POST",
  body: JSON.stringify(t)
}), xi = (e) => {
  const { showToastError: t, showToastApiError: i } = he(), [r, s] = q(!1);
  return { ...ve({
    mutationFn: (l) => ki(e, l),
    onSuccess: (l, m) => {
      s(!0), Gn(l.jobId).then(async () => {
        const c = await Di(
          e,
          !1,
          l.jobId
        );
        await m.onComplete(c);
      }).catch((c) => {
        t({
          title: "Unable to get validation",
          subtitle: c.message
        });
      }).finally(() => {
        s(!1);
      });
    },
    onError: ({ error: l }) => {
      i({
        title: "Failed to get validation",
        apiError: l
      }), s(!1);
    }
  }), isPolling: r };
}, Vi = (e, t) => ve(async ({ sql: i, limit: r }) => Un(e, i, r), {
  mutationKey: ["sqlRunner", "run"],
  ...t
}), Ai = (e, t) => {
  if (!e)
    return;
  const i = e.reduce((r, s) => {
    const a = t.find(
      (l) => l.reference === s.reference
    );
    if (a) {
      if (a.type !== s.type)
        return [
          ...r,
          {
            reference: s.reference,
            type: "typeChanged",
            oldType: s.type,
            newType: a.type
          }
        ];
    } else return [
      ...r,
      { reference: s.reference, type: "deleted" }
    ];
    return r;
  }, []);
  return t.forEach((r) => {
    e.find(
      (a) => a.reference === r.reference
    ) || i.push({
      reference: r.reference,
      type: "added"
    });
  }), i?.sort((r, s) => r.type.localeCompare(s.type));
}, ft = W(({ diff: e }) => /* @__PURE__ */ E(ie, { gap: "xs", wrap: "nowrap", children: [
  /* @__PURE__ */ n(
    I,
    {
      icon: e.type === "deleted" ? ye : Ft,
      color: e.type === "deleted" ? "red" : "yellow",
      size: 16
    }
  ),
  e.type === "deleted" ? /* @__PURE__ */ E(G, { fz: "sm", c: "gray.7", children: [
    /* @__PURE__ */ n(G, { span: !0, fw: 600, c: "gray.8", fz: "sm", children: e.reference }),
    " ",
    "has been deleted"
  ] }) : /* @__PURE__ */ E(G, { fz: "sm", c: "gray.7", children: [
    /* @__PURE__ */ n(G, { span: !0, fw: 600, c: "gray.8", children: e.reference }),
    " ",
    "type changed:",
    " ",
    /* @__PURE__ */ n(G, { span: !0, fw: 500, c: "gray.6", children: e.oldType }),
    " ",
    "→",
    " ",
    /* @__PURE__ */ n(G, { span: !0, fw: 500, c: "gray.8", children: e.newType })
  ] })
] })), yt = ({ chartErrors: e, projectUuid: t }) => {
  const i = e[0], r = e.map((s) => s.error);
  return /* @__PURE__ */ E(ie, { gap: "xs", wrap: "nowrap", children: [
    /* @__PURE__ */ n(I, { icon: Ft, color: "orange", size: 16 }),
    /* @__PURE__ */ n(
      _e,
      {
        variant: "xs",
        withinPortal: !0,
        label: /* @__PURE__ */ n(J, { gap: 2, children: r.map((s, a) => /* @__PURE__ */ n(G, { fz: 11, children: s }, a)) }),
        withArrow: !0,
        position: "right",
        multiline: !0,
        maw: 300,
        children: /* @__PURE__ */ n(
          Yn,
          {
            href: `/projects/${t}/saved/${i.chartUuid}`,
            target: "_blank",
            fz: "sm",
            fw: 500,
            children: i.name
          }
        )
      }
    )
  ] });
}, Oi = ({ opened: e, onClose: t, columnDiffs: i, chartValidationErrors: r, onSave: s }) => {
  const a = X((u) => u.sqlRunner.projectUuid), l = i.filter(
    (u) => u.type === "added"
  ).length, m = i.filter((u) => u.type !== "added"), c = m.length > 3, [d, p] = q(!1), f = m.slice(0, 3), h = x(() => r ? Kn(
    r.filter(
      (u) => Dt(u)
    ),
    "chartUuid"
  ) : {}, [r]), v = Object.entries(h), b = v.length > 3, [y, w] = q(!1), g = v.slice(0, 3);
  return /* @__PURE__ */ n(
    Oe,
    {
      opened: e,
      onClose: t,
      title: "Schema changes detected",
      icon: St,
      actions: /* @__PURE__ */ n(oe, { color: "orange", onClick: s, children: "Save Anyway" }),
      children: /* @__PURE__ */ E(J, { gap: "md", children: [
        /* @__PURE__ */ E(J, { gap: "xs", children: [
          /* @__PURE__ */ n(G, { fz: "sm", fw: 500, c: "ldGray.7", children: "Column changes" }),
          /* @__PURE__ */ n(je, { p: "sm", radius: "md", withBorder: !0, bg: "ldGray.0", children: /* @__PURE__ */ E(J, { gap: "xs", children: [
            l > 0 && /* @__PURE__ */ E(ie, { gap: "xs", children: [
              /* @__PURE__ */ n(
                I,
                {
                  icon: kt,
                  color: "green",
                  size: 16
                }
              ),
              /* @__PURE__ */ E(G, { fz: "sm", c: "ldGray.7", children: [
                l,
                " new column",
                l > 1 ? "s" : "",
                " added"
              ] })
            ] }),
            f.map((u, o) => /* @__PURE__ */ n(ft, { diff: u }, o)),
            /* @__PURE__ */ n(tt, { in: d, children: m.slice(3).map((u, o) => /* @__PURE__ */ n(ft, { diff: u }, o + 3)) }),
            c && /* @__PURE__ */ n(
              oe,
              {
                size: "compact-xs",
                variant: "subtle",
                color: "ldGray.6",
                onClick: () => p(!d),
                children: d ? "Show less" : `Show ${m.length - 3} more`
              }
            )
          ] }) })
        ] }),
        v.length > 0 && /* @__PURE__ */ E(J, { gap: "xs", children: [
          /* @__PURE__ */ E(G, { fz: "sm", fw: 500, c: "ldGray.7", children: [
            "Affected charts (",
            v.length,
            ")"
          ] }),
          /* @__PURE__ */ n(je, { p: "sm", radius: "md", withBorder: !0, bg: "ldGray.0", children: /* @__PURE__ */ E(J, { gap: "xs", children: [
            g.map(
              ([u, o]) => /* @__PURE__ */ n(
                yt,
                {
                  chartErrors: o,
                  projectUuid: a
                },
                u
              )
            ),
            /* @__PURE__ */ n(tt, { in: y, children: v.slice(3).map(([u, o]) => /* @__PURE__ */ n(
              yt,
              {
                chartErrors: o,
                projectUuid: a
              },
              u
            )) }),
            b && /* @__PURE__ */ n(
              oe,
              {
                size: "compact-xs",
                variant: "subtle",
                color: "gray",
                onClick: () => w(
                  !y
                ),
                children: y ? "Show less" : `Show ${v.length - 3} more`
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ n(G, { fz: "sm", c: "ldGray.6", children: "These changes could break existing content using this virtual view." })
      ] })
    }
  );
}, or = ({ virtualViewState: e }) => {
  const { showToastError: t } = he(), [i, r] = q(void 0), s = X((M) => M.sqlRunner.sqlColumns), [a, l] = q([]), [m, c] = q(void 0), [d, p] = q(!1), f = Be(), h = X((M) => M.sqlRunner.sql), v = X((M) => M.sqlRunner.projectUuid), b = X(
    (M) => M.sqlRunner.warehouseConnectionType
  ), y = x(
    () => Hs(
      e.sql,
      h,
      b
    ),
    [h, e.sql, b]
  ), { mutateAsync: w, isPolling: g } = xi(v), { mutateAsync: u, isLoading: o } = Vi(v), { mutateAsync: T, isLoading: V } = vi(v);
  Ke(() => {
    s && (i || r(s));
  }, [i, s]);
  const [S, z] = q(
    e.label || de(e.name)
  ), R = async ({
    handleDiff: M
  }) => {
    console.log("[VirtualView Debug] handleUpdateVirtualView called", {
      handleDiff: M,
      virtualViewName: e.name,
      sql: h.substring(0, 100) + "..."
    });
    let _;
    try {
      const C = await u({ sql: h, limit: 1 });
      if (C)
        _ = C.columns;
      else {
        t({
          title: "Error running query",
          subtitle: "No results returned"
        });
        return;
      }
    } catch (C) {
      Wn(C) && t({
        title: "Error running query",
        subtitle: C.error.message
      });
      return;
    }
    if (!_)
      return t({
        title: "Error running query",
        subtitle: "No columns returned"
      });
    if (console.log("[VirtualView Debug] Columns from query:", {
      columnsFromQuery: _,
      initialColumns: i
    }), !M)
      return await T({
        exploreName: e.name,
        projectUuid: v,
        name: S,
        sql: h,
        columns: _
      }), f(0);
    const F = Xs(
      e.name,
      h,
      _
    );
    console.log("[VirtualView Debug] Created temporary virtual view:", {
      exploreName: F.name,
      baseTable: F.baseTable,
      tables: Object.keys(F.tables || {}),
      dimensions: Object.keys(
        F.tables?.[F.baseTable]?.dimensions || {}
      )
    }), console.log("[VirtualView Debug] Calling getValidation..."), await w({
      explores: [F],
      validationTargets: [Qn.CHARTS],
      onlyValidateExploresInArgs: !0,
      onComplete: async (C) => {
        if (console.log("[VirtualView Debug] Validation response:", {
          responseLength: C.length,
          response: C,
          chartErrors: C.filter(
            (A) => Dt(A)
          )
        }), C.length === 0)
          console.log(
            "[VirtualView Debug] No validation errors, saving directly"
          ), await T({
            exploreName: e.name,
            projectUuid: v,
            name: S,
            sql: h,
            columns: _
          }), f(0);
        else if (console.log(
          "[VirtualView Debug] Has validation errors, checking diffs",
          { handleDiff: M, hasInitialColumns: !!i }
        ), M && i) {
          c(C);
          const A = Ai(
            i,
            _
          );
          console.log("[VirtualView Debug] Column diffs:", {
            diffs: A,
            diffsLength: A?.length ?? 0
          }), !A || A.length === 0 ? (console.log(
            "[VirtualView Debug] No column diffs, saving directly (despite validation errors!)"
          ), await T({
            exploreName: e.name,
            projectUuid: v,
            name: S,
            sql: h,
            columns: _
          }), f(0)) : (console.log(
            "[VirtualView Debug] Showing warning modal with:",
            {
              columnDiffs: A,
              chartValidationErrors: C
            }
          ), l(A), p(!0));
        }
      }
    });
  }, H = x(() => S !== e.label || y, [S, e.label, y]);
  return /* @__PURE__ */ E(
    ie,
    {
      p: "md",
      py: "xs",
      justify: "space-between",
      className: "border-b border-ldGray-3",
      children: [
        /* @__PURE__ */ n(
          qn,
          {
            visible: g || o || V,
            loaderProps: {
              children: /* @__PURE__ */ n(Ge, { h: "95vh", w: "95vw", children: /* @__PURE__ */ E(J, { align: "center", justify: "center", children: [
                /* @__PURE__ */ n(Mt, {}),
                /* @__PURE__ */ n(G, { fw: 500, children: "Validating your changes..." })
              ] }) })
            }
          }
        ),
        /* @__PURE__ */ n(ie, { gap: "xs", children: /* @__PURE__ */ E(ie, { gap: "xs", children: [
          /* @__PURE__ */ n(je, { p: "xxs", withBorder: !0, radius: "sm", children: /* @__PURE__ */ n(I, { icon: Pt }) }),
          "Editing",
          /* @__PURE__ */ n(
            Et,
            {
              fz: "sm",
              fw: 500,
              value: S,
              onChange: (M) => z(M.currentTarget.value)
            }
          )
        ] }) }),
        /* @__PURE__ */ E(ie, { gap: "sm", children: [
          /* @__PURE__ */ n(
            _e,
            {
              variant: "xs",
              label: "No changes to save",
              disabled: H,
              children: /* @__PURE__ */ n(Hn, { children: /* @__PURE__ */ n(
                oe,
                {
                  size: "xs",
                  disabled: g || o || !H,
                  onClick: () => R({ handleDiff: !0 }),
                  color: "green",
                  children: "Save"
                }
              ) })
            }
          ),
          /* @__PURE__ */ n(
            oe,
            {
              size: "xs",
              variant: "default",
              onClick: () => {
                e.onCloseEditVirtualView();
              },
              children: "Cancel"
            }
          )
        ] }),
        /* @__PURE__ */ n(
          Oi,
          {
            opened: d,
            onSave: () => R({ handleDiff: !1 }),
            onClose: () => p(!1),
            columnDiffs: a,
            chartValidationErrors: m
          }
        )
      ]
    }
  );
}, bt = 3, Je = (e, t) => (i, r) => {
  if (e === Ne.INDEX)
    return i.index - r.index;
  const s = t[i.key], a = t[r.key];
  return ee(s) && ee(a) && s.timeInterval && a.timeInterval ? Jn(s.timeInterval, a.timeInterval) : i.label.localeCompare(r.label);
}, Fe = (e) => "children" in e, _i = (e, t) => !t || t === "" ? [] : new Xn(Object.entries(e), {
  keys: ["1.label", "1.groupLabel"],
  ignoreLocation: !0,
  threshold: 0.3
}).search(t).map((i) => i.item[0]), Ni = (e) => ee(e) && e.isIntervalBase === !0, zt = (e, t, i, r, s, a, l) => {
  if (i.length === 0)
    return {
      ...e,
      [t.key]: t
    };
  const [m, ...c] = i, d = r[m] || {
    label: m
  }, p = d.label, f = e[p];
  if (f && !Fe(f))
    return console.warn(
      `Field "${t.key}" cannot be grouped under "${p}" because a field with that key already exists. Adding to current level instead.`
    ), {
      ...e,
      [t.key]: t
    };
  const h = f || {
    key: p,
    label: p,
    description: d.description ?? "",
    children: {},
    index: t.index ?? Number.MAX_SAFE_INTEGER
  }, v = s && c.length === 0 ? {
    ...h.children || {},
    [t.key]: t
  } : zt(
    h.children || {},
    t,
    c,
    r,
    s,
    a,
    l
  ), y = Object.values(v).sort(
    Je(a, l)
  ).reduce(
    (g, u) => ({
      ...g,
      [u.key]: u
    }),
    {}
  ), w = {
    ...h,
    children: y
  };
  return {
    ...e,
    [p]: w
  };
}, Te = (e, t = {}, i = Ne.LABEL) => Object.entries(e).filter(
  ([s, a]) => be(a) ? !0 : !a.hidden
).reduce((s, [a, l]) => {
  const m = be(l) ? {
    key: a,
    label: l.name,
    index: Number.MAX_SAFE_INTEGER
  } : {
    key: a,
    label: l.label || l.name,
    index: l.index ?? Number.MAX_SAFE_INTEGER
  };
  if (!fe(l))
    return {
      ...s,
      [m.key]: m
    };
  if (Ni(l))
    return s;
  let c = [...l.groups || []], d = !1;
  if (l.groupLabel && c.push(l.groupLabel), ee(l) && l.group) {
    const f = U({
      table: l.table,
      name: l.group
    });
    c.push(f), d = !0;
  }
  const p = c.slice(0, bt);
  return c.length > bt && ee(l) && l.timeInterval && p.push(c[c.length - 1]), zt(
    s,
    m,
    p,
    t,
    d,
    i,
    e
  );
}, {});
var L = /* @__PURE__ */ ((e) => (e.Dimensions = "dimensions", e.Metrics = "metrics", e.CustomMetrics = "custom-metrics", e.CustomDimensions = "custom-dimensions", e.MissingFields = "missing-fields", e))(L || {});
function Bt(e, t, i, r = "") {
  const s = r ? `${r}-` : "";
  return `${e}-${t}-group-${s}${i}`;
}
function Ri(e, t) {
  return `${e}-${t}`;
}
const Y = {
  TABLE_HEADER: 32,
  SECTION_HEADER: 42,
  TREE_SINGLE_NODE: 32,
  TREE_GROUP_NODE: 32,
  MISSING_FIELD: 32,
  EMPTY_STATE: 60
};
function Gt(e, t, i, r, s, a, l, m = 0, c = "") {
  const d = [], p = !l || a.includes(e.key), f = Fe(e);
  if (!p && !f) return d;
  if (f) {
    const h = e;
    if (!Object.values(h.children).some(
      (w) => !l || a.includes(w.key) || "children" in w && w.children && Object.values(w.children).some(
        (g) => a.includes(g.key)
      )
    ) && l)
      return d;
    const b = Bt(
      r,
      i,
      e.key,
      c
    ), y = s.has(b) || l;
    if (d.push({
      id: b,
      type: "tree-node",
      estimatedHeight: Y.TREE_GROUP_NODE,
      data: {
        node: e,
        isGroup: !0,
        isExpanded: y,
        sectionKey: t,
        depth: m
      }
    }), y) {
      const w = c ? `${c}-${e.key}` : e.key;
      Object.values(h.children).forEach((g) => {
        d.push(
          ...Gt(
            g,
            t,
            i,
            r,
            s,
            a,
            l,
            m + 1,
            w
          )
        );
      });
    }
  } else
    d.push({
      id: `${r}-${i}-node-${e.key}`,
      type: "tree-node",
      estimatedHeight: Y.TREE_SINGLE_NODE,
      data: {
        node: e,
        isGroup: !1,
        sectionKey: t,
        depth: m
      }
    });
  return d;
}
function Se(e, t, i, r, s, a, l, m = 0) {
  const c = `${t}-${e.type}`, d = a.sectionNodeMaps.get(c);
  if (!d)
    return [];
  const p = Ri(t, e.type), f = {
    tableName: t,
    sectionType: e.type,
    itemsMap: e.itemsMap,
    nodeMap: d,
    // Store the pre-computed nodeMap
    missingCustomMetrics: e.type === L.CustomMetrics && e.missingItems ? e.missingItems.filter((y) => ue(y)) : void 0,
    missingCustomDimensions: e.type === L.CustomDimensions && e.missingItems ? e.missingItems.filter((y) => be(y)) : void 0,
    itemsAlerts: e.itemsAlerts,
    orderFieldsBy: e.orderFieldsBy,
    isGithubIntegrationEnabled: a.isGithubIntegrationEnabled,
    gitIntegration: a.gitIntegration,
    searchQuery: a.searchQuery,
    searchResults: r
  };
  l.set(p, f);
  const h = [], v = e.orderFieldsBy ?? Ne.LABEL;
  return Object.values(d).sort(
    Je(v, e.itemsMap)
  ).forEach((y) => {
    h.push(
      ...Gt(
        y,
        p,
        e.type,
        t,
        i,
        r,
        s,
        m
      )
    );
  }), h;
}
function Fi(e, t, i) {
  const r = [], s = e.name, a = t.expandedTables.has(s) || t.isSearching, l = t.searchResultsMap[s] || [], m = t.showMultipleTables ? 1 : 0;
  if (t.showMultipleTables && r.push({
    id: `table-header-${s}`,
    type: "table-header",
    estimatedHeight: Y.TABLE_HEADER,
    data: {
      table: e,
      isExpanded: a
    }
  }), !a)
    return r;
  const c = t.missingFieldIds;
  c.length > 0 && (r.push({
    id: `${s}-section-missing`,
    type: "section-header",
    estimatedHeight: Y.SECTION_HEADER,
    data: {
      tableName: s,
      treeSection: L.MissingFields,
      // Arbitrary, missing fields aren't tied to a section
      label: "Missing fields",
      color: "ldGray.6",
      depth: m
    }
  }), c.forEach((u) => {
    r.push({
      id: `${s}-missing-${u}`,
      type: "missing-field",
      estimatedHeight: Y.MISSING_FIELD,
      data: {
        fieldId: u,
        tableName: s,
        isDimension: t.selectedDimensions.includes(u)
      }
    });
  }));
  const d = (u) => u.length > 0, p = Object.values(e.dimensions).reduce(
    (u, o) => ({ ...u, [U(o)]: o }),
    {}
  ), f = Object.keys(p).length > 0;
  if ((f || !t.isSearching && !f || t.isSearching && l.length > 0) && r.push({
    id: `${s}-section-dimensions`,
    type: "section-header",
    estimatedHeight: Y.SECTION_HEADER,
    data: {
      tableName: s,
      treeSection: L.Dimensions,
      label: "Dimensions",
      color: ne.dimension.color,
      depth: m
    }
  }), f) {
    const u = Se(
      {
        type: L.Dimensions,
        color: ne.dimension.color,
        itemsMap: p,
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      l,
      t.isSearching,
      t,
      i,
      m
    );
    (d(u) || !t.isSearching) && r.push(...u);
  } else t.isSearching || r.push({
    id: `${s}-empty-dimensions`,
    type: "empty-state",
    estimatedHeight: Y.EMPTY_STATE,
    data: {
      tableName: s,
      treeSection: L.Dimensions,
      message: "No dimensions defined in your dbt project"
    }
  });
  const h = Object.values(e.metrics).reduce(
    (u, o) => ({ ...u, [U(o)]: o }),
    {}
  ), v = Object.keys(h).length > 0;
  if ((v || !t.isSearching && !v || t.isSearching && l.length > 0) && r.push({
    id: `${s}-section-metrics`,
    type: "section-header",
    estimatedHeight: Y.SECTION_HEADER,
    data: {
      tableName: s,
      treeSection: L.Metrics,
      label: "Metrics",
      color: ne.metric.color,
      depth: m,
      helpButton: v ? void 0 : {
        href: "https://docs.lightdash.com/guides/how-to-create-metrics",
        tooltipText: "No metrics defined in your dbt project. Click to view docs and learn how to add a metric to your project."
      }
    }
  }), v) {
    const u = Se(
      {
        type: L.Metrics,
        color: ne.metric.color,
        itemsMap: h,
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      l,
      t.isSearching,
      t,
      i,
      m
    );
    (d(u) || !t.isSearching) && r.push(...u);
  }
  const y = [
    ...t.additionalMetrics.filter(
      (u) => u.table === s
    ),
    ...t.missingCustomMetrics.filter((u) => u.table === s)
  ].reduce((u, o) => ({ ...u, [U(o)]: o }), {});
  if (Object.keys(y).length > 0) {
    r.push({
      id: `${s}-section-custom-metrics`,
      type: "section-header",
      estimatedHeight: Y.SECTION_HEADER,
      data: {
        tableName: s,
        treeSection: L.CustomMetrics,
        label: "Custom metrics",
        color: ne.metric.color,
        depth: m,
        helpButton: {
          href: "https://docs.lightdash.com/guides/how-to-create-metrics#-adding-custom-metrics-in-the-explore-view",
          tooltipText: "Add custom metrics by hovering over the dimension of your choice & selecting the three-dot Action Menu. Click to view docs."
        }
      }
    });
    const u = t.additionalMetrics.reduce(
      (T, V) => {
        const S = Object.keys(h).includes(
          U(V)
        );
        return {
          ...T,
          [U(V)]: {
            errors: S ? [
              {
                message: "A metric with this ID already exists in the table. Rename your custom metric to prevent conflicts."
              }
            ] : void 0
          }
        };
      },
      {}
    ), o = Se(
      {
        type: L.CustomMetrics,
        color: ne.metric.color,
        itemsMap: y,
        missingItems: t.missingCustomMetrics.filter(
          (T) => T.table === s
        ),
        itemsAlerts: u,
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      l,
      t.isSearching,
      t,
      i,
      m
    );
    r.push(...o);
  }
  const g = (t.customDimensions?.filter((u) => u.table === s) || []).reduce(
    (u, o) => ({ ...u, [U(o)]: o }),
    {}
  );
  if (Object.keys(g).length > 0) {
    r.push({
      id: `${s}-section-custom-dimensions`,
      type: "section-header",
      estimatedHeight: Y.SECTION_HEADER,
      data: {
        tableName: s,
        treeSection: L.CustomDimensions,
        label: "Custom dimensions",
        color: ne.dimension.color,
        depth: m
      }
    });
    const u = Se(
      {
        type: L.CustomDimensions,
        color: ne.dimension.color,
        itemsMap: g,
        missingItems: t.missingCustomDimensions.filter(
          (o) => o.table === s
        ),
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      l,
      t.isSearching,
      t,
      i,
      m
    );
    r.push(...u);
  }
  return r;
}
function Pi(e) {
  const t = [], i = /* @__PURE__ */ new Map();
  return e.tables.filter((s) => e.isSearching ? (e.searchResultsMap[s.name] || []).length > 0 : !0).forEach((s) => {
    t.push(...Fi(s, e, i));
  }), {
    items: t,
    sectionContexts: i
  };
}
function $i(e, t, i) {
  const r = /* @__PURE__ */ new Map();
  return Object.values(e.tables).forEach((s) => {
    const a = s.name, l = Object.fromEntries(
      Object.values(s.dimensions).map((p) => [U(p), p])
    );
    Object.keys(l).length > 0 && r.set(
      `${a}-dimensions`,
      Te(
        l,
        s.groupDetails,
        s.orderFieldsBy
      )
    );
    const m = Object.fromEntries(
      Object.values(s.metrics).map((p) => [U(p), p])
    );
    Object.keys(m).length > 0 && r.set(
      `${a}-metrics`,
      Te(
        m,
        s.groupDetails,
        s.orderFieldsBy
      )
    );
    const c = t.filter(
      (p) => p.table === a
    );
    if (c.length > 0) {
      const p = Object.fromEntries(
        c.map((f) => [U(f), f])
      );
      r.set(
        `${a}-custom-metrics`,
        Te(
          p,
          s.groupDetails,
          s.orderFieldsBy
        )
      );
    }
    const d = i?.filter((p) => p.table === a) || [];
    if (d.length > 0) {
      const p = Object.fromEntries(
        d.map((f) => [U(f), f])
      );
      r.set(
        `${a}-custom-dimensions`,
        Te(
          p,
          s.groupDetails,
          s.orderFieldsBy
        )
      );
    }
  }), r;
}
const Li = ({ item: e }) => {
  const { message: t } = e.data;
  return /* @__PURE__ */ n(Ge, { pt: "sm", pb: "md", children: /* @__PURE__ */ n(G, { c: "dimmed", children: t }) });
}, Ut = W(Li);
Ut.displayName = "VirtualEmptyState";
const ji = ({
  item: e,
  onRemove: t
}) => {
  const { fieldId: i, isDimension: r } = e.data, s = D(() => {
    t(i, r);
  }, [t, i, r]);
  return /* @__PURE__ */ E(
    ie,
    {
      ml: 32,
      mr: 16,
      my: "xs",
      gap: "xs",
      wrap: "nowrap",
      style: { overflow: "hidden" },
      children: [
        /* @__PURE__ */ n(
          I,
          {
            icon: me,
            color: "yellow.9",
            style: { flexShrink: 0 }
          }
        ),
        /* @__PURE__ */ n(G, { truncate: !0, size: "sm", style: { flex: 1, minWidth: 0 }, children: i }),
        /* @__PURE__ */ n(
          _e,
          {
            withinPortal: !0,
            label: /* @__PURE__ */ E(G, { size: "xs", style: { wordBreak: "break-all" }, children: [
              'Remove missing field "',
              i,
              '".'
            ] }),
            maw: 300,
            multiline: !0,
            children: /* @__PURE__ */ n(
              Zn,
              {
                color: "gray",
                variant: "transparent",
                style: { flexShrink: 0 },
                onClick: s,
                children: /* @__PURE__ */ n(I, { icon: ye, style: { flexShrink: 0 } })
              }
            )
          }
        )
      ]
    }
  );
}, qt = W(ji);
qt.displayName = "VirtualMissingField";
const zi = ({
  item: e
}) => {
  const { label: t, color: i, depth: r, tableName: s, treeSection: a, helpButton: l } = e.data, m = Ue(), { user: c } = qe(), { track: d } = Re(), p = ge(), f = B(He), h = B(xt), v = Vt(
    We.WriteBackCustomBinDimensions
  ), b = x(() => h ? v ? h : h.filter(Me) : [], [h, v]), y = c.data?.ability?.can(
    "manage",
    De("CustomSql", {
      organizationUuid: c.data.organizationUuid,
      projectUuid: m
    })
  ), w = D(() => {
    p(
      $.toggleCustomDimensionModal({
        isEditing: !1,
        table: s,
        item: void 0
      })
    );
  }, [p, s]), g = D(() => {
    m && c.data?.organizationUuid && d({
      name: Q.WRITE_BACK_FROM_CUSTOM_METRIC_HEADER_CLICKED,
      properties: {
        userId: c.data.userUuid,
        projectId: m,
        organizationId: c.data.organizationUuid,
        customMetricsCount: f?.length || 0,
        customDimensionsCount: 0
      }
    }), p(
      $.toggleWriteBackModal({
        items: f
      })
    );
  }, [m, c.data, f, p, d]), u = D(() => {
    m && c.data?.organizationUuid && d({
      name: Q.WRITE_BACK_FROM_CUSTOM_DIMENSION_HEADER_CLICKED,
      properties: {
        userId: c.data.userUuid,
        projectId: m,
        organizationId: c.data.organizationUuid,
        customMetricsCount: 0,
        customDimensionsCount: b?.length || 0
      }
    }), p(
      $.toggleWriteBackModal({
        items: b || []
      })
    );
  }, [m, c.data, b, p, d]), o = x(() => r ? `${r * 20}px` : void 0, [r]), T = a === L.Dimensions && y, V = a === L.CustomMetrics && f && f.length > 0, S = a === L.CustomDimensions && b.length > 0;
  return /* @__PURE__ */ E(ae, { mt: "sm", mb: "xs", pl: o, pr: "sm", position: "apart", children: [
    /* @__PURE__ */ E(ae, { spacing: "xs", children: [
      /* @__PURE__ */ n(Z, { fw: 600, c: i, children: t }),
      l && /* @__PURE__ */ n(
        es,
        {
          href: l.href,
          tooltipProps: {
            label: l.tooltipText,
            multiline: !0
          }
        }
      )
    ] }),
    /* @__PURE__ */ E(ae, { spacing: "xs", children: [
      T && /* @__PURE__ */ n(
        le,
        {
          label: "Add a custom dimension with SQL",
          variant: "xs",
          position: "left",
          children: /* @__PURE__ */ n(
            ts,
            {
              size: "xs",
              variant: "subtle",
              compact: !0,
              leftIcon: /* @__PURE__ */ n(I, { icon: kt }),
              onClick: w,
              "data-testid": "VirtualSectionHeader/AddCustomDimensionButton",
              children: "Add"
            }
          )
        }
      ),
      V && /* @__PURE__ */ n(le, { label: "Write back custom metrics", children: /* @__PURE__ */ n(
        re,
        {
          onClick: g,
          "data-testid": "VirtualSectionHeader/WriteBackCustomMetricsButton",
          children: /* @__PURE__ */ n(I, { icon: Ce })
        }
      ) }),
      S && /* @__PURE__ */ n(le, { label: "Write back custom dimensions", children: /* @__PURE__ */ n(
        re,
        {
          onClick: u,
          "data-testid": "VirtualSectionHeader/WriteBackCustomDimensionsButton",
          children: /* @__PURE__ */ n(I, { icon: Ce })
        }
      ) })
    ] })
  ] });
}, Ht = W(zi);
Ht.displayName = "VirtualSectionHeader";
const Bi = ({
  item: e,
  onToggle: t
}) => {
  const i = ns(), { table: r, isExpanded: s } = e.data, [a, l] = xe(!1), m = D(
    () => l(!0),
    [l]
  ), c = D(
    () => l(!1),
    [l]
  ), d = D(
    () => l(!1),
    [l]
  ), p = x(
    () => ({
      top: 0,
      position: "sticky",
      backgroundColor: i.colorScheme === "dark" ? i.colors.dark[7] : i.colors.background[0],
      zIndex: 1
    }),
    [i.colorScheme, i.colors]
  ), f = /* @__PURE__ */ n(
    Ws,
    {
      label: r.label,
      description: r.description,
      showPreview: a,
      closePreview: d,
      children: /* @__PURE__ */ n(Z, { truncate: !0, fw: 600, children: r.label })
    }
  );
  return /* @__PURE__ */ n(
    Ye,
    {
      opened: s,
      onClick: t,
      onMouseEnter: m,
      onMouseLeave: c,
      icon: /* @__PURE__ */ n(I, { icon: ss, size: "lg", color: "ldGray.7" }),
      label: f,
      style: p,
      children: []
    }
  );
}, Wt = W(Bi);
Wt.displayName = "VirtualTableHeader";
const Qt = is(void 0), Gi = ({
  item: e,
  isHovered: t,
  isSelected: i,
  isOpened: r,
  onMenuChange: s,
  hasDescription: a,
  onViewDescription: l
}) => {
  const m = Ue(), { user: c } = qe(), { showToastSuccess: d } = he(), { addFilter: p } = rs(), { track: f } = Re(), h = ge(), v = x(() => Me(e) ? nt(e.dimensionType) : ee(e) ? nt(e.type) : [], [e]), b = Vt(
    We.WriteBackCustomBinDimensions
  ), y = (g) => {
    const u = JSON.parse(JSON.stringify(g));
    let o = ot(), T = o.replace(/-/g, "").substring(0, 16), V = u.name;
    const S = "_8id9_", z = V.indexOf(S);
    z !== -1 ? V = V.substring(0, z + S.length) + T : V = V + S + T, u.label = "Copy " + u.label, u.uuid = o, u.name = V, h($.addAdditionalMetric(u));
  }, w = (g) => {
    const u = JSON.parse(JSON.stringify(g));
    let o = ot().replace(/-/g, "").substring(0, 16), T = u.id;
    const V = "_8id9_", S = T.indexOf(V);
    S !== -1 ? T = T.substring(0, S + V.length) + o : T = T + V + o, u.name = "Copy " + u.name, u.id = T, h($.addCustomDimension(u));
  };
  return t || i || r ? /* @__PURE__ */ E(
    O,
    {
      withArrow: !0,
      withinPortal: !0,
      shadow: "lg",
      position: "bottom-end",
      arrowOffset: 12,
      offset: -4,
      opened: r,
      onChange: s,
      children: [
        /* @__PURE__ */ E(O.Dropdown, { children: [
          !ue(e) && At(e) ? /* @__PURE__ */ n(
            O.Item,
            {
              component: "button",
              leftSection: /* @__PURE__ */ n(I, { icon: Ot }),
              onClick: (g) => {
                g.stopPropagation(), f({
                  name: Q.ADD_FILTER_CLICKED
                }), p(e, void 0);
              },
              children: "Add filter"
            }
          ) : null,
          ue(e) ? /* @__PURE__ */ E(se, { children: [
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: st }),
                onClick: (g) => {
                  g.stopPropagation(), h(
                    $.toggleAdditionalMetricModal(
                      {
                        type: e.type,
                        item: e,
                        isEditing: !0
                      }
                    )
                  );
                },
                children: "Edit custom metric"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: it }),
                onClick: (g) => {
                  g.stopPropagation(), y(e), f({
                    name: Q.ADD_CUSTOM_METRIC_CLICKED
                  }), d({
                    title: "Copy of Custom metric added successfully"
                  });
                },
                children: "Duplicate custom metric"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: Ce }),
                onClick: (g) => {
                  g.stopPropagation(), m && c.data?.organizationUuid && f({
                    name: Q.WRITE_BACK_FROM_CUSTOM_METRIC_CLICKED,
                    properties: {
                      userId: c.data.userUuid,
                      projectId: m,
                      organizationId: c.data.organizationUuid,
                      customMetricsCount: 1
                    }
                  }), h(
                    $.toggleWriteBackModal({
                      items: [e]
                    })
                  );
                },
                children: "Write back to dbt"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                color: "red",
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: ye }),
                onClick: (g) => {
                  g.stopPropagation(), f({
                    name: Q.REMOVE_CUSTOM_METRIC_CLICKED
                  }), h(
                    $.removeAdditionalMetric(
                      U(e)
                    )
                  );
                },
                children: "Remove custom metric"
              },
              "custommetric"
            )
          ] }) : null,
          a && /* @__PURE__ */ n(
            O.Item,
            {
              component: "button",
              leftSection: /* @__PURE__ */ n(I, { icon: Ve }),
              onClick: (g) => {
                g.stopPropagation(), l();
              },
              children: "View description"
            }
          ),
          be(e) && /* @__PURE__ */ E(se, { children: [
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: st }),
                onClick: (g) => {
                  g.stopPropagation(), h(
                    $.toggleCustomDimensionModal({
                      item: e,
                      isEditing: !0
                    })
                  );
                },
                children: "Edit custom dimension"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: it }),
                onClick: (g) => {
                  g.stopPropagation(), w(e), f({
                    name: Q.ADD_CUSTOM_DIMENSION_CLICKED
                  }), d({
                    title: "Copy of Custom Dimension added successfully"
                  });
                },
                children: "Duplicate custom dimension"
              }
            ),
            (Me(e) || b) && /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: Ce }),
                onClick: (g) => {
                  g.stopPropagation(), m && c.data?.organizationUuid && f({
                    name: Q.WRITE_BACK_FROM_CUSTOM_DIMENSION_CLICKED,
                    properties: {
                      userId: c.data.userUuid,
                      projectId: m,
                      organizationId: c.data.organizationUuid,
                      customDimensionsCount: 1
                    }
                  }), h(
                    $.toggleWriteBackModal({
                      items: [e]
                    })
                  );
                },
                children: "Write back to dbt"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                color: "red",
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: ye }),
                onClick: (g) => {
                  g.stopPropagation(), h(
                    $.removeCustomDimension(
                      U(e)
                    )
                  );
                },
                children: "Remove custom dimension"
              }
            )
          ] }),
          v.length > 0 && (ee(e) || Me(e)) ? /* @__PURE__ */ E(se, { children: [
            /* @__PURE__ */ n(O.Divider, {}),
            /* @__PURE__ */ n(O.Label, { children: "Add custom metrics" }),
            v.map((g) => /* @__PURE__ */ n(
              O.Item,
              {
                role: "menuitem",
                component: "button",
                onClick: (u) => {
                  u.stopPropagation(), console.debug(
                    "opening custom metric modal: " + g
                  ), h(
                    $.toggleAdditionalMetricModal(
                      {
                        type: g,
                        item: e,
                        isEditing: !1
                      }
                    )
                  ), f({
                    name: Q.ADD_CUSTOM_METRIC_CLICKED
                  });
                },
                children: de(g)
              },
              g
            ))
          ] }) : null,
          ee(e) && e.type === Ct.NUMBER ? /* @__PURE__ */ E(se, { children: [
            /* @__PURE__ */ n(O.Divider, {}),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(I, { icon: os }),
                onClick: (g) => {
                  g.stopPropagation(), f({
                    name: Q.ADD_CUSTOM_DIMENSION_CLICKED
                  }), h(
                    $.toggleCustomDimensionModal({
                      item: e,
                      isEditing: !1
                    })
                  );
                },
                children: "Add custom dimensions"
              }
            )
          ] }) : null
        ] }),
        /* @__PURE__ */ n(
          rt,
          {
            component: "div",
            onClick: (g) => {
              g.stopPropagation(), g.preventDefault();
            },
            children: /* @__PURE__ */ n(O.Target, { children: /* @__PURE__ */ n(
              le,
              {
                openDelay: 500,
                position: "top",
                label: "View options",
                disabled: r,
                children: /* @__PURE__ */ n(re, { variant: "transparent", children: /* @__PURE__ */ n(
                  I,
                  {
                    icon: Ve,
                    color: r ? "black" : void 0
                  }
                ) })
              }
            ) })
          }
        )
      ]
    }
  ) : /* @__PURE__ */ n(rt, { w: 28 });
};
function P(e) {
  return as(Qt, (t) => {
    if (t === void 0)
      throw new Error(
        "useTableTree must be used within a TableTreeProvider"
      );
    return e(t);
  });
}
const Kt = ({
  isMissing: e,
  item: t
}) => e ? /* @__PURE__ */ n(I, { icon: me, color: "ldGray.7" }) : /* @__PURE__ */ n(hs, { item: t, color: gs(t), size: "md" });
Kt.displayName = "NavItemIcon";
const Ui = ({ node: e }) => {
  const t = P((k) => k.itemsMap), i = P((k) => k.isSearching), r = P((k) => k.searchResults), s = P((k) => k.searchQuery), a = P(
    (k) => k.missingCustomMetrics
  ), l = P((k) => k.itemsAlerts), m = P(
    (k) => k.missingCustomDimensions
  ), c = P((k) => k.onItemClick), d = P((k) => k.isVirtualized), p = P((k) => k.depth), { track: f } = Re(), h = ls(), v = ge(), [b, y] = xe(!1), [w, g] = xe(!1), u = !i || r.includes(e.key), o = t[e.key], T = x(() => U(o), [o]), V = x(
    () => (k) => cs(k, T),
    [T]
  ), S = x(
    () => (k) => ds(k, T),
    [T]
  ), z = B(
    V,
    (k, ce) => k === ce
  ), R = B(S, (k, ce) => k === ce), H = x(() => {
    if (at(o))
      return {
        type: o.type,
        sql: o.sql,
        compiledSql: o.compiledSql,
        filters: o.filters,
        table: o.table,
        name: o.name
      };
  }, [o]), M = fe(o) ? o.description : void 0, _ = ue(o) && a && a.includes(o) || be(o) && m && m.includes(o), F = x(() => at(o) && (H || M) ? !1 : !M && !_, [M, _, o, H]), C = us(o), A = l?.[U(o)], j = fe(o) && z, N = (j || b) && !ue(o) && At(o), we = ee(o) && o.timeInterval && ms(o.timeInterval) ? ps[o.timeInterval].getLabel() : void 0, Ee = (fe(o) || ue(o)) && (we || o.label) || o.name, nn = D(
    (k) => {
      f({ name: Q.ADD_FILTER_CLICKED }), j || h(o, void 0), k.stopPropagation();
    },
    [j, h, o, f]
  ), sn = D(() => {
    c(e.key, o);
  }, [c, e.key, o]), rn = D(
    () => y(!0),
    [y]
  ), on = D(
    () => y(!1),
    [y]
  ), an = D(
    /**
     * If we don't stop propagation, users may unintentionally toggle dimensions/metrics
     * while interacting with the hovercard.
     */
    (k) => k.stopPropagation(),
    []
  ), et = D(() => {
    y(!1), v(
      $.openItemDetail({
        itemType: "field",
        label: Ee,
        description: M,
        fieldItem: o
      })
    );
  }, [y, v, o, Ee, M]), ln = D(() => {
    y(!1), g();
  }, [y, g]), cn = x(
    () => ({
      backgroundColor: R ? C.bg : void 0,
      "&:hover": {
        backgroundColor: C.bgHover
      }
    }),
    [R, C]
  ), dn = x(
    () => /* @__PURE__ */ n(Kt, { isMissing: _, item: o }),
    [_, o]
  ), un = x(() => [
    { type: "infos", alertIcon: It, color: "blue.6" },
    {
      type: "warnings",
      alertIcon: me,
      color: "yellow.9"
    },
    { type: "errors", alertIcon: me, color: "red.6" }
  ].flatMap(({ type: ce, alertIcon: pn, color: hn }) => {
    const Pe = A?.[ce];
    return !Pe || Pe.length === 0 ? [] : /* @__PURE__ */ n(
      le,
      {
        withinPortal: !0,
        maw: 300,
        multiline: !0,
        label: Pe.join(`
`),
        children: /* @__PURE__ */ n(
          I,
          {
            icon: pn,
            color: hn,
            style: { flexShrink: 0 }
          }
        )
      },
      ce
    );
  }), [A]), mn = x(() => {
    if (d)
      return `${12 + (p ?? 0) * 20}px`;
  }, [p, d]);
  return !o || !u ? null : /* @__PURE__ */ n(
    Ye,
    {
      component: "div",
      noWrap: !0,
      sx: cn,
      icon: dn,
      onClick: sn,
      onMouseEnter: rn,
      onMouseLeave: on,
      pl: mn,
      label: /* @__PURE__ */ E(ae, { noWrap: !0, spacing: "xs", children: [
        /* @__PURE__ */ E(
          te,
          {
            openDelay: 300,
            keepMounted: !1,
            shadow: "subtle",
            withinPortal: !0,
            withArrow: !0,
            disabled: F,
            position: "right",
            radius: "md",
            offset: 70,
            children: [
              /* @__PURE__ */ n(te.Target, { children: /* @__PURE__ */ n(
                _t,
                {
                  component: Z,
                  truncate: !0,
                  sx: { flexGrow: 1 },
                  highlight: s || "",
                  children: Ee
                }
              ) }),
              /* @__PURE__ */ n(
                te.Dropdown,
                {
                  hidden: !b,
                  p: "xs",
                  miw: 400,
                  mah: 500,
                  maw: 500,
                  sx: { overflow: "auto" },
                  onClick: an,
                  children: _ ? `This field from '${o.table}' table is no longer available` : /* @__PURE__ */ n(
                    Rt,
                    {
                      onViewDescription: et,
                      description: M,
                      metricInfo: H
                    }
                  )
                }
              )
            ]
          }
        ),
        un,
        N && /* @__PURE__ */ n(
          le,
          {
            withinPortal: !0,
            label: j ? "This field is filtered" : "Click here to add filter",
            children: /* @__PURE__ */ n(re, { onClick: nn, children: /* @__PURE__ */ n(
              I,
              {
                icon: Ot,
                style: { flexShrink: 0 }
              }
            ) })
          }
        ),
        fe(o) && o.hidden ? /* @__PURE__ */ n(
          le,
          {
            withinPortal: !0,
            label: "This field has been hidden in the dbt project. It's recommend to remove it from the query",
            children: /* @__PURE__ */ n(
              I,
              {
                icon: me,
                color: "yellow.9",
                style: { flexShrink: 0 }
              }
            )
          }
        ) : null
      ] }),
      rightSection: /* @__PURE__ */ n(
        Gi,
        {
          item: o,
          isHovered: b,
          isSelected: R,
          isOpened: w,
          hasDescription: !!M,
          onViewDescription: et,
          onMenuChange: ln
        }
      ),
      "data-testid": `tree-single-node-${Ee}`
    }
  );
}, Xe = W(Ui);
Xe.displayName = "TreeSingleNode";
const qi = ({ nodeMap: e }) => {
  const t = P((s) => s.itemsMap), i = P((s) => s.orderFieldsBy), r = x(() => Object.values(e).sort(
    Je(i ?? Ne.LABEL, t)
  ), [e, i, t]);
  return /* @__PURE__ */ n(se, { children: r.map(
    (s) => Fe(s) ? /* @__PURE__ */ n(Ze, { node: s }, s.key) : /* @__PURE__ */ n(Xe, { node: s }, s.key)
  ) });
}, Yt = W(qi);
Yt.displayName = "TreeNodes";
const Hi = (e) => e.flatMap(function t(i) {
  return i.children ? Object.values(i.children).flatMap(t) : [i.key];
}), Wi = ({ node: e }) => {
  const t = ge(), i = B(Nt), r = P((N) => N.isSearching), s = P((N) => N.searchQuery), a = P((N) => N.searchResults), l = P((N) => N.tableName), m = P((N) => N.treeSectionType), c = P((N) => N.expandedGroups), d = P((N) => N.onToggleGroup), p = P((N) => N.isVirtualized), f = P((N) => N.depth), h = P((N) => N.groupKey), [v, b] = xe(!1), y = h ?? Bt(l, m, e.key), w = c.has(y), g = x(() => Hi([e]), [e]), u = x(
    () => lt(g, Array.from(i)),
    [g, i]
  ), o = x(
    () => fs(g, Array.from(i)).length,
    [g, i]
  ), T = x(
    () => !r || lt(g, Array.from(a)),
    [r, g, a]
  ), S = r && T || w, { description: z, label: R } = e, H = D(() => {
    b(!1), t(
      $.openItemDetail({
        itemType: "group",
        label: R,
        description: z
      })
    );
  }, [b, t, R, z]), M = D(
    () => d(y),
    [d, y]
  ), _ = D(
    () => b(!0),
    [b]
  ), F = D(
    () => b(!1),
    [b]
  ), C = D(
    /**
     * If we don't stop propagation, users may unintentionally toggle dimensions/metrics
     * while interacting with the hovercard.
     */
    (N) => N.stopPropagation(),
    []
  ), A = x(
    () => /* @__PURE__ */ n(
      I,
      {
        icon: ys,
        size: 14,
        style: {
          margin: 1,
          transition: "transform 200ms ease",
          transform: S ? "rotate(90deg)" : "rotate(0deg)"
        }
      }
    ),
    [S]
  ), j = x(() => {
    if (p)
      return `${12 + (f ?? 0) * 20}px`;
  }, [f, p]);
  return T ? /* @__PURE__ */ n(
    Ye,
    {
      opened: S,
      onClick: M,
      disableRightSectionRotation: !0,
      rightSection: /* @__PURE__ */ n(se, {}),
      icon: A,
      onMouseEnter: _,
      onMouseLeave: F,
      pl: j,
      label: /* @__PURE__ */ E(ae, { children: [
        !w && u && /* @__PURE__ */ n(bs, { children: o }),
        /* @__PURE__ */ E(
          te,
          {
            openDelay: 300,
            keepMounted: !1,
            shadow: "sm",
            withinPortal: !0,
            withArrow: !0,
            disabled: !z,
            position: "right",
            offset: 80,
            children: [
              /* @__PURE__ */ n(te.Target, { children: /* @__PURE__ */ n(
                _t,
                {
                  component: Z,
                  truncate: !0,
                  highlight: s || "",
                  children: R
                }
              ) }),
              /* @__PURE__ */ n(
                te.Dropdown,
                {
                  hidden: !v,
                  p: "xs",
                  maw: 500,
                  onClick: C,
                  children: /* @__PURE__ */ n(
                    Rt,
                    {
                      onViewDescription: H,
                      description: z
                    }
                  )
                }
              )
            ]
          }
        )
      ] }),
      children: S && !p && /* @__PURE__ */ n(Yt, { nodeMap: e.children })
    }
  ) : null;
}, Ze = W(Wi);
Ze.displayName = "TreeGroupNode";
const Qi = ({
  item: e,
  sectionContexts: t,
  onToggleGroup: i,
  onSelectedFieldChange: r
}) => {
  const { node: s, isGroup: a, sectionKey: l, depth: m, isExpanded: c } = e.data, d = t.get(l), p = x(() => {
    if (!d)
      return {
        itemsMap: {},
        nodeMap: {},
        isSearching: !1,
        searchQuery: void 0,
        missingCustomMetrics: void 0,
        itemsAlerts: void 0,
        missingCustomDimensions: void 0,
        orderFieldsBy: void 0,
        isGithubIntegrationEnabled: !1,
        gitIntegration: void 0,
        onItemClick: () => {
        },
        searchResults: [],
        tableName: "",
        treeSectionType: L.Dimensions,
        expandedGroups: /* @__PURE__ */ new Set(),
        onToggleGroup: () => {
        }
      };
    const f = /* @__PURE__ */ new Set();
    return a && c && f.add(e.id), {
      itemsMap: d.itemsMap,
      nodeMap: d.nodeMap,
      isSearching: !!d.searchQuery && d.searchQuery !== "",
      searchQuery: d.searchQuery,
      missingCustomMetrics: d.missingCustomMetrics,
      itemsAlerts: d.itemsAlerts,
      missingCustomDimensions: d.missingCustomDimensions,
      orderFieldsBy: d.orderFieldsBy,
      isGithubIntegrationEnabled: d.isGithubIntegrationEnabled,
      gitIntegration: d.gitIntegration,
      onItemClick: (h) => {
        if (d.itemsMap[h]) {
          const b = d.sectionType === L.Dimensions || d.sectionType === L.CustomDimensions;
          r(h, b);
        }
      },
      searchResults: d.searchResults,
      tableName: d.tableName,
      treeSectionType: d.sectionType,
      expandedGroups: f,
      onToggleGroup: i,
      isVirtualized: !0,
      // Flag to prevent inline children rendering
      depth: m,
      // Nesting depth for indentation
      groupKey: a ? e.id : void 0
      // Pre-computed unique group key with parent path
    };
  }, [
    d,
    m,
    r,
    i,
    a,
    c,
    e.id
  ]);
  return d ? /* @__PURE__ */ n(Qt.Provider, { value: p, children: a && Fe(s) ? /* @__PURE__ */ n(Ze, { node: s }) : /* @__PURE__ */ n(Xe, { node: s }) }) : (console.error(`Section context not found for key: ${l}`), null);
}, Jt = W(Qi);
Jt.displayName = "VirtualTreeNode";
const Ki = ({
  item: e,
  sectionContexts: t,
  onToggleTable: i,
  onToggleGroup: r,
  onSelectedFieldChange: s
}) => {
  switch (e.type) {
    case "table-header":
      return /* @__PURE__ */ n(
        Wt,
        {
          item: e,
          onToggle: () => i(e.data.table.name)
        }
      );
    case "section-header":
      return /* @__PURE__ */ n(Ht, { item: e });
    case "missing-field":
      return /* @__PURE__ */ n(
        qt,
        {
          item: e,
          onRemove: s
        }
      );
    case "tree-node":
      return /* @__PURE__ */ n(
        Jt,
        {
          item: e,
          sectionContexts: t,
          onToggleGroup: r,
          onSelectedFieldChange: s
        }
      );
    case "empty-state":
      return /* @__PURE__ */ n(Ut, { item: e });
    default:
      return null;
  }
}, Xt = W(Ki);
Xt.displayName = "VirtualTreeItem";
const Yi = {
  components: {
    NavLink: {
      styles: (e) => ({
        root: {
          height: e.spacing.xxl,
          padding: `0 ${e.spacing.sm}`,
          flexGrow: 0
        },
        rightSection: {
          marginLeft: e.spacing.xxs
        }
      })
    }
  }
}, Ji = ({
  data: e,
  onToggleTable: t,
  onToggleGroup: i,
  onSelectedFieldChange: r
}) => {
  const { items: s, sectionContexts: a } = e, l = ut(null), m = ut(0), c = x(
    () => s.map(
      (b, y) => b.type === "table-header" ? y : -1
    ).filter((b) => b !== -1),
    [s]
  ), d = D(
    (b) => c.includes(b),
    [c]
  ), p = D(
    (b) => m.current === b,
    []
  ), f = D(
    (b) => {
      const y = [...c].reverse().find((w) => b.startIndex >= w);
      return y !== void 0 ? (m.current = y, [.../* @__PURE__ */ new Set([
        y,
        ...ct(b)
      ])].sort((g, u) => g - u)) : (m.current = -1, ct(b));
    },
    [c]
  ), h = Cs({
    count: s.length,
    getScrollElement: () => l.current,
    estimateSize: (b) => s[b].estimatedHeight,
    overscan: 5,
    // Render 5 extra items above and below viewport
    rangeExtractor: f
  }), v = h.getVirtualItems();
  return /* @__PURE__ */ n(vs, { inherit: !0, theme: Yi, children: /* @__PURE__ */ n(
    "div",
    {
      ref: l,
      "data-testid": "virtualized-tree-scroll-container",
      style: {
        height: "100%",
        overflow: "auto"
      },
      children: /* @__PURE__ */ n(
        "div",
        {
          style: {
            height: `${h.getTotalSize()}px`,
            width: "100%",
            position: "relative"
          },
          children: v.map((b) => {
            const y = s[b.index], w = d(b.index), g = p(
              b.index
            );
            return /* @__PURE__ */ n(
              "div",
              {
                "data-index": b.index,
                style: {
                  ...w ? {
                    zIndex: 1
                  } : {},
                  ...g ? {
                    position: "sticky"
                  } : {
                    position: "absolute",
                    transform: `translateY(${b.start}px)`
                  },
                  top: 0,
                  left: 0,
                  width: "100%"
                },
                children: /* @__PURE__ */ n(
                  Xt,
                  {
                    item: y,
                    sectionContexts: a,
                    onToggleTable: t,
                    onToggleGroup: i,
                    onSelectedFieldChange: r
                  }
                )
              },
              y.id
            );
          })
        }
      )
    }
  ) });
}, Zt = W(Ji);
Zt.displayName = "VirtualizedTreeList";
const Xi = ({
  explore: e,
  onSelectedFieldChange: t
}) => {
  const i = B(He), r = B(xt), s = B(
    (C) => ws(C, e)
  ), a = B(
    (C) => Es(C, e)
  ), l = B(
    (C) => Is(C, e)
  ), m = B(Nt), c = B(Ts), [d, p] = q(""), [f, h] = Qe(), [v, b] = q({}), [y] = Ss(d, 300), w = x(() => {
    const C = y.trim();
    return !!C && C !== "";
  }, [y]), g = x(() => $i(
    e,
    i,
    r
  ), [e, i, r]), u = D(
    (C) => {
      p(C.target.value);
    },
    []
  ), o = D(() => {
    p("");
  }, []), T = D(
    (C) => {
      const j = [
        ...Object.values({
          ...C.dimensions,
          ...C.metrics
        }),
        ...i
      ].reduce((N, we) => ({ ...N, [U(we)]: we }), {});
      return _i(j, y);
    },
    [i, y]
  );
  Ke(() => {
    h(() => {
      w && b(
        Object.values(e.tables).reduce(
          (C, A) => ({ ...C, [A.name]: T(A) }),
          {}
        )
      );
    });
  }, [e, w, T]);
  const V = x(() => Object.values(e.tables).sort((C, A) => C.name === e.baseTable ? -1 : A.name === e.baseTable ? 1 : C.label.localeCompare(A.label)).filter(
    (C) => !(w && v[C.name]?.length === 0) && !C.hidden
  ), [e, w, v]), [S, z] = q(() => {
    const C = V[0];
    return C ? /* @__PURE__ */ new Set([C.name]) : /* @__PURE__ */ new Set();
  }), [R, H] = q(
    /* @__PURE__ */ new Set()
  ), M = D((C) => {
    z((A) => {
      const j = new Set(A);
      return j.has(C) ? j.delete(C) : j.add(C), j;
    });
  }, []), _ = D((C) => {
    H((A) => {
      const j = new Set(A);
      return j.has(C) ? j.delete(C) : j.add(C), j;
    });
  }, []), F = x(() => Pi({
    tables: V,
    showMultipleTables: Object.keys(e.tables).length > 1,
    expandedTables: S,
    expandedGroups: R,
    searchQuery: y,
    searchResultsMap: v,
    isSearching: w,
    additionalMetrics: i,
    customDimensions: r ?? [],
    missingCustomMetrics: s,
    missingCustomDimensions: a,
    missingFieldIds: l,
    selectedDimensions: c,
    sectionNodeMaps: g
  }), [
    m,
    i,
    r,
    y,
    R,
    S,
    e.tables,
    w,
    a,
    s,
    l,
    v,
    g,
    c,
    V
  ]);
  return /* @__PURE__ */ E(se, { children: [
    /* @__PURE__ */ n(
      Ms,
      {
        icon: /* @__PURE__ */ n(I, { icon: xs }),
        rightSection: f ? /* @__PURE__ */ n(
          Ds,
          {
            size: "xs",
            "data-testid": "ExploreTree/SearchInput-Loader"
          }
        ) : d ? /* @__PURE__ */ n(re, { onClick: o, children: /* @__PURE__ */ n(I, { icon: ks }) }) : null,
        placeholder: "Search metrics + dimensions",
        value: d,
        onChange: u,
        "data-testid": "ExploreTree/SearchInput"
      }
    ),
    /* @__PURE__ */ n(
      Zt,
      {
        data: F,
        onToggleTable: M,
        onToggleGroup: _,
        onSelectedFieldChange: t
      }
    )
  ] });
}, en = W(Xi);
en.displayName = "ExploreTree";
const tn = W(({ onBack: e }) => {
  const { track: t } = Re(), { user: i } = qe(), [r, s] = q(!1), [a, l] = q(!1), [, m] = Qe(), c = Ue(), d = Vs(c ?? ""), { open: p } = hi(), { data: f } = As(
    We.EditYamlInUi
  ), h = B(Tt), v = B(He), y = B(Os)?.uuid, w = ge(), g = D(
    (_, F) => {
      w(F ? $.toggleDimension(_) : $.toggleMetric(_));
    },
    [w]
  ), u = B(
    _s
  ), {
    data: o,
    isFetching: T,
    status: V,
    error: S
  } = Ns(h);
  Ke(() => {
    if (c && i.data?.organizationUuid && o && v) {
      const _ = Rs({
        metrics: Fs(o),
        customMetrics: v
      }), F = Ps(
        _
      );
      F && (w(
        $.replaceFields({
          fieldsToReplace: {
            customMetrics: F
          }
        })
      ), t({
        name: Q.CUSTOM_FIELDS_REPLACEMENT_APPLIED,
        properties: {
          userId: i.data.userUuid,
          projectId: c,
          organizationId: i.data.organizationUuid,
          chartId: y,
          customMetricIds: Object.keys(F)
        }
      }));
    }
  }, [
    o,
    v,
    w,
    t,
    i,
    c,
    y
  ]);
  const z = D(() => {
    m(() => s(!0));
  }, []), R = D(() => {
    l(!0);
  }, []), H = D(() => {
    h && p({ explore: h });
  }, [p, h]), M = x(() => o ? e ? [
    { title: "Tables", onClick: e },
    { title: o.label, active: !0 }
  ] : [{ title: o.label, active: !0 }] : [], [e, o]);
  return T ? /* @__PURE__ */ n($s, {}) : o ? V === "error" && S.error.statusCode < 500 ? (e?.(), null) : /* @__PURE__ */ E(se, { children: [
    /* @__PURE__ */ n(
      dt,
      {
        id: Ls,
        sx: {
          flexGrow: 1,
          overflow: "hidden",
          display: u ? "flex" : "none"
        }
      }
    ),
    /* @__PURE__ */ E(
      dt,
      {
        h: "100%",
        sx: {
          flexGrow: 1,
          display: u ? "none" : "flex"
        },
        children: [
          /* @__PURE__ */ E(ae, { position: "apart", children: [
            /* @__PURE__ */ E(ae, { spacing: "xs", children: [
              /* @__PURE__ */ n(Qs, { size: "md", items: M }),
              o.warnings && o.warnings.length > 0 && /* @__PURE__ */ E(
                te,
                {
                  withinPortal: !0,
                  position: "right",
                  withArrow: !0,
                  radius: "md",
                  shadow: "subtle",
                  children: [
                    /* @__PURE__ */ n(te.Target, { children: /* @__PURE__ */ n(
                      re,
                      {
                        variant: "subtle",
                        color: "yellow",
                        size: "sm",
                        children: /* @__PURE__ */ n(
                          I,
                          {
                            icon: me,
                            color: "yellow.9"
                          }
                        )
                      }
                    ) }),
                    /* @__PURE__ */ n(te.Dropdown, { maw: 400, p: "xs", children: /* @__PURE__ */ n(
                      Ks,
                      {
                        type: "warnings",
                        warnings: o.warnings
                      }
                    ) })
                  ]
                }
              )
            ] }),
            o.type === Le.VIRTUAL && /* @__PURE__ */ n(
              $e,
              {
                I: "create",
                this: De("VirtualView", {
                  organizationUuid: i.data?.organizationUuid,
                  projectUuid: c
                }),
                children: /* @__PURE__ */ E(O, { withArrow: !0, offset: -2, children: [
                  /* @__PURE__ */ n(O.Target, { children: /* @__PURE__ */ n(re, { variant: "transparent", children: /* @__PURE__ */ n(I, { icon: Ve }) }) }),
                  /* @__PURE__ */ E(O.Dropdown, { children: [
                    /* @__PURE__ */ n(
                      O.Item,
                      {
                        leftSection: /* @__PURE__ */ n(I, { icon: js }),
                        onClick: z,
                        children: /* @__PURE__ */ n(Z, { fz: "xs", fw: 500, children: "Edit virtual view" })
                      }
                    ),
                    /* @__PURE__ */ n(
                      $e,
                      {
                        I: "delete",
                        this: De("VirtualView", {
                          organizationUuid: i.data?.organizationUuid,
                          projectUuid: c
                        }),
                        children: /* @__PURE__ */ n(
                          O.Item,
                          {
                            leftSection: /* @__PURE__ */ n(I, { icon: ye }),
                            color: "red",
                            onClick: R,
                            children: /* @__PURE__ */ n(Z, { fz: "xs", fw: 500, children: "Delete" })
                          }
                        )
                      }
                    )
                  ] })
                ] })
              }
            ),
            o.type !== Le.VIRTUAL && d && o.ymlPath && f?.enabled && /* @__PURE__ */ n(
              $e,
              {
                I: "view",
                this: De("SourceCode", {
                  organizationUuid: i.data?.organizationUuid,
                  projectUuid: c
                }),
                children: /* @__PURE__ */ E(O, { withArrow: !0, offset: -2, children: [
                  /* @__PURE__ */ n(O.Target, { children: /* @__PURE__ */ n(re, { variant: "transparent", children: /* @__PURE__ */ n(I, { icon: Ve }) }) }),
                  /* @__PURE__ */ n(O.Dropdown, { children: /* @__PURE__ */ n(
                    O.Item,
                    {
                      leftSection: /* @__PURE__ */ n(I, { icon: Ce }),
                      onClick: H,
                      children: /* @__PURE__ */ n(Z, { fz: "xs", fw: 500, children: "View source code" })
                    }
                  ) })
                ] })
              }
            )
          ] }),
          /* @__PURE__ */ n(Ys, { children: /* @__PURE__ */ n(
            en,
            {
              explore: o,
              onSelectedFieldChange: g
            }
          ) }),
          r && /* @__PURE__ */ n(
            Mi,
            {
              opened: r,
              onClose: () => s(!1),
              activeTableName: h,
              setIsEditVirtualViewOpen: s,
              explore: o
            }
          ),
          a && c && /* @__PURE__ */ n(
            Ti,
            {
              opened: a,
              onClose: () => l(!1),
              virtualViewName: h,
              projectUuid: c
            }
          )
        ]
      }
    )
  ] }) : null;
});
tn.displayName = "ExplorePanel";
const ar = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: tn
}, Symbol.toStringTag, { value: "Module" }));
export {
  rr as C,
  or as H,
  Pt as I,
  X as a,
  fi as b,
  ar as i,
  ir as u
};
//# sourceMappingURL=index-Cnox7AbF.mjs.map
