import { jsx as n, jsxs as w, Fragment as se } from "react/jsx-runtime";
import { ab as gn, ac as de, ad as fn, ae as je, af as yn, ag as ze, ah as bn, ai as Cn, aj as wt, 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 qe, ax as Et, 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 _e, S as J, aI as It, aJ as oe, aK as Ne, z as T, aL as Tt, aM as jn, T as G, aN as zn, U as ge, aO as B, aP as St, V as L, aQ as Bn, aR as Mt, aS as Ie, aT as He, aU as Dt, aV as Gn, aW as Un, E as ie, aX as qn, aY as Be, B as Hn, aZ as Wn, a_ as Qn, a$ as kt, b0 as Kn, b1 as xt, b2 as st, b3 as ye, b4 as Yn, b5 as Re, 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 We, o as Qe, bf as Fe, bg as Ke, bh as Vt, bi as Ge, bj as xe, 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 Ve, br as ss, bs as is, bt as rs, bu as it, y as O, bv as At, bw as Ot, bx as rt, I as ot, by as Ae, bz as os, $ as at, bA as lt, bB as as, bC as ls, bD as cs, bE as ds, bF as ct, 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 dt, bP as fs, bQ as ys, bR as bs, bS as ut, 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 mt, cc as Ls, C as Le, cd as js } from "./index-BJZQSU1O.mjs";
import K, { forwardRef as zs, createContext as Bs, useContext as Gs, useCallback as M, useTransition as Ye, useState as q, Suspense as Us, lazy as qs, useMemo as x, useEffect as Je, memo as W, useRef as pt } from "react";
import { c as Hs } from "./sqlRunnerSlice-C3O32avm.mjs";
import { T as Ws, I as Rt, P as Qs, W as Ks, a as Ys } from "./WarningsHoverCardContent-efIXLU-1.mjs";
const Js = (e, t, i, r, s) => {
  const l = new yn(r), c = r.getFieldQuoteChar(), m = i.reduce((g, h) => (g[h.reference] = {
    name: h.reference,
    label: de(h.reference),
    type: h.type ?? je.STRING,
    table: e,
    fieldType: fn.DIMENSION,
    sql: `${c}${h.reference}${c}`,
    tableLabel: de(e),
    hidden: !1
  }, g), {}), d = {
    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 {
    ...l.compileExplore({
      name: e,
      label: de(e),
      tags: [],
      baseTable: e,
      joinedTables: [],
      tables: { [e]: d },
      targetDatabase: r.getAdapterType(),
      meta: {}
    }),
    type: ze.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, l) => `INTERVAL '${s} ${l}'`,
    getTimestampDiffSeconds: (s, l) => `EXTRACT(EPOCH FROM (${l} - ${s}))`,
    getMedianSql: (s) => `PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ${s})`,
    buildArray: (s) => `ARRAY[${s.join(", ")}]`,
    buildArrayAgg: (s, l) => l ? `ARRAY_AGG(${s} ORDER BY ${l})` : `ARRAY_AGG(${s})`
  };
  return Js(e, t, i, r);
};
var Ft = wt("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 = wt("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, ht = Object.getOwnPropertySymbols, ni = Object.prototype.hasOwnProperty, si = Object.prototype.propertyIsEnumerable, gt = (e, t, i) => t in e ? Zs(e, t, { enumerable: !0, configurable: !0, writable: !0, value: i }) : e[t] = i, Ue = (e, t) => {
  for (var i in t || (t = {}))
    ni.call(t, i) && gt(e, i, t[i]);
  if (ht)
    for (var i of ht(t))
      si.call(t, i) && gt(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]": Ue({
      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: l }) => ({
  root: ii(Ue(Ue({
    display: "flex",
    alignItems: "center",
    width: "100%",
    padding: `${ke(8)} ${e.spacing.sm}`,
    userSelect: "none"
  }, oi({ theme: e, variant: l, 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, Oe = Object.getOwnPropertySymbols, $t = Object.prototype.hasOwnProperty, Lt = Object.prototype.propertyIsEnumerable, ft = (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) && ft(e, i, t[i]);
  if (Oe)
    for (var i of Oe(t))
      Lt.call(t, i) && ft(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 && Oe)
    for (var r of Oe(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: l,
    rightSection: c,
    className: m,
    classNames: d,
    styles: u,
    unstyled: p,
    active: g,
    color: h,
    variant: C,
    noWrap: y,
    children: f,
    opened: v,
    defaultOpened: E,
    onChange: a,
    disableRightSectionRotation: o,
    childrenOffset: k,
    disabled: V,
    onClick: I
  } = i, $ = di(i, [
    "label",
    "description",
    "icon",
    "rightSection",
    "className",
    "classNames",
    "styles",
    "unstyled",
    "active",
    "color",
    "variant",
    "noWrap",
    "children",
    "opened",
    "defaultOpened",
    "onChange",
    "disableRightSectionRotation",
    "childrenOffset",
    "disabled",
    "onClick"
  ]), { classes: _, cx: H } = ai({ color: h, noWrap: y, childrenOffset: k, alignIcon: s ? "top" : "center" }, { name: "NavLink", classNames: d, styles: u, unstyled: p, variant: C }), [S, N] = Tn({
    value: v,
    defaultValue: E,
    finalValue: !1,
    onChange: a
  }), F = !!f, b = (A) => {
    F ? (A.preventDefault(), I?.(A), N(!S)) : I?.(A);
  };
  return /* @__PURE__ */ K.createElement(K.Fragment, null, /* @__PURE__ */ K.createElement(Sn, ci({
    ref: t,
    className: H(_.root, m),
    "data-active": g || void 0,
    onClick: b,
    unstyled: p,
    "data-expanded": S || void 0,
    "data-disabled": V || void 0,
    disabled: V
  }, $), l && /* @__PURE__ */ K.createElement("span", {
    className: _.icon
  }, l), /* @__PURE__ */ K.createElement("span", {
    className: _.body
  }, /* @__PURE__ */ K.createElement(Z, {
    component: "span",
    size: "sm",
    className: _.label
  }, r), /* @__PURE__ */ K.createElement(Z, {
    component: "span",
    color: "dimmed",
    size: "xs",
    "data-active": g || void 0,
    className: _.description
  }, s)), (F || c) && /* @__PURE__ */ K.createElement("span", {
    className: _.rightSection,
    "data-rotate": S && !o || void 0
  }, F ? c || /* @__PURE__ */ K.createElement(Mn, {
    width: ke(14),
    height: ke(14),
    style: { transform: "rotate(-90deg)" }
  }) : c)), /* @__PURE__ */ K.createElement(Dn, {
    in: S
  }, /* @__PURE__ */ K.createElement("div", {
    className: _.children
  }, f)));
});
jt.displayName = "@mantine/core/NavLink";
const Xe = 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 = Et(), { 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 = qe(), i = Et(), { 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)
}), yt = "create-virtual-view-form", rr = ({ opened: e, onClose: t }) => {
  const i = _n(), r = X((v) => v.sqlRunner.projectUuid), s = X((v) => v.sqlRunner.sql), l = X((v) => v.sqlRunner.sqlColumns), c = X((v) => v.sqlRunner.name), {
    mutateAsync: m,
    isLoading: d,
    error: u
  } = bi({
    projectUuid: r
  }), p = Nn({
    initialValues: {
      name: c || ""
    },
    validate: Rn(Ii)
  }), { data: g } = Pn(r), { data: h, isError: C } = fi(), y = !!(i.data?.hasGithub && h?.enabled === !0 && !C && g?.dbtConnection.type === $n.GITHUB), f = M(
    async (v) => {
      l && (await m({
        name: Ln(v.name),
        sql: s,
        columns: l,
        projectUuid: r
      }), t());
    },
    [l, t, r, s, m]
  );
  return /* @__PURE__ */ n(
    _e,
    {
      opened: e,
      onClose: t,
      title: "Create virtual view",
      icon: Pt,
      size: "md",
      cancelDisabled: d,
      headerActions: /* @__PURE__ */ n(
        Ne,
        {
          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. ${y ? "If you're expecting to reuse this query regularly, we suggest writing it back to dbt." : ""} `,
          children: /* @__PURE__ */ n(T, { color: "ldGray.7", icon: Tt })
        }
      ),
      actions: /* @__PURE__ */ n(
        oe,
        {
          type: "submit",
          form: yt,
          disabled: !p.values.name || !s,
          loading: d,
          children: "Create"
        }
      ),
      children: /* @__PURE__ */ n("form", { id: yt, onSubmit: p.onSubmit(f), children: /* @__PURE__ */ n(J, { children: /* @__PURE__ */ n(
        It,
        {
          label: "Name",
          required: !0,
          ...p.getInputProps("name"),
          error: !!u?.error
        }
      ) }) })
    }
  );
}, Ti = ({
  opened: e,
  onClose: t,
  virtualViewName: i,
  projectUuid: r
}) => {
  const { mutate: s, isLoading: l } = Ei(r);
  return /* @__PURE__ */ n(
    _e,
    {
      opened: e,
      onClose: t,
      title: "Delete virtual view",
      variant: "delete",
      resourceType: "virtual view",
      resourceLabel: i,
      onConfirm: () => {
        s({ projectUuid: r, name: i }), t();
      },
      confirmLoading: l,
      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-D3m7EyTg.mjs")), Mi = ({
  opened: e,
  onClose: t,
  activeTableName: i,
  explore: r
}) => {
  const s = !!zn("create_saved_chart_version"), [l, c] = Ye(), m = ge(), d = qe(), u = B(St), [p, g] = q(s ? "unsavedChanges" : "editVirtualView"), h = M(() => {
    m(
      L.clearQuery({
        defaultState: Bn,
        tableName: u
      })
    ), d({ search: "" }, { replace: !0 });
  }, [m, u, d]), C = () => {
    p === "editVirtualView" && (g(void 0), t());
  };
  return p === "unsavedChanges" ? /* @__PURE__ */ n(
    _e,
    {
      opened: e,
      onClose: t,
      title: "You have unsaved changes",
      icon: Mt,
      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: () => {
            c(() => {
              h(), g("editVirtualView");
            });
          },
          loading: l,
          children: "Discard & continue"
        }
      )
    }
  ) : /* @__PURE__ */ w(
    Ie.Root,
    {
      opened: e && p === "editVirtualView",
      onClose: C,
      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(He, { h: "95vh", w: "95vw", children: /* @__PURE__ */ w(J, { align: "center", justify: "center", children: [
              /* @__PURE__ */ n(Dt, { 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: (c) => ki(e, c),
    onSuccess: (c, m) => {
      s(!0), Gn(c.jobId).then(async () => {
        const d = await Di(
          e,
          !1,
          c.jobId
        );
        await m.onComplete(d);
      }).catch((d) => {
        t({
          title: "Unable to get validation",
          subtitle: d.message
        });
      }).finally(() => {
        s(!1);
      });
    },
    onError: ({ error: c }) => {
      i({
        title: "Failed to get validation",
        apiError: c
      }), 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 l = t.find(
      (c) => c.reference === s.reference
    );
    if (l) {
      if (l.type !== s.type)
        return [
          ...r,
          {
            reference: s.reference,
            type: "typeChanged",
            oldType: s.type,
            newType: l.type
          }
        ];
    } else return [
      ...r,
      { reference: s.reference, type: "deleted" }
    ];
    return r;
  }, []);
  return t.forEach((r) => {
    e.find(
      (l) => l.reference === r.reference
    ) || i.push({
      reference: r.reference,
      type: "added"
    });
  }), i?.sort((r, s) => r.type.localeCompare(s.type));
}, bt = W(({ diff: e }) => /* @__PURE__ */ w(ie, { gap: "xs", wrap: "nowrap", children: [
  /* @__PURE__ */ n(
    T,
    {
      icon: e.type === "deleted" ? ye : Ft,
      color: e.type === "deleted" ? "red" : "yellow",
      size: 16
    }
  ),
  e.type === "deleted" ? /* @__PURE__ */ w(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__ */ w(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 })
  ] })
] })), Ct = ({ chartErrors: e, projectUuid: t }) => {
  const i = e[0], r = e.map((s) => s.error);
  return /* @__PURE__ */ w(ie, { gap: "xs", wrap: "nowrap", children: [
    /* @__PURE__ */ n(T, { icon: Ft, color: "orange", size: 16 }),
    /* @__PURE__ */ n(
      Ne,
      {
        variant: "xs",
        withinPortal: !0,
        label: /* @__PURE__ */ n(J, { gap: 2, children: r.map((s, l) => /* @__PURE__ */ n(G, { fz: 11, children: s }, l)) }),
        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 l = X((a) => a.sqlRunner.projectUuid), c = i.filter(
    (a) => a.type === "added"
  ).length, m = i.filter((a) => a.type !== "added"), d = m.length > 3, [u, p] = q(!1), g = m.slice(0, 3), h = x(() => r ? Kn(
    r.filter(
      (a) => kt(a)
    ),
    "chartUuid"
  ) : {}, [r]), C = Object.entries(h), y = C.length > 3, [f, v] = q(!1), E = C.slice(0, 3);
  return /* @__PURE__ */ n(
    _e,
    {
      opened: e,
      onClose: t,
      title: "Schema changes detected",
      icon: Mt,
      actions: /* @__PURE__ */ n(oe, { color: "orange", onClick: s, children: "Save Anyway" }),
      children: /* @__PURE__ */ w(J, { gap: "md", children: [
        /* @__PURE__ */ w(J, { gap: "xs", children: [
          /* @__PURE__ */ n(G, { fz: "sm", fw: 500, c: "ldGray.7", children: "Column changes" }),
          /* @__PURE__ */ n(Be, { p: "sm", radius: "md", withBorder: !0, bg: "ldGray.0", children: /* @__PURE__ */ w(J, { gap: "xs", children: [
            c > 0 && /* @__PURE__ */ w(ie, { gap: "xs", children: [
              /* @__PURE__ */ n(
                T,
                {
                  icon: xt,
                  color: "green",
                  size: 16
                }
              ),
              /* @__PURE__ */ w(G, { fz: "sm", c: "ldGray.7", children: [
                c,
                " new column",
                c > 1 ? "s" : "",
                " added"
              ] })
            ] }),
            g.map((a, o) => /* @__PURE__ */ n(bt, { diff: a }, o)),
            /* @__PURE__ */ n(st, { in: u, children: m.slice(3).map((a, o) => /* @__PURE__ */ n(bt, { diff: a }, o + 3)) }),
            d && /* @__PURE__ */ n(
              oe,
              {
                size: "compact-xs",
                variant: "subtle",
                color: "ldGray.6",
                onClick: () => p(!u),
                children: u ? "Show less" : `Show ${m.length - 3} more`
              }
            )
          ] }) })
        ] }),
        C.length > 0 && /* @__PURE__ */ w(J, { gap: "xs", children: [
          /* @__PURE__ */ w(G, { fz: "sm", fw: 500, c: "ldGray.7", children: [
            "Affected charts (",
            C.length,
            ")"
          ] }),
          /* @__PURE__ */ n(Be, { p: "sm", radius: "md", withBorder: !0, bg: "ldGray.0", children: /* @__PURE__ */ w(J, { gap: "xs", children: [
            E.map(
              ([a, o]) => /* @__PURE__ */ n(
                Ct,
                {
                  chartErrors: o,
                  projectUuid: l
                },
                a
              )
            ),
            /* @__PURE__ */ n(st, { in: f, children: C.slice(3).map(([a, o]) => /* @__PURE__ */ n(
              Ct,
              {
                chartErrors: o,
                projectUuid: l
              },
              a
            )) }),
            y && /* @__PURE__ */ n(
              oe,
              {
                size: "compact-xs",
                variant: "subtle",
                color: "gray",
                onClick: () => v(
                  !f
                ),
                children: f ? "Show less" : `Show ${C.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((S) => S.sqlRunner.sqlColumns), [l, c] = q([]), [m, d] = q(void 0), [u, p] = q(!1), g = qe(), h = X((S) => S.sqlRunner.sql), C = X((S) => S.sqlRunner.projectUuid), y = X(
    (S) => S.sqlRunner.warehouseConnectionType
  ), f = x(
    () => Hs(
      e.sql,
      h,
      y
    ),
    [h, e.sql, y]
  ), { mutateAsync: v, isPolling: E } = xi(C), { mutateAsync: a, isLoading: o } = Vi(C), { mutateAsync: k, isLoading: V } = vi(C);
  Je(() => {
    s && (i || r(s));
  }, [i, s]);
  const [I, $] = q(
    e.label || de(e.name)
  ), _ = async ({
    handleDiff: S
  }) => {
    console.log("[VirtualView Debug] handleUpdateVirtualView called", {
      handleDiff: S,
      virtualViewName: e.name,
      sql: h.substring(0, 100) + "..."
    });
    let N;
    try {
      const b = await a({ sql: h, limit: 1 });
      if (b)
        N = b.columns;
      else {
        t({
          title: "Error running query",
          subtitle: "No results returned"
        });
        return;
      }
    } catch (b) {
      Wn(b) && t({
        title: "Error running query",
        subtitle: b.error.message
      });
      return;
    }
    if (!N)
      return t({
        title: "Error running query",
        subtitle: "No columns returned"
      });
    if (console.log("[VirtualView Debug] Columns from query:", {
      columnsFromQuery: N,
      initialColumns: i
    }), !S)
      return await k({
        exploreName: e.name,
        projectUuid: C,
        name: I,
        sql: h,
        columns: N
      }), g(0);
    const F = Xs(
      e.name,
      h,
      N
    );
    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 v({
      explores: [F],
      validationTargets: [Qn.CHARTS],
      onlyValidateExploresInArgs: !0,
      onComplete: async (b) => {
        if (console.log("[VirtualView Debug] Validation response:", {
          responseLength: b.length,
          response: b,
          chartErrors: b.filter(
            (A) => kt(A)
          )
        }), b.length === 0)
          console.log(
            "[VirtualView Debug] No validation errors, saving directly"
          ), await k({
            exploreName: e.name,
            projectUuid: C,
            name: I,
            sql: h,
            columns: N
          }), g(0);
        else if (console.log(
          "[VirtualView Debug] Has validation errors, checking diffs",
          { handleDiff: S, hasInitialColumns: !!i }
        ), S && i) {
          d(b);
          const A = Ai(
            i,
            N
          );
          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 k({
            exploreName: e.name,
            projectUuid: C,
            name: I,
            sql: h,
            columns: N
          }), g(0)) : (console.log(
            "[VirtualView Debug] Showing warning modal with:",
            {
              columnDiffs: A,
              chartValidationErrors: b
            }
          ), c(A), p(!0));
        }
      }
    });
  }, H = x(() => I !== e.label || f, [I, e.label, f]);
  return /* @__PURE__ */ w(
    ie,
    {
      p: "md",
      py: "xs",
      justify: "space-between",
      className: "border-b border-ldGray-3",
      children: [
        /* @__PURE__ */ n(
          qn,
          {
            visible: E || o || V,
            loaderProps: {
              children: /* @__PURE__ */ n(He, { h: "95vh", w: "95vw", children: /* @__PURE__ */ w(J, { align: "center", justify: "center", children: [
                /* @__PURE__ */ n(Dt, {}),
                /* @__PURE__ */ n(G, { fw: 500, children: "Validating your changes..." })
              ] }) })
            }
          }
        ),
        /* @__PURE__ */ n(ie, { gap: "xs", children: /* @__PURE__ */ w(ie, { gap: "xs", children: [
          /* @__PURE__ */ n(Be, { p: "xxs", withBorder: !0, radius: "sm", children: /* @__PURE__ */ n(T, { icon: Pt }) }),
          "Editing",
          /* @__PURE__ */ n(
            It,
            {
              fz: "sm",
              fw: 500,
              value: I,
              onChange: (S) => $(S.currentTarget.value)
            }
          )
        ] }) }),
        /* @__PURE__ */ w(ie, { gap: "sm", children: [
          /* @__PURE__ */ n(
            Ne,
            {
              variant: "xs",
              label: "No changes to save",
              disabled: H,
              children: /* @__PURE__ */ n(Hn, { children: /* @__PURE__ */ n(
                oe,
                {
                  size: "xs",
                  disabled: E || o || !H,
                  onClick: () => _({ handleDiff: !0 }),
                  color: "green",
                  children: "Save"
                }
              ) })
            }
          ),
          /* @__PURE__ */ n(
            oe,
            {
              size: "xs",
              variant: "default",
              onClick: () => {
                e.onCloseEditVirtualView();
              },
              children: "Cancel"
            }
          )
        ] }),
        /* @__PURE__ */ n(
          Oi,
          {
            opened: u,
            onSave: () => _({ handleDiff: !1 }),
            onClose: () => p(!1),
            columnDiffs: l,
            chartValidationErrors: m
          }
        )
      ]
    }
  );
}, vt = 3, Ze = (e, t) => (i, r) => {
  if (e === Re.INDEX)
    return i.index - r.index;
  const s = t[i.key], l = t[r.key];
  return ee(s) && ee(l) && s.timeInterval && l.timeInterval ? Jn(s.timeInterval, l.timeInterval) : i.label.localeCompare(r.label);
}, Pe = (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, l, c) => {
  if (i.length === 0)
    return {
      ...e,
      [t.key]: t
    };
  const [m, ...d] = i, u = r[m] || {
    label: m
  }, p = u.label, g = e[p];
  if (g && !Pe(g))
    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 = g || {
    key: p,
    label: p,
    description: u.description ?? "",
    children: {},
    index: t.index ?? Number.MAX_SAFE_INTEGER
  }, C = s && d.length === 0 ? {
    ...h.children || {},
    [t.key]: t
  } : zt(
    h.children || {},
    t,
    d,
    r,
    s,
    l,
    c
  ), f = Object.values(C).sort(
    Ze(l, c)
  ).reduce(
    (E, a) => ({
      ...E,
      [a.key]: a
    }),
    {}
  ), v = {
    ...h,
    children: f
  };
  return {
    ...e,
    [p]: v
  };
}, Te = (e, t = {}, i = Re.LABEL) => Object.entries(e).filter(
  ([s, l]) => be(l) ? !0 : !l.hidden
).reduce((s, [l, c]) => {
  const m = be(c) ? {
    key: l,
    label: c.name,
    index: Number.MAX_SAFE_INTEGER
  } : {
    key: l,
    label: c.label || c.name,
    index: c.index ?? Number.MAX_SAFE_INTEGER
  };
  if (!fe(c))
    return {
      ...s,
      [m.key]: m
    };
  if (Ni(c))
    return s;
  let d = [...c.groups || []], u = !1;
  if (c.groupLabel && d.push(c.groupLabel), ee(c) && c.group) {
    const g = U({
      table: c.table,
      name: c.group
    });
    d.push(g), u = !0;
  }
  const p = d.slice(0, vt);
  return d.length > vt && ee(c) && c.timeInterval && p.push(d[d.length - 1]), zt(
    s,
    m,
    p,
    t,
    u,
    i,
    e
  );
}, {});
var j = /* @__PURE__ */ ((e) => (e.Dimensions = "dimensions", e.Metrics = "metrics", e.CustomMetrics = "custom-metrics", e.CustomDimensions = "custom-dimensions", e.MissingFields = "missing-fields", e))(j || {});
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, l, c, m = 0, d = "") {
  const u = [], p = !c || l.includes(e.key), g = Pe(e);
  if (!p && !g) return u;
  if (g) {
    const h = e;
    if (!Object.values(h.children).some(
      (v) => !c || l.includes(v.key) || "children" in v && v.children && Object.values(v.children).some(
        (E) => l.includes(E.key)
      )
    ) && c)
      return u;
    const y = Bt(
      r,
      i,
      e.key,
      d
    ), f = s.has(y) || c;
    if (u.push({
      id: y,
      type: "tree-node",
      estimatedHeight: Y.TREE_GROUP_NODE,
      data: {
        node: e,
        isGroup: !0,
        isExpanded: f,
        sectionKey: t,
        depth: m
      }
    }), f) {
      const v = d ? `${d}-${e.key}` : e.key;
      Object.values(h.children).forEach((E) => {
        u.push(
          ...Gt(
            E,
            t,
            i,
            r,
            s,
            l,
            c,
            m + 1,
            v
          )
        );
      });
    }
  } else
    u.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 u;
}
function Se(e, t, i, r, s, l, c, m = 0) {
  const d = `${t}-${e.type}`, u = l.sectionNodeMaps.get(d);
  if (!u)
    return [];
  const p = Ri(t, e.type), g = {
    tableName: t,
    sectionType: e.type,
    itemsMap: e.itemsMap,
    nodeMap: u,
    // Store the pre-computed nodeMap
    missingCustomMetrics: e.type === j.CustomMetrics && e.missingItems ? e.missingItems.filter((f) => ue(f)) : void 0,
    missingCustomDimensions: e.type === j.CustomDimensions && e.missingItems ? e.missingItems.filter((f) => be(f)) : void 0,
    itemsAlerts: e.itemsAlerts,
    orderFieldsBy: e.orderFieldsBy,
    isGithubIntegrationEnabled: l.isGithubIntegrationEnabled,
    gitIntegration: l.gitIntegration,
    searchQuery: l.searchQuery,
    searchResults: r
  };
  c.set(p, g);
  const h = [], C = e.orderFieldsBy ?? Re.LABEL;
  return Object.values(u).sort(
    Ze(C, e.itemsMap)
  ).forEach((f) => {
    h.push(
      ...Gt(
        f,
        p,
        e.type,
        t,
        i,
        r,
        s,
        m
      )
    );
  }), h;
}
function Fi(e, t, i) {
  const r = [], s = e.name, l = t.expandedTables.has(s) || t.isSearching, c = 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: l
    }
  }), !l)
    return r;
  const d = t.missingFieldIds;
  d.length > 0 && (r.push({
    id: `${s}-section-missing`,
    type: "section-header",
    estimatedHeight: Y.SECTION_HEADER,
    data: {
      tableName: s,
      treeSection: j.MissingFields,
      // Arbitrary, missing fields aren't tied to a section
      label: "Missing fields",
      color: "ldGray.6",
      depth: m
    }
  }), d.forEach((a) => {
    r.push({
      id: `${s}-missing-${a}`,
      type: "missing-field",
      estimatedHeight: Y.MISSING_FIELD,
      data: {
        fieldId: a,
        tableName: s,
        isDimension: t.selectedDimensions.includes(a)
      }
    });
  }));
  const u = (a) => a.length > 0, p = Object.values(e.dimensions).reduce(
    (a, o) => ({ ...a, [U(o)]: o }),
    {}
  ), g = Object.keys(p).length > 0;
  if ((g || !t.isSearching && !g || t.isSearching && c.length > 0) && r.push({
    id: `${s}-section-dimensions`,
    type: "section-header",
    estimatedHeight: Y.SECTION_HEADER,
    data: {
      tableName: s,
      treeSection: j.Dimensions,
      label: "Dimensions",
      color: ne.dimension.color,
      depth: m
    }
  }), g) {
    const a = Se(
      {
        type: j.Dimensions,
        color: ne.dimension.color,
        itemsMap: p,
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      c,
      t.isSearching,
      t,
      i,
      m
    );
    (u(a) || !t.isSearching) && r.push(...a);
  } else t.isSearching || r.push({
    id: `${s}-empty-dimensions`,
    type: "empty-state",
    estimatedHeight: Y.EMPTY_STATE,
    data: {
      tableName: s,
      treeSection: j.Dimensions,
      message: "No dimensions defined in your dbt project"
    }
  });
  const h = Object.values(e.metrics).reduce(
    (a, o) => ({ ...a, [U(o)]: o }),
    {}
  ), C = Object.keys(h).length > 0;
  if ((C || !t.isSearching && !C || t.isSearching && c.length > 0) && r.push({
    id: `${s}-section-metrics`,
    type: "section-header",
    estimatedHeight: Y.SECTION_HEADER,
    data: {
      tableName: s,
      treeSection: j.Metrics,
      label: "Metrics",
      color: ne.metric.color,
      depth: m,
      helpButton: C ? 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."
      }
    }
  }), C) {
    const a = Se(
      {
        type: j.Metrics,
        color: ne.metric.color,
        itemsMap: h,
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      c,
      t.isSearching,
      t,
      i,
      m
    );
    (u(a) || !t.isSearching) && r.push(...a);
  }
  const f = [
    ...t.additionalMetrics.filter(
      (a) => a.table === s
    ),
    ...t.missingCustomMetrics.filter((a) => a.table === s)
  ].reduce((a, o) => ({ ...a, [U(o)]: o }), {});
  if (Object.keys(f).length > 0) {
    r.push({
      id: `${s}-section-custom-metrics`,
      type: "section-header",
      estimatedHeight: Y.SECTION_HEADER,
      data: {
        tableName: s,
        treeSection: j.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 a = t.additionalMetrics.reduce(
      (k, V) => {
        const I = Object.keys(h).includes(
          U(V)
        );
        return {
          ...k,
          [U(V)]: {
            errors: I ? [
              {
                message: "A metric with this ID already exists in the table. Rename your custom metric to prevent conflicts."
              }
            ] : void 0
          }
        };
      },
      {}
    ), o = Se(
      {
        type: j.CustomMetrics,
        color: ne.metric.color,
        itemsMap: f,
        missingItems: t.missingCustomMetrics.filter(
          (k) => k.table === s
        ),
        itemsAlerts: a,
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      c,
      t.isSearching,
      t,
      i,
      m
    );
    r.push(...o);
  }
  const E = (t.customDimensions?.filter((a) => a.table === s) || []).reduce(
    (a, o) => ({ ...a, [U(o)]: o }),
    {}
  );
  if (Object.keys(E).length > 0) {
    r.push({
      id: `${s}-section-custom-dimensions`,
      type: "section-header",
      estimatedHeight: Y.SECTION_HEADER,
      data: {
        tableName: s,
        treeSection: j.CustomDimensions,
        label: "Custom dimensions",
        color: ne.dimension.color,
        depth: m
      }
    });
    const a = Se(
      {
        type: j.CustomDimensions,
        color: ne.dimension.color,
        itemsMap: E,
        missingItems: t.missingCustomDimensions.filter(
          (o) => o.table === s
        ),
        orderFieldsBy: e.orderFieldsBy
      },
      s,
      t.expandedGroups,
      c,
      t.isSearching,
      t,
      i,
      m
    );
    r.push(...a);
  }
  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 l = s.name, c = Object.fromEntries(
      Object.values(s.dimensions).map((p) => [U(p), p])
    );
    Object.keys(c).length > 0 && r.set(
      `${l}-dimensions`,
      Te(
        c,
        s.groupDetails,
        s.orderFieldsBy
      )
    );
    const m = Object.fromEntries(
      Object.values(s.metrics).map((p) => [U(p), p])
    );
    Object.keys(m).length > 0 && r.set(
      `${l}-metrics`,
      Te(
        m,
        s.groupDetails,
        s.orderFieldsBy
      )
    );
    const d = t.filter(
      (p) => p.table === l
    );
    if (d.length > 0) {
      const p = Object.fromEntries(
        d.map((g) => [U(g), g])
      );
      r.set(
        `${l}-custom-metrics`,
        Te(
          p,
          s.groupDetails,
          s.orderFieldsBy
        )
      );
    }
    const u = i?.filter((p) => p.table === l) || [];
    if (u.length > 0) {
      const p = Object.fromEntries(
        u.map((g) => [U(g), g])
      );
      r.set(
        `${l}-custom-dimensions`,
        Te(
          p,
          s.groupDetails,
          s.orderFieldsBy
        )
      );
    }
  }), r;
}
const Li = ({ item: e }) => {
  const { message: t } = e.data;
  return /* @__PURE__ */ n(He, { 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 = M(() => {
    t(i, r);
  }, [t, i, r]);
  return /* @__PURE__ */ w(
    ie,
    {
      ml: 32,
      mr: 16,
      my: "xs",
      gap: "xs",
      wrap: "nowrap",
      style: { overflow: "hidden" },
      children: [
        /* @__PURE__ */ n(
          T,
          {
            icon: me,
            color: "yellow.9",
            style: { flexShrink: 0 }
          }
        ),
        /* @__PURE__ */ n(G, { truncate: !0, size: "sm", style: { flex: 1, minWidth: 0 }, children: i }),
        /* @__PURE__ */ n(
          Ne,
          {
            withinPortal: !0,
            label: /* @__PURE__ */ w(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(T, { 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: l, helpButton: c } = e.data, m = We(), { user: d } = Qe(), { track: u } = Fe(), p = ge(), g = B(Ke), h = B(Vt), C = Ge(
    xe.WriteBackCustomBinDimensions
  ), y = x(() => h ? C ? h : h.filter(Me) : [], [h, C]), f = d.data?.ability?.can(
    "manage",
    De("CustomSql", {
      organizationUuid: d.data.organizationUuid,
      projectUuid: m
    })
  ), v = M(() => {
    p(
      L.toggleCustomDimensionModal({
        isEditing: !1,
        table: s,
        item: void 0
      })
    );
  }, [p, s]), E = M(() => {
    m && d.data?.organizationUuid && u({
      name: Q.WRITE_BACK_FROM_CUSTOM_METRIC_HEADER_CLICKED,
      properties: {
        userId: d.data.userUuid,
        projectId: m,
        organizationId: d.data.organizationUuid,
        customMetricsCount: g?.length || 0,
        customDimensionsCount: 0
      }
    }), p(
      L.toggleWriteBackModal({
        items: g
      })
    );
  }, [m, d.data, g, p, u]), a = M(() => {
    m && d.data?.organizationUuid && u({
      name: Q.WRITE_BACK_FROM_CUSTOM_DIMENSION_HEADER_CLICKED,
      properties: {
        userId: d.data.userUuid,
        projectId: m,
        organizationId: d.data.organizationUuid,
        customMetricsCount: 0,
        customDimensionsCount: y?.length || 0
      }
    }), p(
      L.toggleWriteBackModal({
        items: y || []
      })
    );
  }, [m, d.data, y, p, u]), o = x(() => r ? `${r * 20}px` : void 0, [r]), k = l === j.Dimensions && f, V = l === j.CustomMetrics && g && g.length > 0, I = l === j.CustomDimensions && y.length > 0;
  return /* @__PURE__ */ w(ae, { mt: "sm", mb: "xs", pl: o, pr: "sm", position: "apart", children: [
    /* @__PURE__ */ w(ae, { spacing: "xs", children: [
      /* @__PURE__ */ n(Z, { fw: 600, c: i, children: t }),
      c && /* @__PURE__ */ n(
        es,
        {
          href: c.href,
          tooltipProps: {
            label: c.tooltipText,
            multiline: !0
          }
        }
      )
    ] }),
    /* @__PURE__ */ w(ae, { spacing: "xs", children: [
      k && /* @__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(T, { icon: xt }),
              onClick: v,
              "data-testid": "VirtualSectionHeader/AddCustomDimensionButton",
              children: "Add"
            }
          )
        }
      ),
      V && /* @__PURE__ */ n(le, { label: "Write back custom metrics", children: /* @__PURE__ */ n(
        re,
        {
          onClick: E,
          "data-testid": "VirtualSectionHeader/WriteBackCustomMetricsButton",
          children: /* @__PURE__ */ n(T, { icon: Ce })
        }
      ) }),
      I && /* @__PURE__ */ n(le, { label: "Write back custom dimensions", children: /* @__PURE__ */ n(
        re,
        {
          onClick: a,
          "data-testid": "VirtualSectionHeader/WriteBackCustomDimensionsButton",
          children: /* @__PURE__ */ n(T, { icon: Ce })
        }
      ) })
    ] })
  ] });
}, Ht = W(zi);
Ht.displayName = "VirtualSectionHeader";
const Bi = ({
  item: e,
  onToggle: t
}) => {
  const i = ns(), { table: r, isExpanded: s } = e.data, [l, c] = Ve(!1), m = M(
    () => c(!0),
    [c]
  ), d = M(
    () => c(!1),
    [c]
  ), u = M(
    () => c(!1),
    [c]
  ), p = x(
    () => ({
      top: 0,
      position: "sticky",
      backgroundColor: i.colorScheme === "dark" ? i.colors.dark[7] : i.colors.background[0],
      zIndex: 1
    }),
    [i.colorScheme, i.colors]
  ), g = /* @__PURE__ */ n(
    Ws,
    {
      label: r.label,
      description: r.description,
      showPreview: l,
      closePreview: u,
      children: /* @__PURE__ */ n(Z, { truncate: !0, fw: 600, children: r.label })
    }
  );
  return /* @__PURE__ */ n(
    Xe,
    {
      opened: s,
      onClick: t,
      onMouseEnter: m,
      onMouseLeave: d,
      icon: /* @__PURE__ */ n(T, { icon: ss, size: "lg", color: "ldGray.7" }),
      label: g,
      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: l,
  onViewDescription: c
}) => {
  const m = We(), { user: d } = Qe(), { showToastSuccess: u } = he(), { addFilter: p } = rs(), { track: g } = Fe(), h = ge(), C = x(() => Me(e) ? it(e.dimensionType) : ee(e) ? it(e.type) : [], [e]), y = Ge(
    xe.WriteBackCustomBinDimensions
  ), f = Ge(
    xe.CustomGroupBins
  ), v = (a) => {
    const o = JSON.parse(JSON.stringify(a));
    let k = lt(), V = k.replace(/-/g, "").substring(0, 16), I = o.name;
    const $ = "_8id9_", _ = I.indexOf($);
    _ !== -1 ? I = I.substring(0, _ + $.length) + V : I = I + $ + V, o.label = "Copy " + o.label, o.uuid = k, o.name = I, h(L.addAdditionalMetric(o));
  }, E = (a) => {
    const o = JSON.parse(JSON.stringify(a));
    let k = lt().replace(/-/g, "").substring(0, 16), V = o.id;
    const I = "_8id9_", $ = V.indexOf(I);
    $ !== -1 ? V = V.substring(0, $ + I.length) + k : V = V + I + k, o.name = "Copy " + o.name, o.id = V, h(L.addCustomDimension(o));
  };
  return t || i || r ? /* @__PURE__ */ w(
    O,
    {
      withArrow: !0,
      withinPortal: !0,
      shadow: "lg",
      position: "bottom-end",
      arrowOffset: 12,
      offset: -4,
      opened: r,
      onChange: s,
      children: [
        /* @__PURE__ */ w(O.Dropdown, { children: [
          !ue(e) && At(e) ? /* @__PURE__ */ n(
            O.Item,
            {
              component: "button",
              leftSection: /* @__PURE__ */ n(T, { icon: Ot }),
              onClick: (a) => {
                a.stopPropagation(), g({
                  name: Q.ADD_FILTER_CLICKED
                }), p(e, void 0);
              },
              children: "Add filter"
            }
          ) : null,
          ue(e) ? /* @__PURE__ */ w(se, { children: [
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: rt }),
                onClick: (a) => {
                  a.stopPropagation(), h(
                    L.toggleAdditionalMetricModal(
                      {
                        type: e.type,
                        item: e,
                        isEditing: !0
                      }
                    )
                  );
                },
                children: "Edit custom metric"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: ot }),
                onClick: (a) => {
                  a.stopPropagation(), v(e), g({
                    name: Q.ADD_CUSTOM_METRIC_CLICKED
                  }), u({
                    title: "Copy of Custom metric added successfully"
                  });
                },
                children: "Duplicate custom metric"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: Ce }),
                onClick: (a) => {
                  a.stopPropagation(), m && d.data?.organizationUuid && g({
                    name: Q.WRITE_BACK_FROM_CUSTOM_METRIC_CLICKED,
                    properties: {
                      userId: d.data.userUuid,
                      projectId: m,
                      organizationId: d.data.organizationUuid,
                      customMetricsCount: 1
                    }
                  }), h(
                    L.toggleWriteBackModal({
                      items: [e]
                    })
                  );
                },
                children: "Write back to dbt"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                color: "red",
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: ye }),
                onClick: (a) => {
                  a.stopPropagation(), g({
                    name: Q.REMOVE_CUSTOM_METRIC_CLICKED
                  }), h(
                    L.removeAdditionalMetric(
                      U(e)
                    )
                  );
                },
                children: "Remove custom metric"
              },
              "custommetric"
            )
          ] }) : null,
          l && /* @__PURE__ */ n(
            O.Item,
            {
              component: "button",
              leftSection: /* @__PURE__ */ n(T, { icon: Ae }),
              onClick: (a) => {
                a.stopPropagation(), c();
              },
              children: "View description"
            }
          ),
          be(e) && /* @__PURE__ */ w(se, { children: [
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: rt }),
                onClick: (a) => {
                  a.stopPropagation(), h(
                    L.toggleCustomDimensionModal({
                      item: e,
                      isEditing: !0
                    })
                  );
                },
                children: "Edit custom dimension"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: ot }),
                onClick: (a) => {
                  a.stopPropagation(), E(e), g({
                    name: Q.ADD_CUSTOM_DIMENSION_CLICKED
                  }), u({
                    title: "Copy of Custom Dimension added successfully"
                  });
                },
                children: "Duplicate custom dimension"
              }
            ),
            (Me(e) || y) && /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: Ce }),
                onClick: (a) => {
                  a.stopPropagation(), m && d.data?.organizationUuid && g({
                    name: Q.WRITE_BACK_FROM_CUSTOM_DIMENSION_CLICKED,
                    properties: {
                      userId: d.data.userUuid,
                      projectId: m,
                      organizationId: d.data.organizationUuid,
                      customDimensionsCount: 1
                    }
                  }), h(
                    L.toggleWriteBackModal({
                      items: [e]
                    })
                  );
                },
                children: "Write back to dbt"
              }
            ),
            /* @__PURE__ */ n(
              O.Item,
              {
                color: "red",
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: ye }),
                onClick: (a) => {
                  a.stopPropagation(), h(
                    L.removeCustomDimension(
                      U(e)
                    )
                  );
                },
                children: "Remove custom dimension"
              }
            )
          ] }),
          C.length > 0 && (ee(e) || Me(e)) ? /* @__PURE__ */ w(se, { children: [
            /* @__PURE__ */ n(O.Divider, {}),
            /* @__PURE__ */ n(O.Label, { children: "Add custom metrics" }),
            C.map((a) => /* @__PURE__ */ n(
              O.Item,
              {
                role: "menuitem",
                component: "button",
                onClick: (o) => {
                  o.stopPropagation(), console.debug(
                    "opening custom metric modal: " + a
                  ), h(
                    L.toggleAdditionalMetricModal(
                      {
                        type: a,
                        item: e,
                        isEditing: !1
                      }
                    )
                  ), g({
                    name: Q.ADD_CUSTOM_METRIC_CLICKED
                  });
                },
                children: de(a)
              },
              a
            ))
          ] }) : null,
          ee(e) && (e.type === je.NUMBER || e.type === je.STRING && f) ? /* @__PURE__ */ w(se, { children: [
            /* @__PURE__ */ n(O.Divider, {}),
            /* @__PURE__ */ n(
              O.Item,
              {
                component: "button",
                leftSection: /* @__PURE__ */ n(T, { icon: os }),
                onClick: (a) => {
                  a.stopPropagation(), g({
                    name: Q.ADD_CUSTOM_DIMENSION_CLICKED
                  }), h(
                    L.toggleCustomDimensionModal({
                      item: e,
                      isEditing: !1
                    })
                  );
                },
                children: "Add custom dimensions"
              }
            )
          ] }) : null
        ] }),
        /* @__PURE__ */ n(
          at,
          {
            component: "div",
            onClick: (a) => {
              a.stopPropagation(), a.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(
                  T,
                  {
                    icon: Ae,
                    color: r ? "black" : void 0
                  }
                ) })
              }
            ) })
          }
        )
      ]
    }
  ) : /* @__PURE__ */ n(at, { 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(T, { 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((D) => D.itemsMap), i = P((D) => D.isSearching), r = P((D) => D.searchResults), s = P((D) => D.searchQuery), l = P(
    (D) => D.missingCustomMetrics
  ), c = P((D) => D.itemsAlerts), m = P(
    (D) => D.missingCustomDimensions
  ), d = P((D) => D.onItemClick), u = P((D) => D.isVirtualized), p = P((D) => D.depth), { track: g } = Fe(), h = ls(), C = ge(), [y, f] = Ve(!1), [v, E] = Ve(!1), a = !i || r.includes(e.key), o = t[e.key], k = x(() => U(o), [o]), V = x(
    () => (D) => cs(D, k),
    [k]
  ), I = x(
    () => (D) => ds(D, k),
    [k]
  ), $ = B(
    V,
    (D, ce) => D === ce
  ), _ = B(I, (D, ce) => D === ce), H = x(() => {
    if (ct(o))
      return {
        type: o.type,
        sql: o.sql,
        compiledSql: o.compiledSql,
        filters: o.filters,
        table: o.table,
        name: o.name
      };
  }, [o]), S = fe(o) ? o.description : void 0, N = ue(o) && l && l.includes(o) || be(o) && m && m.includes(o), F = x(() => ct(o) && (H || S) ? !1 : !S && !N, [S, N, o, H]), b = us(o), A = c?.[U(o)], z = fe(o) && $, R = (z || y) && !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 = M(
    (D) => {
      g({ name: Q.ADD_FILTER_CLICKED }), z || h(o, void 0), D.stopPropagation();
    },
    [z, h, o, g]
  ), sn = M(() => {
    d(e.key, o);
  }, [d, e.key, o]), rn = M(
    () => f(!0),
    [f]
  ), on = M(
    () => f(!1),
    [f]
  ), an = M(
    /**
     * If we don't stop propagation, users may unintentionally toggle dimensions/metrics
     * while interacting with the hovercard.
     */
    (D) => D.stopPropagation(),
    []
  ), nt = M(() => {
    f(!1), C(
      L.openItemDetail({
        itemType: "field",
        label: Ee,
        description: S,
        fieldItem: o
      })
    );
  }, [f, C, o, Ee, S]), ln = M(() => {
    f(!1), E();
  }, [f, E]), cn = x(
    () => ({
      backgroundColor: _ ? b.bg : void 0,
      "&:hover": {
        backgroundColor: b.bgHover
      }
    }),
    [_, b]
  ), dn = x(
    () => /* @__PURE__ */ n(Kt, { isMissing: N, item: o }),
    [N, o]
  ), un = x(() => [
    { type: "infos", alertIcon: Tt, 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 $e = A?.[ce];
    return !$e || $e.length === 0 ? [] : /* @__PURE__ */ n(
      le,
      {
        withinPortal: !0,
        maw: 300,
        multiline: !0,
        label: $e.join(`
`),
        children: /* @__PURE__ */ n(
          T,
          {
            icon: pn,
            color: hn,
            style: { flexShrink: 0 }
          }
        )
      },
      ce
    );
  }), [A]), mn = x(() => {
    if (u)
      return `${12 + (p ?? 0) * 20}px`;
  }, [p, u]);
  return !o || !a ? null : /* @__PURE__ */ n(
    Xe,
    {
      component: "div",
      noWrap: !0,
      sx: cn,
      icon: dn,
      onClick: sn,
      onMouseEnter: rn,
      onMouseLeave: on,
      pl: mn,
      label: /* @__PURE__ */ w(ae, { noWrap: !0, spacing: "xs", children: [
        /* @__PURE__ */ w(
          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: !y,
                  p: "xs",
                  miw: 400,
                  mah: 500,
                  maw: 500,
                  sx: { overflow: "auto" },
                  onClick: an,
                  children: N ? `This field from '${o.table}' table is no longer available` : /* @__PURE__ */ n(
                    Rt,
                    {
                      onViewDescription: nt,
                      description: S,
                      metricInfo: H
                    }
                  )
                }
              )
            ]
          }
        ),
        un,
        R && /* @__PURE__ */ n(
          le,
          {
            withinPortal: !0,
            label: z ? "This field is filtered" : "Click here to add filter",
            children: /* @__PURE__ */ n(re, { onClick: nn, children: /* @__PURE__ */ n(
              T,
              {
                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(
              T,
              {
                icon: me,
                color: "yellow.9",
                style: { flexShrink: 0 }
              }
            )
          }
        ) : null
      ] }),
      rightSection: /* @__PURE__ */ n(
        Gi,
        {
          item: o,
          isHovered: y,
          isSelected: _,
          isOpened: v,
          hasDescription: !!S,
          onViewDescription: nt,
          onMenuChange: ln
        }
      ),
      "data-testid": `tree-single-node-${Ee}`
    }
  );
}, et = W(Ui);
et.displayName = "TreeSingleNode";
const qi = ({ nodeMap: e }) => {
  const t = P((s) => s.itemsMap), i = P((s) => s.orderFieldsBy), r = x(() => Object.values(e).sort(
    Ze(i ?? Re.LABEL, t)
  ), [e, i, t]);
  return /* @__PURE__ */ n(se, { children: r.map(
    (s) => Pe(s) ? /* @__PURE__ */ n(tt, { node: s }, s.key) : /* @__PURE__ */ n(et, { 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((R) => R.isSearching), s = P((R) => R.searchQuery), l = P((R) => R.searchResults), c = P((R) => R.tableName), m = P((R) => R.treeSectionType), d = P((R) => R.expandedGroups), u = P((R) => R.onToggleGroup), p = P((R) => R.isVirtualized), g = P((R) => R.depth), h = P((R) => R.groupKey), [C, y] = Ve(!1), f = h ?? Bt(c, m, e.key), v = d.has(f), E = x(() => Hi([e]), [e]), a = x(
    () => dt(E, Array.from(i)),
    [E, i]
  ), o = x(
    () => fs(E, Array.from(i)).length,
    [E, i]
  ), k = x(
    () => !r || dt(E, Array.from(l)),
    [r, E, l]
  ), I = r && k || v, { description: $, label: _ } = e, H = M(() => {
    y(!1), t(
      L.openItemDetail({
        itemType: "group",
        label: _,
        description: $
      })
    );
  }, [y, t, _, $]), S = M(
    () => u(f),
    [u, f]
  ), N = M(
    () => y(!0),
    [y]
  ), F = M(
    () => y(!1),
    [y]
  ), b = M(
    /**
     * If we don't stop propagation, users may unintentionally toggle dimensions/metrics
     * while interacting with the hovercard.
     */
    (R) => R.stopPropagation(),
    []
  ), A = x(
    () => /* @__PURE__ */ n(
      T,
      {
        icon: ys,
        size: 14,
        style: {
          margin: 1,
          transition: "transform 200ms ease",
          transform: I ? "rotate(90deg)" : "rotate(0deg)"
        }
      }
    ),
    [I]
  ), z = x(() => {
    if (p)
      return `${12 + (g ?? 0) * 20}px`;
  }, [g, p]);
  return k ? /* @__PURE__ */ n(
    Xe,
    {
      opened: I,
      onClick: S,
      disableRightSectionRotation: !0,
      rightSection: /* @__PURE__ */ n(se, {}),
      icon: A,
      onMouseEnter: N,
      onMouseLeave: F,
      pl: z,
      label: /* @__PURE__ */ w(ae, { children: [
        !v && a && /* @__PURE__ */ n(bs, { children: o }),
        /* @__PURE__ */ w(
          te,
          {
            openDelay: 300,
            keepMounted: !1,
            shadow: "sm",
            withinPortal: !0,
            withArrow: !0,
            disabled: !$,
            position: "right",
            offset: 80,
            children: [
              /* @__PURE__ */ n(te.Target, { children: /* @__PURE__ */ n(
                _t,
                {
                  component: Z,
                  truncate: !0,
                  highlight: s || "",
                  children: _
                }
              ) }),
              /* @__PURE__ */ n(
                te.Dropdown,
                {
                  hidden: !C,
                  p: "xs",
                  maw: 500,
                  onClick: b,
                  children: /* @__PURE__ */ n(
                    Rt,
                    {
                      onViewDescription: H,
                      description: $
                    }
                  )
                }
              )
            ]
          }
        )
      ] }),
      children: I && !p && /* @__PURE__ */ n(Yt, { nodeMap: e.children })
    }
  ) : null;
}, tt = W(Wi);
tt.displayName = "TreeGroupNode";
const Qi = ({
  item: e,
  sectionContexts: t,
  onToggleGroup: i,
  onSelectedFieldChange: r
}) => {
  const { node: s, isGroup: l, sectionKey: c, depth: m, isExpanded: d } = e.data, u = t.get(c), p = x(() => {
    if (!u)
      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: j.Dimensions,
        expandedGroups: /* @__PURE__ */ new Set(),
        onToggleGroup: () => {
        }
      };
    const g = /* @__PURE__ */ new Set();
    return l && d && g.add(e.id), {
      itemsMap: u.itemsMap,
      nodeMap: u.nodeMap,
      isSearching: !!u.searchQuery && u.searchQuery !== "",
      searchQuery: u.searchQuery,
      missingCustomMetrics: u.missingCustomMetrics,
      itemsAlerts: u.itemsAlerts,
      missingCustomDimensions: u.missingCustomDimensions,
      orderFieldsBy: u.orderFieldsBy,
      isGithubIntegrationEnabled: u.isGithubIntegrationEnabled,
      gitIntegration: u.gitIntegration,
      onItemClick: (h) => {
        if (u.itemsMap[h]) {
          const y = u.sectionType === j.Dimensions || u.sectionType === j.CustomDimensions;
          r(h, y);
        }
      },
      searchResults: u.searchResults,
      tableName: u.tableName,
      treeSectionType: u.sectionType,
      expandedGroups: g,
      onToggleGroup: i,
      isVirtualized: !0,
      // Flag to prevent inline children rendering
      depth: m,
      // Nesting depth for indentation
      groupKey: l ? e.id : void 0
      // Pre-computed unique group key with parent path
    };
  }, [
    u,
    m,
    r,
    i,
    l,
    d,
    e.id
  ]);
  return u ? /* @__PURE__ */ n(Qt.Provider, { value: p, children: l && Pe(s) ? /* @__PURE__ */ n(tt, { node: s }) : /* @__PURE__ */ n(et, { node: s }) }) : (console.error(`Section context not found for key: ${c}`), 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: l } = e, c = pt(null), m = pt(0), d = x(
    () => s.map(
      (y, f) => y.type === "table-header" ? f : -1
    ).filter((y) => y !== -1),
    [s]
  ), u = M(
    (y) => d.includes(y),
    [d]
  ), p = M(
    (y) => m.current === y,
    []
  ), g = M(
    (y) => {
      const f = [...d].reverse().find((v) => y.startIndex >= v);
      return f !== void 0 ? (m.current = f, [.../* @__PURE__ */ new Set([
        f,
        ...ut(y)
      ])].sort((E, a) => E - a)) : (m.current = -1, ut(y));
    },
    [d]
  ), h = Cs({
    count: s.length,
    getScrollElement: () => c.current,
    estimateSize: (y) => s[y].estimatedHeight,
    overscan: 5,
    // Render 5 extra items above and below viewport
    rangeExtractor: g
  }), C = h.getVirtualItems();
  return /* @__PURE__ */ n(vs, { inherit: !0, theme: Yi, children: /* @__PURE__ */ n(
    "div",
    {
      ref: c,
      "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: C.map((y) => {
            const f = s[y.index], v = u(y.index), E = p(
              y.index
            );
            return /* @__PURE__ */ n(
              "div",
              {
                "data-index": y.index,
                style: {
                  ...v ? {
                    zIndex: 1
                  } : {},
                  ...E ? {
                    position: "sticky"
                  } : {
                    position: "absolute",
                    transform: `translateY(${y.start}px)`
                  },
                  top: 0,
                  left: 0,
                  width: "100%"
                },
                children: /* @__PURE__ */ n(
                  Xt,
                  {
                    item: f,
                    sectionContexts: l,
                    onToggleTable: t,
                    onToggleGroup: i,
                    onSelectedFieldChange: r
                  }
                )
              },
              f.id
            );
          })
        }
      )
    }
  ) });
}, Zt = W(Ji);
Zt.displayName = "VirtualizedTreeList";
const Xi = ({
  explore: e,
  onSelectedFieldChange: t
}) => {
  const i = B(Ke), r = B(Vt), s = B(
    (b) => ws(b, e)
  ), l = B(
    (b) => Es(b, e)
  ), c = B(
    (b) => Is(b, e)
  ), m = B(Nt), d = B(Ts), [u, p] = q(""), [g, h] = Ye(), [C, y] = q({}), [f] = Ss(u, 300), v = x(() => {
    const b = f.trim();
    return !!b && b !== "";
  }, [f]), E = x(() => $i(
    e,
    i,
    r
  ), [e, i, r]), a = M(
    (b) => {
      p(b.target.value);
    },
    []
  ), o = M(() => {
    p("");
  }, []), k = M(
    (b) => {
      const z = [
        ...Object.values({
          ...b.dimensions,
          ...b.metrics
        }),
        ...i
      ].reduce((R, we) => ({ ...R, [U(we)]: we }), {});
      return _i(z, f);
    },
    [i, f]
  );
  Je(() => {
    h(() => {
      v && y(
        Object.values(e.tables).reduce(
          (b, A) => ({ ...b, [A.name]: k(A) }),
          {}
        )
      );
    });
  }, [e, v, k]);
  const V = x(() => Object.values(e.tables).sort((b, A) => b.name === e.baseTable ? -1 : A.name === e.baseTable ? 1 : b.label.localeCompare(A.label)).filter(
    (b) => !(v && C[b.name]?.length === 0) && !b.hidden
  ), [e, v, C]), [I, $] = q(() => {
    const b = V[0];
    return b ? /* @__PURE__ */ new Set([b.name]) : /* @__PURE__ */ new Set();
  }), [_, H] = q(
    /* @__PURE__ */ new Set()
  ), S = M((b) => {
    $((A) => {
      const z = new Set(A);
      return z.has(b) ? z.delete(b) : z.add(b), z;
    });
  }, []), N = M((b) => {
    H((A) => {
      const z = new Set(A);
      return z.has(b) ? z.delete(b) : z.add(b), z;
    });
  }, []), F = x(() => Pi({
    tables: V,
    showMultipleTables: Object.keys(e.tables).length > 1,
    expandedTables: I,
    expandedGroups: _,
    searchQuery: f,
    searchResultsMap: C,
    isSearching: v,
    additionalMetrics: i,
    customDimensions: r ?? [],
    missingCustomMetrics: s,
    missingCustomDimensions: l,
    missingFieldIds: c,
    selectedDimensions: d,
    sectionNodeMaps: E
  }), [
    m,
    i,
    r,
    f,
    _,
    I,
    e.tables,
    v,
    l,
    s,
    c,
    C,
    E,
    d,
    V
  ]);
  return /* @__PURE__ */ w(se, { children: [
    /* @__PURE__ */ n(
      Ms,
      {
        icon: /* @__PURE__ */ n(T, { icon: xs }),
        rightSection: g ? /* @__PURE__ */ n(
          Ds,
          {
            size: "xs",
            "data-testid": "ExploreTree/SearchInput-Loader"
          }
        ) : u ? /* @__PURE__ */ n(re, { onClick: o, children: /* @__PURE__ */ n(T, { icon: ks }) }) : null,
        placeholder: "Search metrics + dimensions",
        value: u,
        onChange: a,
        "data-testid": "ExploreTree/SearchInput"
      }
    ),
    /* @__PURE__ */ n(
      Zt,
      {
        data: F,
        onToggleTable: S,
        onToggleGroup: N,
        onSelectedFieldChange: t
      }
    )
  ] });
}, en = W(Xi);
en.displayName = "ExploreTree";
const tn = W(({ onBack: e }) => {
  const { track: t } = Fe(), { user: i } = Qe(), [r, s] = q(!1), [l, c] = q(!1), [, m] = Ye(), d = We(), u = Vs(d ?? ""), { open: p } = hi(), { data: g } = As(
    xe.EditYamlInUi
  ), h = B(St), C = B(Ke), f = B(Os)?.uuid, v = ge(), E = M(
    (N, F) => {
      v(F ? L.toggleDimension(N) : L.toggleMetric(N));
    },
    [v]
  ), a = B(
    _s
  ), {
    data: o,
    isFetching: k,
    status: V,
    error: I
  } = Ns(h);
  Je(() => {
    if (d && i.data?.organizationUuid && o && C) {
      const N = Rs({
        metrics: Fs(o),
        customMetrics: C
      }), F = Ps(
        N
      );
      F && (v(
        L.replaceFields({
          fieldsToReplace: {
            customMetrics: F
          }
        })
      ), t({
        name: Q.CUSTOM_FIELDS_REPLACEMENT_APPLIED,
        properties: {
          userId: i.data.userUuid,
          projectId: d,
          organizationId: i.data.organizationUuid,
          chartId: f,
          customMetricIds: Object.keys(F)
        }
      }));
    }
  }, [
    o,
    C,
    v,
    t,
    i,
    d,
    f
  ]);
  const $ = M(() => {
    m(() => s(!0));
  }, []), _ = M(() => {
    c(!0);
  }, []), H = M(() => {
    h && p({ explore: h });
  }, [p, h]), S = x(() => o ? e ? [
    { title: "Tables", onClick: e },
    { title: o.label, active: !0 }
  ] : [{ title: o.label, active: !0 }] : [], [e, o]);
  return k ? /* @__PURE__ */ n($s, {}) : o ? V === "error" && I.error.statusCode < 500 ? (e?.(), null) : /* @__PURE__ */ w(se, { children: [
    /* @__PURE__ */ n(
      mt,
      {
        id: Ls,
        sx: {
          flexGrow: 1,
          overflow: "hidden",
          display: a ? "flex" : "none"
        }
      }
    ),
    /* @__PURE__ */ w(
      mt,
      {
        h: "100%",
        sx: {
          flexGrow: 1,
          display: a ? "none" : "flex"
        },
        children: [
          /* @__PURE__ */ w(ae, { position: "apart", children: [
            /* @__PURE__ */ w(ae, { spacing: "xs", children: [
              /* @__PURE__ */ n(Qs, { size: "md", items: S }),
              o.warnings && o.warnings.length > 0 && /* @__PURE__ */ w(
                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(
                          T,
                          {
                            icon: me,
                            color: "yellow.9"
                          }
                        )
                      }
                    ) }),
                    /* @__PURE__ */ n(te.Dropdown, { maw: 400, p: "xs", children: /* @__PURE__ */ n(
                      Ks,
                      {
                        type: "warnings",
                        warnings: o.warnings
                      }
                    ) })
                  ]
                }
              )
            ] }),
            o.type === ze.VIRTUAL && /* @__PURE__ */ n(
              Le,
              {
                I: "create",
                this: De("VirtualView", {
                  organizationUuid: i.data?.organizationUuid,
                  projectUuid: d
                }),
                children: /* @__PURE__ */ w(O, { withArrow: !0, offset: -2, children: [
                  /* @__PURE__ */ n(O.Target, { children: /* @__PURE__ */ n(re, { variant: "transparent", children: /* @__PURE__ */ n(T, { icon: Ae }) }) }),
                  /* @__PURE__ */ w(O.Dropdown, { children: [
                    /* @__PURE__ */ n(
                      O.Item,
                      {
                        leftSection: /* @__PURE__ */ n(T, { icon: js }),
                        onClick: $,
                        children: /* @__PURE__ */ n(Z, { fz: "xs", fw: 500, children: "Edit virtual view" })
                      }
                    ),
                    /* @__PURE__ */ n(
                      Le,
                      {
                        I: "delete",
                        this: De("VirtualView", {
                          organizationUuid: i.data?.organizationUuid,
                          projectUuid: d
                        }),
                        children: /* @__PURE__ */ n(
                          O.Item,
                          {
                            leftSection: /* @__PURE__ */ n(T, { icon: ye }),
                            color: "red",
                            onClick: _,
                            children: /* @__PURE__ */ n(Z, { fz: "xs", fw: 500, children: "Delete" })
                          }
                        )
                      }
                    )
                  ] })
                ] })
              }
            ),
            o.type !== ze.VIRTUAL && u && o.ymlPath && g?.enabled && /* @__PURE__ */ n(
              Le,
              {
                I: "view",
                this: De("SourceCode", {
                  organizationUuid: i.data?.organizationUuid,
                  projectUuid: d
                }),
                children: /* @__PURE__ */ w(O, { withArrow: !0, offset: -2, children: [
                  /* @__PURE__ */ n(O.Target, { children: /* @__PURE__ */ n(re, { variant: "transparent", children: /* @__PURE__ */ n(T, { icon: Ae }) }) }),
                  /* @__PURE__ */ n(O.Dropdown, { children: /* @__PURE__ */ n(
                    O.Item,
                    {
                      leftSection: /* @__PURE__ */ n(T, { 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: E
            }
          ) }),
          r && /* @__PURE__ */ n(
            Mi,
            {
              opened: r,
              onClose: () => s(!1),
              activeTableName: h,
              setIsEditVirtualViewOpen: s,
              explore: o
            }
          ),
          l && d && /* @__PURE__ */ n(
            Ti,
            {
              opened: l,
              onClose: () => c(!1),
              virtualViewName: h,
              projectUuid: d
            }
          )
        ]
      }
    )
  ] }) : 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-BRzNuD5Z.mjs.map
