UNPKG

drizzle-cube

Version:

Drizzle ORM-first semantic layer with Cube.js compatibility. Type-safe analytics and dashboards with SQL injection protection.

13,699 lines 503 kB
import { jsxs as s, jsx as e, Fragment as Ie } from "react/jsx-runtime";
import * as Lt from "react";
import lt, { Component as bs, forwardRef as Fr, useState as H, useRef as Te, useEffect as Ce, useMemo as Oe, useImperativeHandle as Lr, useCallback as F, memo as gt, Suspense as gs, lazy as ys } from "react";
import { useCubeQuery as Rn, useDebounce as On, useFilterValues as Mn, useResponsiveDashboard as vs } from "../hooks.js";
import { useScrollContainer as Ns, ScrollContainerProvider as In } from "../providers.js";
import { l as z, L as ws, v as qt, y as pr, M as Ot, O as ks, Q as Cs, U as Ds, V as Ts, W as Ss, X as As, Y as _s, Z as Es, _ as Rs, $ as Os, a0 as Ms, a1 as Is, a2 as $s, a3 as Fs, a4 as Ls, a5 as js, u as jt } from "./charts-B8YMw1mi.js";
import { u as Ps, i as $n, L as Mr, b as br } from "./charts-amt7VOyw.js";
import Bs, { verticalCompactor as qs } from "react-grid-layout";
var Ir = /* @__PURE__ */ new Map(), sr = /* @__PURE__ */ new WeakMap(), Zr = 0, Vs;
function Hs(t) {
  return t ? (sr.has(t) || (Zr += 1, sr.set(t, Zr.toString())), sr.get(t)) : "0";
}
function zs(t) {
  return Object.keys(t).sort().filter(
    (r) => t[r] !== void 0
  ).map((r) => `${r}_${r === "root" ? Hs(t.root) : t[r]}`).toString();
}
function Qs(t) {
  const r = zs(t);
  let n = Ir.get(r);
  if (!n) {
    const a = /* @__PURE__ */ new Map();
    let c;
    const l = new IntersectionObserver((d) => {
      d.forEach((h) => {
        var o;
        const u = h.isIntersecting && c.some((m) => h.intersectionRatio >= m);
        t.trackVisibility && typeof h.isVisible > "u" && (h.isVisible = u), (o = a.get(h.target)) == null || o.forEach((m) => {
          m(u, h);
        });
      });
    }, t);
    c = l.thresholds || (Array.isArray(t.threshold) ? t.threshold : [t.threshold || 0]), n = {
      id: r,
      observer: l,
      elements: a
    }, Ir.set(r, n);
  }
  return n;
}
function Us(t, r, n = {}, a = Vs) {
  if (typeof window.IntersectionObserver > "u" && a !== void 0) {
    const o = t.getBoundingClientRect();
    return r(a, {
      isIntersecting: a,
      target: t,
      intersectionRatio: typeof n.threshold == "number" ? n.threshold : 0,
      time: 0,
      boundingClientRect: o,
      intersectionRect: o,
      rootBounds: o
    }), () => {
    };
  }
  const { id: c, observer: l, elements: d } = Qs(n), h = d.get(t) || [];
  return d.has(t) || d.set(t, h), h.push(r), l.observe(t), function() {
    h.splice(h.indexOf(r), 1), h.length === 0 && (d.delete(t), l.unobserve(t)), d.size === 0 && (l.disconnect(), Ir.delete(c));
  };
}
function Gs({
  threshold: t,
  delay: r,
  trackVisibility: n,
  rootMargin: a,
  root: c,
  triggerOnce: l,
  skip: d,
  initialInView: h,
  fallbackInView: o,
  onChange: u
} = {}) {
  var m;
  const [x, f] = Lt.useState(null), S = Lt.useRef(u), T = Lt.useRef(h), [D, k] = Lt.useState({
    inView: !!h,
    entry: void 0
  });
  S.current = u, Lt.useEffect(
    () => {
      if (T.current === void 0 && (T.current = h), d || !x) return;
      let R;
      return R = Us(
        x,
        (y, i) => {
          const g = T.current;
          T.current = y, !(g === void 0 && !y) && (k({
            inView: y,
            entry: i
          }), S.current && S.current(y, i), i.isIntersecting && l && R && (R(), R = void 0));
        },
        {
          root: c,
          rootMargin: a,
          threshold: t,
          // @ts-expect-error
          trackVisibility: n,
          delay: r
        },
        o
      ), () => {
        R && R();
      };
    },
    // We break the rule here, because we aren't including the actual `threshold` variable
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      // If the threshold is an array, convert it to a string, so it won't change between renders.
      Array.isArray(t) ? t.toString() : t,
      x,
      c,
      a,
      l,
      d,
      n,
      o,
      r
    ]
  );
  const A = (m = D.entry) == null ? void 0 : m.target, _ = Lt.useRef(void 0);
  !x && A && !l && !d && _.current !== A && (_.current = A, k({
    inView: !!h,
    entry: void 0
  }), T.current = h);
  const O = [f, D.inView, D.entry];
  return O.ref = O[0], O.inView = O[1], O.entry = O[2], O;
}
const Ws = z("refresh");
class Js extends bs {
  constructor(r) {
    super(r), this.state = {
      hasError: !1,
      error: null,
      errorInfo: null
    };
  }
  static getDerivedStateFromError(r) {
    return {
      hasError: !0,
      error: r,
      errorInfo: null
    };
  }
  componentDidCatch(r, n) {
    this.setState({
      error: r,
      errorInfo: n.componentStack || null
    }), console.error("Chart Error Boundary caught a rendering error:", r, n);
  }
  handleReset = () => {
    this.setState({
      hasError: !1,
      error: null,
      errorInfo: null
    });
  };
  render() {
    return this.state.hasError ? this.props.fallback ? this.props.fallback : /* @__PURE__ */ s(
      "div",
      {
        className: "flex flex-col items-center justify-center w-full h-full p-6 text-center border border-dashed rounded-lg",
        style: { borderColor: "var(--dc-border)", backgroundColor: "var(--dc-surface)" },
        children: [
          /* @__PURE__ */ e("div", { className: "h-12 w-12 mb-4 text-dc-text-muted", children: "⚠️" }),
          /* @__PURE__ */ e("h3", { className: "text-lg font-semibold mb-2 text-dc-text", children: this.props.portletTitle ? `Unable to render ${this.props.portletTitle}` : "Unable to render chart" }),
          /* @__PURE__ */ e("p", { className: "text-sm text-dc-text-secondary mb-4 max-w-md", children: "There was an error rendering this chart component. The error details are shown below." }),
          /* @__PURE__ */ e("div", { className: "w-full max-w-2xl mb-4", children: /* @__PURE__ */ s("div", { className: "bg-dc-surface-secondary rounded-lg p-3 text-left", children: [
            /* @__PURE__ */ s("div", { className: "text-xs font-mono mb-2 text-dc-text", children: [
              /* @__PURE__ */ e("strong", { children: "Error:" }),
              " ",
              this.state.error?.message
            ] }),
            this.state.error?.name && /* @__PURE__ */ s("div", { className: "text-xs font-mono text-dc-text-secondary mb-2", children: [
              /* @__PURE__ */ e("strong", { children: "Type:" }),
              " ",
              this.state.error.name
            ] }),
            this.props.portletConfig && /* @__PURE__ */ s("details", { className: "text-xs font-mono text-dc-text-secondary mb-2", children: [
              /* @__PURE__ */ e("summary", { className: "cursor-pointer", children: "Portlet Configuration" }),
              /* @__PURE__ */ e(
                "pre",
                {
                  className: "mt-2 whitespace-pre-wrap p-2 rounded-sm overflow-auto max-h-32",
                  style: { backgroundColor: "rgba(var(--dc-primary-rgb), 0.1)" },
                  children: JSON.stringify(this.props.portletConfig, null, 2)
                }
              )
            ] }),
            this.props.cubeQuery && /* @__PURE__ */ s("details", { className: "text-xs font-mono text-dc-text-secondary mb-2", children: [
              /* @__PURE__ */ e("summary", { className: "cursor-pointer", children: "Cube Query" }),
              /* @__PURE__ */ e(
                "pre",
                {
                  className: "mt-2 whitespace-pre-wrap p-2 rounded-sm overflow-auto max-h-32",
                  style: { backgroundColor: "#d1fae5" },
                  children: typeof this.props.cubeQuery == "string" ? JSON.stringify(JSON.parse(this.props.cubeQuery), null, 2) : JSON.stringify(this.props.cubeQuery, null, 2)
                }
              )
            ] }),
            this.state.errorInfo && /* @__PURE__ */ s("details", { className: "text-xs font-mono text-dc-text-secondary", children: [
              /* @__PURE__ */ e("summary", { className: "cursor-pointer", children: "Component Stack" }),
              /* @__PURE__ */ e("pre", { className: "mt-2 whitespace-pre-wrap", children: this.state.errorInfo })
            ] })
          ] }) }),
          /* @__PURE__ */ s(
            "button",
            {
              onClick: this.handleReset,
              className: "px-3 py-1 text-white rounded-sm text-sm hover:opacity-90 transition-opacity",
              style: {
                backgroundColor: "var(--dc-primary)"
              },
              children: [
                /* @__PURE__ */ e(Ws, { style: { width: "16px", height: "16px", display: "inline", marginRight: "4px" } }),
                "Try Again"
              ]
            }
          )
        ]
      }
    ) : this.props.children;
  }
}
const en = [];
class jr {
  cache = /* @__PURE__ */ new Map();
  maxSize = 100;
  // Prevent unbounded growth
  get(r) {
    try {
      const n = JSON.stringify(r);
      return this.cache.get(n);
    } catch {
      return;
    }
  }
  set(r, n) {
    try {
      const a = JSON.stringify(r);
      if (this.cache.size >= this.maxSize) {
        const c = this.cache.keys().next().value;
        c && this.cache.delete(c);
      }
      this.cache.set(a, n);
    } catch {
    }
  }
  clear() {
    this.cache.clear();
  }
}
const tn = new jr(), rn = new jr(), nn = new jr();
function Fn(t) {
  if ("member" in t && "operator" in t) {
    const r = t;
    return ["set", "notSet", "isEmpty", "isNotEmpty"].includes(r.operator) || r.operator === "inDateRange" && r.dateRange ? !0 : !!(r.values && r.values.length > 0);
  }
  return "type" in t && "filters" in t ? t.filters.filter((a) => Fn(a)).length > 0 : !1;
}
function Ys(t, r) {
  if (!t || !t.length || !r || !r.length)
    return en;
  const n = { dashboardFilters: t, filterMapping: r }, a = tn.get(n);
  if (a)
    return a;
  const c = t.filter((d) => r.includes(d.id)).filter((d) => Fn(d.filter)).map((d) => d.filter), l = Object.freeze(c);
  return tn.set(n, l), l;
}
function Ln(t) {
  if ("type" in t && "filters" in t) {
    const r = t, n = r.filters.map(Ln);
    return r.type === "and" ? { and: n } : { or: n };
  }
  return t;
}
function Ks(t, r) {
  if (!t || t.length === 0)
    return r;
  if (!r || r.length === 0)
    return Object.freeze([...t]);
  const n = { dashboardFilters: t, portletFilters: r }, a = rn.get(n);
  if (a)
    return a;
  const l = [{
    and: [...t, ...r].map(Ln)
  }], d = Object.freeze(l);
  return rn.set(n, d), d;
}
function Xs(t) {
  const r = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set();
  return t.portlets.forEach((c) => {
    try {
      const l = JSON.parse(c.query);
      l.measures && Array.isArray(l.measures) && l.measures.forEach((d) => r.add(d)), l.dimensions && Array.isArray(l.dimensions) && l.dimensions.forEach((d) => n.add(d)), l.timeDimensions && Array.isArray(l.timeDimensions) && l.timeDimensions.forEach((d) => {
        d.dimension && a.add(d.dimension);
      }), l.filters && jn(l.filters).forEach((d) => {
        n.add(d);
      });
    } catch (l) {
      console.warn("Failed to parse portlet query:", c.id, l);
    }
  }), { measures: r, dimensions: n, timeDimensions: a };
}
function jn(t) {
  const r = [];
  return t.forEach((n) => {
    "member" in n ? r.push(n.member) : "type" in n && "filters" in n && r.push(...jn(n.filters));
  }), [...new Set(r)];
}
function sn(t) {
  if (t.dateRange)
    return t.dateRange;
  if (t.values && t.values.length > 0)
    return t.values.length === 1 ? t.values[0] : t.values;
}
function Zs(t, r, n) {
  if (!n || n.length === 0 || !r || r.length === 0)
    return n;
  const a = { dashboardFilters: t, filterMapping: r, portletTimeDimensions: n }, c = nn.get(a);
  if (c)
    return c;
  const l = t?.filter((x) => x.isUniversalTime && r.includes(x.id))?.filter((x) => {
    if (!("member" in x.filter)) return !1;
    const f = x.filter;
    return sn(f) !== void 0;
  });
  if (!l || l.length === 0)
    return n;
  const h = l[0].filter, o = sn(h), u = n.map((x) => ({
    ...x,
    dateRange: o
  })), m = Object.freeze(u);
  return nn.set(a, m), m;
}
const gr = lt.memo(Fr(({
  query: t,
  chartType: r,
  chartConfig: n,
  displayConfig: a,
  dashboardFilters: c,
  dashboardFilterMapping: l,
  eagerLoad: d = !1,
  isVisible: h,
  // Deprecated - visibility now handled internally via useInView
  height: o = 300,
  title: u,
  colorPalette: m,
  loadingComponent: x,
  onDebugDataReady: f
}, S) => {
  const [T, D] = H(0), k = Te(f), A = Ns(), { ref: _, inView: O } = Gs({
    root: A,
    rootMargin: "500px",
    // Start loading 500px before entering viewport (about half screen)
    triggerOnce: !0,
    // Once visible, stay "visible" (don't unload data)
    initialInView: !1,
    // Start as not visible, let observer determine actual state
    skip: d
    // Skip observation entirely if eagerLoad is true
  }), R = d || O;
  Ce(() => {
    k.current = f;
  }, [f]);
  const { config: y } = Ps(r), i = y.skipQuery === !0, g = Oe(() => c?.filter((E) => !E.isUniversalTime), [c]), p = Oe(() => {
    if (i)
      return null;
    try {
      const E = JSON.parse(t), K = Ys(g, l), P = Ks(K, E.filters), Ne = Zs(
        c,
        l,
        E.timeDimensions
      );
      return {
        ...E,
        filters: P,
        timeDimensions: Ne,
        __refresh_counter: T
      };
    } catch (E) {
      return console.error("AnalyticsPortlet: Invalid query JSON:", E), null;
    }
  }, [t, T, i, g, c, l]), b = !p || i || !d && !R, { resultSet: w, isLoading: v, error: M } = Rn(p, {
    skip: b,
    resetResultSetOnChange: !0
  });
  Lr(S, () => ({
    refresh: () => {
      D((E) => E + 1);
    }
  }), []), Ce(() => {
    if (k.current && n && p && w && !M) {
      const K = (() => {
        switch (r) {
          case "pie":
          case "table":
            return w.tablePivot();
          default:
            return w.rawData();
        }
      })();
      K && k.current({
        chartConfig: n || {},
        displayConfig: a || {},
        queryObject: p,
        data: K,
        chartType: r
      });
    }
  }, [n, a, p, w, r, M]);
  const $ = !i && y.dropZones.some((E) => E.mandatory === !0);
  if (!n && $)
    return /* @__PURE__ */ e("div", { ref: _, className: "flex items-center justify-center w-full text-dc-text-muted", style: { height: o }, children: /* @__PURE__ */ s("div", { className: "text-center", children: [
      /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "Configuration Required" }),
      /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-secondary", children: "Please configure this chart" })
    ] }) });
  if (!i && !d && !R)
    return /* @__PURE__ */ e("div", { ref: _, className: "w-full h-full", style: { height: o }, children: /* @__PURE__ */ e("div", { className: "w-full h-full animate-pulse bg-dc-surface-secondary rounded", style: { minHeight: "100px" } }) });
  if (!i) {
    if (v || p && !w && !M)
      return /* @__PURE__ */ e("div", { ref: _, className: "flex items-center justify-center w-full", style: { height: o }, children: x || /* @__PURE__ */ e(ws, { size: "md" }) });
    if (M)
      return /* @__PURE__ */ s("div", { ref: _, className: "p-4 border rounded-sm", style: { height: o, borderColor: "var(--dc-border)", backgroundColor: "var(--dc-surface)" }, children: [
        /* @__PURE__ */ e("div", { className: "mb-2", children: /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ e("span", { className: "font-medium text-sm", style: { color: "var(--dc-text)" }, children: "⚠️ Query Error" }),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => D((E) => E + 1),
              className: "px-2 py-1 text-white rounded-sm text-xs",
              style: { backgroundColor: "var(--dc-primary)" },
              children: "Retry"
            }
          )
        ] }) }),
        /* @__PURE__ */ e("div", { className: "mb-3", children: /* @__PURE__ */ e("div", { className: "text-xs p-2 rounded-sm border", style: { color: "var(--dc-text-secondary)", backgroundColor: "var(--dc-surface)", borderColor: "var(--dc-border)" }, children: M.message || M.toString() }) }),
        /* @__PURE__ */ s("div", { className: "space-y-2 text-xs", children: [
          /* @__PURE__ */ s("details", { children: [
            /* @__PURE__ */ e("summary", { className: "cursor-pointer font-medium", style: { color: "var(--dc-text-secondary)" }, children: "Query (with filters applied)" }),
            /* @__PURE__ */ e("pre", { className: "mt-1 p-2 rounded-sm text-xs overflow-auto max-h-20", style: { backgroundColor: "rgba(var(--dc-primary-rgb), 0.1)" }, children: p ? JSON.stringify(p, null, 2) : t })
          ] }),
          /* @__PURE__ */ s("details", { children: [
            /* @__PURE__ */ e("summary", { className: "cursor-pointer font-medium", style: { color: "var(--dc-text-secondary)" }, children: "Chart Config" }),
            /* @__PURE__ */ e("pre", { className: "mt-1 p-2 rounded-sm text-xs overflow-auto max-h-20", style: { backgroundColor: "rgba(var(--dc-primary-rgb), 0.05)" }, children: JSON.stringify({
              chartType: r,
              chartConfig: n,
              displayConfig: a
            }, null, 2) })
          ] })
        ] })
      ] });
    if (!w || !p)
      return /* @__PURE__ */ e("div", { ref: _, className: "flex items-center justify-center w-full text-dc-text-muted", style: { height: o }, children: /* @__PURE__ */ s("div", { className: "text-center", children: [
        /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "No data available" }),
        /* @__PURE__ */ e("div", { className: "text-xs", children: "Invalid query or no results" })
      ] }) });
  }
  const L = (() => {
    if (i)
      return [];
    if (!w)
      return [];
    switch (r) {
      case "pie":
      case "table":
        return w.tablePivot();
      default:
        return w.rawData();
    }
  })();
  return /* @__PURE__ */ e("div", { ref: _, className: "w-full h-full", children: /* @__PURE__ */ e(
    Js,
    {
      portletTitle: u,
      portletConfig: {
        chartType: r,
        chartConfig: n,
        displayConfig: a,
        height: o
      },
      cubeQuery: t,
      children: /* @__PURE__ */ e("div", { className: "w-full h-full flex flex-col flex-1", style: { minHeight: "200px" }, children: (() => {
        try {
          const E = o;
          return $n(r) ? /* @__PURE__ */ e(
            Mr,
            {
              chartType: r,
              data: r === "markdown" ? [] : L,
              chartConfig: n,
              displayConfig: a,
              queryObject: p ?? void 0,
              height: E,
              colorPalette: m,
              fallback: /* @__PURE__ */ e(
                "div",
                {
                  className: "flex items-center justify-center w-full",
                  style: { height: typeof E == "number" ? `${E}px` : E },
                  children: /* @__PURE__ */ e("div", { className: "animate-pulse bg-dc-surface-secondary rounded w-full h-full min-h-[100px]" })
                }
              )
            }
          ) : /* @__PURE__ */ e("div", { className: "flex items-center justify-center w-full", style: { height: o }, children: /* @__PURE__ */ s("div", { className: "text-center text-dc-text-muted", children: [
            /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "Unsupported chart type" }),
            /* @__PURE__ */ e("div", { className: "text-xs", children: r })
          ] }) });
        } catch (E) {
          return console.error("Chart rendering error:", E), /* @__PURE__ */ e("div", { className: "flex items-center justify-center w-full text-dc-text-muted p-4", style: { height: o }, children: /* @__PURE__ */ s("div", { className: "text-center", children: [
            /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "Unable to render chart" }),
            /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-secondary", children: E instanceof Error ? E.message : "Unknown error" })
          ] }) });
        }
      })() })
    }
  ) });
}));
gr.displayName = "AnalyticsPortlet";
function ea(t, { threshold: r = 20, debounceMs: n = 150 } = {}) {
  const [a, c] = H(!1), l = Te();
  return Ce(() => {
    const d = t.current;
    if (!d) return;
    const h = () => {
      l.current && clearTimeout(l.current), l.current = window.setTimeout(() => {
        const u = d.scrollTop > r;
        c((m) => m !== u ? u : m);
      }, n);
    };
    return d.addEventListener("scroll", h, { passive: !0 }), h(), () => {
      d.removeEventListener("scroll", h), l.current && clearTimeout(l.current);
    };
  }, [r, n]), a;
}
let xr = null, Wt = null;
async function ta() {
  if (!xr)
    return Wt || (Wt = (async () => {
      try {
        const t = await import("./core-Dkym7d1O.js"), r = await import("./javascript-DII1YQGr.js"), n = await Promise.resolve().then(() => Ea), a = await Promise.resolve().then(() => _a);
        t.default.registerLanguage("javascript", r.default), t.default.registerLanguage("sql", n.default), t.default.registerLanguage("json", a.default), xr = t.default;
      } catch (t) {
        console.error("Failed to load syntax highlighter:", t), Wt = null;
      }
    })(), Wt);
}
async function ra() {
  await ta(), xr && document.querySelectorAll("pre code").forEach((t) => {
    t.classList.contains("hljs") || xr.highlightElement(t);
  });
}
function Pn({
  chartConfig: t,
  displayConfig: r,
  queryObject: n,
  data: a,
  chartType: c
}) {
  const [l, d] = H(!1);
  return Ce(() => {
    const h = (o) => {
      o.key === "Escape" && l && d(!1);
    };
    return document.addEventListener("keydown", h), () => document.removeEventListener("keydown", h);
  }, [l]), Ce(() => {
    if (l) {
      const h = setTimeout(() => {
        ra().catch((o) => {
          console.debug("Syntax highlighting not available:", o);
        });
      }, 10);
      return () => clearTimeout(h);
    }
  }, [l]), l ? /* @__PURE__ */ e(
    "div",
    {
      className: "absolute inset-0 bg-dc-surface border border-dc-border rounded-lg z-50 overflow-auto",
      onClick: (h) => h.stopPropagation(),
      children: /* @__PURE__ */ s("div", { className: "p-4 h-full flex flex-col", children: [
        /* @__PURE__ */ s("div", { className: "flex justify-between items-center mb-4 shrink-0", children: [
          /* @__PURE__ */ e("h2", { className: "text-lg font-semibold text-dc-text", children: "Chart Debug Information" }),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => d(!1),
              className: "p-2 text-dc-text-muted hover:text-dc-text-secondary hover:bg-dc-surface-secondary rounded-sm",
              children: /* @__PURE__ */ s(
                "svg",
                {
                  width: "16",
                  height: "16",
                  viewBox: "0 0 24 24",
                  fill: "none",
                  stroke: "currentColor",
                  strokeWidth: "2",
                  children: [
                    /* @__PURE__ */ e("line", { x1: "18", y1: "6", x2: "6", y2: "18" }),
                    /* @__PURE__ */ e("line", { x1: "6", y1: "6", x2: "18", y2: "18" })
                  ]
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ s("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-4 flex-1 overflow-auto", children: [
          /* @__PURE__ */ s("div", { children: [
            /* @__PURE__ */ e("h3", { className: "text-sm font-medium text-dc-text-secondary mb-2", children: "Chart Type" }),
            /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary p-2 rounded-sm text-sm font-mono border border-dc-border", children: c })
          ] }),
          /* @__PURE__ */ s("div", { children: [
            /* @__PURE__ */ e("h3", { className: "text-sm font-medium text-dc-text-secondary mb-2", children: "Field Analysis" }),
            /* @__PURE__ */ s("div", { className: "bg-dc-surface-secondary p-2 rounded-sm text-xs space-y-1 border border-dc-border", children: [
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("strong", { children: "xAxis:" }),
                " ",
                Array.isArray(t?.xAxis) ? `Array: [${t.xAxis.join(", ")}]` : `String: "${t?.xAxis}"`
              ] }),
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("strong", { children: "yAxis:" }),
                " ",
                Array.isArray(t?.yAxis) ? `Array: [${t.yAxis.join(", ")}]` : `String: "${t?.yAxis}"`
              ] }),
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("strong", { children: "series:" }),
                " ",
                Array.isArray(t?.series) ? `Array: [${t.series.join(", ")}]` : `String: "${t?.series}"`
              ] }),
              t?.sizeField && /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("strong", { children: "sizeField:" }),
                " ",
                Array.isArray(t?.sizeField) ? `Array: [${t.sizeField.join(", ")}]` : `String: "${t?.sizeField}"`
              ] }),
              t?.colorField && /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("strong", { children: "colorField:" }),
                " ",
                Array.isArray(t?.colorField) ? `Array: [${t.colorField.join(", ")}]` : `String: "${t?.colorField}"`
              ] })
            ] })
          ] }),
          /* @__PURE__ */ s("div", { className: "lg:col-span-2", children: [
            /* @__PURE__ */ e("h3", { className: "text-sm font-medium text-dc-text-secondary mb-2", children: "Chart Config" }),
            /* @__PURE__ */ e("pre", { className: "text-dc-text-secondary overflow-x-auto font-mono p-2 rounded-sm border border-dc-border", style: { fontSize: "10px", lineHeight: "1.4" }, children: /* @__PURE__ */ e("code", { className: "language-json", children: JSON.stringify(t, null, 2) }) })
          ] }),
          /* @__PURE__ */ s("div", { className: "lg:col-span-2", children: [
            /* @__PURE__ */ e("h3", { className: "text-sm font-medium text-dc-text-secondary mb-2", children: "Display Config" }),
            /* @__PURE__ */ e("pre", { className: "text-dc-text-secondary overflow-x-auto font-mono p-2 rounded-sm border border-dc-border", style: { fontSize: "10px", lineHeight: "1.4" }, children: /* @__PURE__ */ e("code", { className: "language-json", children: JSON.stringify(r, null, 2) }) })
          ] }),
          /* @__PURE__ */ s("div", { className: "lg:col-span-2", children: [
            /* @__PURE__ */ e("h3", { className: "text-sm font-medium text-dc-text-secondary mb-2", children: "Query Object" }),
            /* @__PURE__ */ e("pre", { className: "text-dc-text-secondary overflow-x-auto font-mono p-2 rounded-sm border border-dc-border", style: { fontSize: "10px", lineHeight: "1.4" }, children: /* @__PURE__ */ e("code", { className: "language-json", children: JSON.stringify(n, null, 2) }) })
          ] }),
          /* @__PURE__ */ s("div", { className: "lg:col-span-2", children: [
            /* @__PURE__ */ e("h3", { className: "text-sm font-medium text-dc-text-secondary mb-2", children: "Data Sample (first 3 rows)" }),
            /* @__PURE__ */ e("pre", { className: "text-dc-text-secondary overflow-x-auto font-mono p-2 rounded-sm border border-dc-border", style: { fontSize: "10px", lineHeight: "1.4" }, children: /* @__PURE__ */ e("code", { className: "language-json", children: JSON.stringify(a?.slice(0, 3) || [], null, 2) }) })
          ] })
        ] }),
        /* @__PURE__ */ s("div", { className: "mt-4 pt-2 border-t border-dc-border text-xs text-dc-text-muted shrink-0", children: [
          "Press ",
          /* @__PURE__ */ e("kbd", { className: "px-1 py-0.5 bg-dc-surface-secondary rounded-sm text-xs", children: "ESC" }),
          " to close"
        ] })
      ] })
    }
  ) : /* @__PURE__ */ e(
    "button",
    {
      onClick: () => d(!0),
      className: "p-1 text-dc-text-muted hover:text-dc-text-secondary transition-colors",
      title: "Debug chart configuration",
      children: /* @__PURE__ */ s(
        "svg",
        {
          width: "16",
          height: "16",
          viewBox: "0 0 24 24",
          fill: "none",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round",
          children: [
            /* @__PURE__ */ e("circle", { cx: "12", cy: "12", r: "10" }),
            /* @__PURE__ */ e("line", { x1: "12", y1: "8", x2: "12", y2: "12" }),
            /* @__PURE__ */ e("line", { x1: "12", y1: "16", x2: "12.01", y2: "16" })
          ]
        }
      )
    }
  );
}
const Jt = { width: "16px", height: "16px", color: "currentColor" };
function na(t, r) {
  if (t === r) return !0;
  if (t.editable !== r.editable || t.isEditMode !== r.isEditMode || t.selectedFilterId !== r.selectedFilterId || t.configEagerLoad !== r.configEagerLoad || t.portlet !== r.portlet || t.debugData !== r.debugData || t.dashboardFilters !== r.dashboardFilters || t.colorPalette !== r.colorPalette || t.loadingComponent !== r.loadingComponent || t.icons !== r.icons || t.onToggleFilter !== r.onToggleFilter || t.onRefresh !== r.onRefresh || t.onDuplicate !== r.onDuplicate || t.onEdit !== r.onEdit || t.onDelete !== r.onDelete || t.onOpenFilterConfig !== r.onOpenFilterConfig || t.onDebugDataReady !== r.onDebugDataReady || t.setPortletRef !== r.setPortletRef || t.setPortletComponentRef !== r.setPortletComponentRef)
    return !1;
  const n = an(t.containerProps, r.containerProps), a = an(t.headerProps, r.headerProps);
  return n && a;
}
function an(t, r) {
  if (t === r) return !0;
  if (!t || !r) return t === r;
  const n = Object.keys(t), a = Object.keys(r);
  if (n.length !== a.length) return !1;
  for (const c of n)
    if (t[c] !== r[c]) return !1;
  return !0;
}
const sa = lt.memo(function({
  portlet: r,
  editable: n,
  isEditMode: a,
  selectedFilterId: c,
  debugData: l,
  dashboardFilters: d,
  configEagerLoad: h,
  loadingComponent: o,
  colorPalette: u,
  containerProps: m,
  headerProps: x,
  onToggleFilter: f,
  onRefresh: S,
  onDuplicate: T,
  onEdit: D,
  onDelete: k,
  onOpenFilterConfig: A,
  onDebugDataReady: _,
  setPortletRef: O,
  setPortletComponentRef: R,
  icons: y
}) {
  const i = c ? (r.dashboardFilterMapping || []).includes(c) : !1, g = !!c, p = [
    "bg-dc-surface border rounded-lg flex flex-col h-full transition-all",
    g ? "cursor-pointer" : "",
    m?.className
  ].filter(Boolean).join(" "), b = [
    "flex items-center justify-between px-3 py-1.5 md:px-4 md:py-1 border-b border-dc-border shrink-0 bg-dc-surface-secondary rounded-t-lg portlet-drag-handle",
    a ? "cursor-move" : "cursor-default",
    x?.className
  ].filter(Boolean).join(" "), {
    onClick: w,
    className: v,
    style: M,
    ...$
  } = m ?? {}, {
    onClick: C,
    className: L,
    style: I,
    ...E
  } = x ?? {}, K = F((P) => {
    _(r.id, P);
  }, [r.id, _]);
  return /* @__PURE__ */ s(
    "div",
    {
      "data-portlet-id": r.id,
      ref: (P) => O(r.id, P),
      className: p,
      style: {
        boxShadow: "var(--dc-shadow-sm)",
        borderColor: g && i ? "var(--dc-primary)" : "var(--dc-border)",
        borderWidth: g && i ? "2px" : "1px",
        backgroundColor: g && i ? "rgba(var(--dc-primary-rgb), 0.05)" : "var(--dc-surface)",
        opacity: g && !i ? "0.5" : "1",
        ...M
      },
      onClick: (P) => {
        g && c && (P.stopPropagation(), f(r.id, c)), w?.(P);
      },
      ...$,
      children: [
        (!r.displayConfig?.hideHeader || a) && /* @__PURE__ */ s(
          "div",
          {
            className: b,
            style: I,
            onClick: (P) => {
              C?.(P);
            },
            ...E,
            children: [
              /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
                /* @__PURE__ */ e("h3", { className: "font-semibold text-sm text-dc-text truncate", children: r.title }),
                n && a && l && /* @__PURE__ */ e(
                  "div",
                  {
                    onMouseDown: (P) => P.stopPropagation(),
                    onClick: (P) => P.stopPropagation(),
                    onTouchStart: (P) => P.stopPropagation(),
                    onTouchEnd: (P) => P.stopPropagation(),
                    children: /* @__PURE__ */ e(
                      Pn,
                      {
                        chartConfig: l.chartConfig,
                        displayConfig: l.displayConfig,
                        queryObject: l.queryObject,
                        data: l.data,
                        chartType: l.chartType
                      }
                    )
                  }
                )
              ] }),
              /* @__PURE__ */ s(
                "div",
                {
                  className: "flex items-center gap-1 shrink-0 ml-4 -mr-2",
                  onMouseDown: (P) => P.stopPropagation(),
                  onClick: (P) => P.stopPropagation(),
                  onTouchStart: (P) => P.stopPropagation(),
                  onTouchEnd: (P) => P.stopPropagation(),
                  children: [
                    /* @__PURE__ */ e(
                      "button",
                      {
                        onClick: (P) => {
                          P.stopPropagation(), S(r.id);
                        },
                        onTouchEnd: (P) => {
                          P.stopPropagation(), P.preventDefault(), S(r.id);
                        },
                        disabled: g,
                        className: `p-1 bg-transparent border-none rounded-sm text-dc-text-secondary transition-colors ${g ? "cursor-not-allowed opacity-50" : "cursor-pointer hover:bg-dc-surface-hover"}`,
                        title: "Refresh portlet data",
                        children: /* @__PURE__ */ e(y.RefreshIcon, { style: Jt })
                      }
                    ),
                    n && a && !g && /* @__PURE__ */ s(Ie, { children: [
                      /* @__PURE__ */ e(
                        "button",
                        {
                          onClick: (P) => {
                            P.stopPropagation(), A(r);
                          },
                          onTouchEnd: (P) => {
                            P.stopPropagation(), P.preventDefault(), A(r);
                          },
                          className: "p-1 bg-transparent border-none rounded-sm cursor-pointer hover:bg-dc-surface-hover transition-colors relative",
                          title: `Configure dashboard filters${r.dashboardFilterMapping && r.dashboardFilterMapping.length > 0 ? ` (${r.dashboardFilterMapping.length} active)` : ""}`,
                          style: {
                            color: r.dashboardFilterMapping && r.dashboardFilterMapping.length > 0 ? "var(--dc-primary)" : "var(--dc-text-secondary)"
                          },
                          children: /* @__PURE__ */ e(y.FilterIcon, { style: Jt })
                        }
                      ),
                      /* @__PURE__ */ e(
                        "button",
                        {
                          onClick: (P) => {
                            P.stopPropagation(), T(r.id);
                          },
                          onTouchEnd: (P) => {
                            P.stopPropagation(), P.preventDefault(), T(r.id);
                          },
                          className: "p-1 bg-transparent border-none rounded-sm text-dc-text-secondary cursor-pointer hover:bg-dc-surface-hover transition-colors",
                          title: "Duplicate portlet",
                          children: /* @__PURE__ */ e(y.CopyIcon, { style: Jt })
                        }
                      ),
                      /* @__PURE__ */ e(
                        "button",
                        {
                          onClick: (P) => {
                            P.stopPropagation(), D(r);
                          },
                          onTouchEnd: (P) => {
                            P.stopPropagation(), P.preventDefault(), D(r);
                          },
                          className: "p-1 bg-transparent border-none rounded-sm text-dc-text-secondary cursor-pointer hover:bg-dc-surface-hover transition-colors",
                          title: "Edit portlet",
                          children: /* @__PURE__ */ e(y.EditIcon, { style: Jt })
                        }
                      ),
                      /* @__PURE__ */ e(
                        "button",
                        {
                          onClick: (P) => {
                            P.stopPropagation(), k(r.id);
                          },
                          onTouchEnd: (P) => {
                            P.stopPropagation(), P.preventDefault(), k(r.id);
                          },
                          className: "p-1 mr-0.5 bg-transparent border-none rounded-sm cursor-pointer hover:bg-dc-danger-bg text-dc-danger transition-colors",
                          title: "Delete portlet",
                          children: /* @__PURE__ */ e(y.DeleteIcon, { style: Jt })
                        }
                      )
                    ] })
                  ]
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ e("div", { className: "flex-1 px-2 py-3 md:px-4 md:py-4 min-h-0 overflow-visible flex flex-col", children: /* @__PURE__ */ e(
          gr,
          {
            ref: (P) => R(r.id, P),
            query: r.query,
            chartType: r.chartType,
            chartConfig: r.chartConfig,
            displayConfig: r.displayConfig,
            dashboardFilters: d,
            dashboardFilterMapping: r.dashboardFilterMapping,
            eagerLoad: r.eagerLoad ?? h ?? !1,
            title: r.title,
            height: "100%",
            colorPalette: u,
            loadingComponent: o,
            onDebugDataReady: K
          }
        ) })
      ]
    }
  );
}, na), ar = 16;
function aa({
  rows: t,
  portlets: r,
  gridSettings: n,
  gridWidth: a,
  canEdit: c,
  isDragging: l,
  onRowResize: d,
  onColumnResize: h,
  onPortletDragStart: o,
  onPortletDragEnd: u,
  onRowDrop: m,
  onNewRowDrop: x,
  renderPortlet: f
}) {
  const S = new Map(r.map((i) => [i.id, i])), [T, D] = H(null), k = (i) => {
    D(i);
  }, A = l || T !== null, _ = F((i) => {
    const g = parseInt(i.currentTarget.dataset.rowIndex || "0", 10), p = parseInt(i.currentTarget.dataset.columnIndex || "0", 10), b = i.currentTarget.dataset.portletId || "";
    o(g, p, b, i);
  }, [o]), O = F(() => {
    k(null), u();
  }, [u]), R = T === "row-insert-0", y = T === "row-bottom";
  return /* @__PURE__ */ s(
    "div",
    {
      className: `dc-row-layout${c ? " dc-row-layout-editable" : ""}${A ? " dc-row-layout-dragging" : ""}`,
      style: {
        "--dc-row-gap": "24px",
        "--dc-column-gap": `${ar}px`,
        "--dc-top-drop-space": R ? "24px" : "0px",
        "--dc-bottom-drop-space": y ? "24px" : "0px"
      },
      children: [
        c && /* @__PURE__ */ e(
          "div",
          {
            className: `dc-row-boundary-drop dc-row-boundary-drop-top dc-split-handle${T === "row-insert-0" ? " dc-drop-zone-active" : ""}`,
            onDragOver: (i) => {
              i.preventDefault(), k("row-insert-0");
            },
            onDragLeave: () => k(null),
            onDrop: (i) => {
              i.preventDefault(), k(null), x(0);
            }
          }
        ),
        t.map((i, g) => {
          const p = i.h * n.rowHeight, b = a || n.cols * n.rowHeight, w = T === `row-${g}-insert-0` ? ar : 0, v = T === `row-${g}-insert-${i.columns.length}` ? ar : 0, $ = (b - (i.columns.length - 1) * ar - w - v) / n.cols;
          return /* @__PURE__ */ s("div", { className: "dc-row-layout-row-wrapper", children: [
            /* @__PURE__ */ e(
              "div",
              {
                className: "dc-row-layout-row",
                style: { height: p, paddingLeft: w, paddingRight: v },
                children: i.columns.map((C, L) => {
                  const I = S.get(C.portletId);
                  if (!I) return null;
                  const E = C.w * $, K = {
                    draggable: c,
                    "data-row-index": g.toString(),
                    "data-column-index": L.toString(),
                    "data-portlet-id": I.id,
                    onDragStart: _,
                    onDragEnd: O,
                    className: "dc-row-layout-column"
                  };
                  return /* @__PURE__ */ s(
                    "div",
                    {
                      className: "dc-row-layout-column-wrapper",
                      style: {
                        flex: `0 0 ${E}px`,
                        maxWidth: `${E}px`
                      },
                      children: [
                        f(I, K),
                        L < i.columns.length - 1 && /* @__PURE__ */ e(
                          "div",
                          {
                            className: `dc-column-resize-handle dc-split-handle${T === `row-${g}-insert-${L + 1}` ? " dc-drop-zone-active" : ""}`,
                            onMouseDown: (P) => h(g, L, P),
                            onDragOver: (P) => {
                              c && (P.preventDefault(), k(`row-${g}-insert-${L + 1}`));
                            },
                            onDragLeave: () => k(null),
                            onDrop: (P) => {
                              c && (P.preventDefault(), P.stopPropagation(), k(null), m(g, L + 1));
                            }
                          }
                        )
                      ]
                    },
                    I.id
                  );
                })
              }
            ),
            c && /* @__PURE__ */ s(Ie, { children: [
              /* @__PURE__ */ e(
                "div",
                {
                  className: `dc-row-edge-drop dc-row-edge-drop-left dc-split-handle${T === `row-${g}-insert-0` ? " dc-drop-zone-active" : ""}`,
                  onDragOver: (C) => {
                    C.preventDefault(), k(`row-${g}-insert-0`);
                  },
                  onDragLeave: () => {
                    k(null);
                  },
                  onDrop: (C) => {
                    C.preventDefault(), k(null), m(g, 0);
                  }
                }
              ),
              /* @__PURE__ */ e(
                "div",
                {
                  className: `dc-row-edge-drop dc-row-edge-drop-right dc-split-handle${T === `row-${g}-insert-${i.columns.length}` ? " dc-drop-zone-active" : ""}`,
                  onDragOver: (C) => {
                    C.preventDefault(), k(`row-${g}-insert-${i.columns.length}`);
                  },
                  onDragLeave: () => {
                    k(null);
                  },
                  onDrop: (C) => {
                    C.preventDefault(), k(null), m(g, i.columns.length);
                  }
                }
              )
            ] }),
            c && /* @__PURE__ */ e(
              "div",
              {
                className: `dc-row-resize-handle dc-split-handle${T === `row-insert-${g + 1}` ? " dc-drop-zone-active" : ""}`,
                onMouseDown: (C) => d(g, C),
                onDragOver: (C) => {
                  C.preventDefault(), k(`row-insert-${g + 1}`);
                },
                onDragLeave: () => k(null),
                onDrop: (C) => {
                  C.preventDefault(), k(null), x(g + 1);
                }
              }
            )
          ] }, i.id);
        }),
        c && /* @__PURE__ */ e(
          "div",
          {
            className: `dc-row-boundary-drop dc-row-boundary-drop-bottom dc-split-handle${T === "row-bottom" ? " dc-drop-zone-active" : ""}`,
            onDragOver: (i) => {
              i.preventDefault(), k("row-bottom");
            },
            onDragLeave: () => k(null),
            onDrop: (i) => {
              i.preventDefault(), k(null), x(t.length);
            }
          }
        )
      ]
    }
  );
}
const Pr = ({
  isOpen: t,
  onClose: r,
  title: n,
  size: a = "md",
  closeOnBackdropClick: c = !0,
  closeOnEscape: l = !0,
  showCloseButton: d = !0,
  children: h,
  footer: o,
  noPadding: u = !1
}) => {
  const m = F((f) => {
    f.key === "Escape" && l && r();
  }, [l, r]);
  return Ce(() => (t ? (l && document.addEventListener("keydown", m), document.body.style.overflow = "hidden") : document.body.style.overflow = "unset", () => {
    document.removeEventListener("keydown", m), document.body.style.overflow = "unset";
  }), [t, l, m]), t ? /* @__PURE__ */ e(
    "div",
    {
      className: `fixed inset-0 z-50 backdrop-blur-md ${a === "fullscreen-mobile" ? "flex md:flex md:items-center md:justify-center" : "flex items-center justify-center"}`,
      style: { backgroundColor: "var(--dc-overlay)" },
      onClick: c ? r : void 0,
      children: /* @__PURE__ */ s(
        "div",
        {
          className: `relative bg-dc-surface border border-dc-border ${a === "fullscreen-mobile" ? "rounded-none md:rounded-lg" : "rounded-lg"} ${a === "fullscreen" || a === "fullscreen-mobile" ? "" : "mx-4"} ${(() => {
            switch (a) {
              case "sm":
                return "max-w-md";
              case "md":
                return "max-w-lg";
              case "lg":
                return "max-w-2xl";
              case "xl":
                return "max-w-6xl";
              case "xxl":
                return "max-w-[1400px]";
              // Good for retina/mac displays
              case "full":
                return "max-w-7xl";
              case "fullscreen":
                return "w-[90vw] h-[90vh] max-w-none";
              case "fullscreen-mobile":
                return "w-full h-full md:w-[min(90vw,1400px)] md:h-[90vh]";
              default:
                return "max-w-lg";
            }
          })()} ${a === "fullscreen" || a === "fullscreen-mobile" ? "" : "max-h-[90vh]"} flex flex-col`,
          style: { boxShadow: "var(--dc-shadow-2xl)" },
          onClick: (f) => f.stopPropagation(),
          role: "dialog",
          "aria-modal": "true",
          "aria-labelledby": n ? "modal-title" : void 0,
          children: [
            (n || d) && /* @__PURE__ */ s("div", { className: "flex items-center justify-between px-6 py-4 border-b border-dc-border", children: [
              n && /* @__PURE__ */ e("h2", { id: "modal-title", className: "text-xl font-semibold text-dc-text", children: n }),
              d && /* @__PURE__ */ e(
                "button",
                {
                  type: "button",
                  onClick: r,
                  className: "text-dc-text-muted hover:text-dc-text-secondary transition-colors p-2 -mr-2",
                  "aria-label": "Close modal",
                  children: /* @__PURE__ */ e("svg", { width: "24", height: "24", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) })
                }
              )
            ] }),
            /* @__PURE__ */ e("div", { className: `flex-1 overflow-y-auto ${u ? "" : "px-6 py-4"}`, children: h }),
            o && /* @__PURE__ */ e("div", { className: "flex items-center justify-end space-x-3 px-6 py-4 border-t border-dc-border bg-dc-surface-secondary", children: lt.Children.toArray(o) })
          ]
        }
      )
    }
  ) : null;
};
function Br(t, r) {
  if (!r) return null;
  for (const n of r.cubes) {
    const a = n.measures.find((l) => l.name === t);
    if (a)
      return { field: a, cubeName: n.name, fieldType: "measure" };
    const c = n.dimensions.find((l) => l.name === t);
    if (c)
      return {
        field: c,
        cubeName: n.name,
        fieldType: c.type === "time" ? "timeDimension" : "dimension"
      };
  }
  return null;
}
function Bn(t, r) {
  const n = Br(t, r);
  return n && (n.field.title || n.field.shortTitle) || t;
}
function qn(t, r) {
  if (!t) return [];
  const n = [];
  for (const a of t.cubes)
    if (r === "metrics")
      for (const c of a.measures)
        n.push({
          name: c.name,
          title: c.title || c.shortTitle || c.name,
          shortTitle: c.shortTitle || c.title || c.name,
          type: c.type,
          description: c.description,
          cubeName: a.name,
          fieldType: "measure"
        });
    else if (r === "breakdown")
      for (const c of a.dimensions) {
        const l = c.type === "time";
        n.push({
          name: c.name,
          title: c.title || c.shortTitle || c.name,
          shortTitle: c.shortTitle || c.title || c.name,
          type: c.type,
          description: c.description,
          cubeName: a.name,
          fieldType: l ? "timeDimension" : "dimension"
        });
      }
    else {
      for (const c of a.measures)
        n.push({
          name: c.name,
          title: c.title || c.shortTitle || c.name,
          shortTitle: c.shortTitle || c.title || c.name,
          type: c.type,
          description: c.description,
          cubeName: a.name,
          fieldType: "measure"
        });
      for (const c of a.dimensions) {
        const l = c.type === "time";
        n.push({
          name: c.name,
          title: c.title || c.shortTitle || c.name,
          shortTitle: c.shortTitle || c.title || c.name,
          type: c.type,
          description: c.description,
          cubeName: a.name,
          fieldType: l ? "timeDimension" : "dimension"
        });
      }
    }
  return n;
}
function ca(t, r, n) {
  let a = t;
  if (n && n !== "all" && (a = a.filter((c) => c.cubeName === n)), r.trim()) {
    const c = r.toLowerCase();
    a = a.filter(
      (l) => l.name.toLowerCase().includes(c) || l.title.toLowerCase().includes(c) || (l.description?.toLowerCase().includes(c) ?? !1)
    );
  }
  return a;
}
function la(t) {
  const r = /* @__PURE__ */ new Map();
  for (const n of t) {
    const a = r.get(n.cubeName) || [];
    a.push(n), r.set(n.cubeName, a);
  }
  return r;
}
const Vn = "drizzle-cube-recent-fields", ia = 10;
function Hn() {
  try {
    const t = localStorage.getItem(Vn);
    if (t)
      return JSON.parse(t);
  } catch {
  }
  return { metrics: [], breakdowns: [] };
}
function oa(t, r) {
  try {
    const n = Hn(), c = n[r].filter((l) => l !== t);
    c.unshift(t), n[r] = c.slice(0, ia), localStorage.setItem(Vn, JSON.stringify(n));
  } catch {
  }
}
function da(t, r, n) {
  if (!t || n.length === 0) return [];
  const a = qn(t, r), c = [];
  for (const l of n) {
    const d = a.find((h) => h.name === l);
    d && c.push(d);
  }
  return c;
}
function ua(t) {
  return t ? t.cubes.map((r) => r.name) : [];
}
function cr(t, r) {
  return r && r.cubes.find((a) => a.name === t)?.title || t;
}
const ma = z("check");
function fa({
  field: t,
  isSelected: r,
  isFocused: n,
  onClick: a,
  onMouseEnter: c,
  ...l
}) {
  const d = () => {
    if (t.fieldType === "measure") {
      const u = qt(t.type);
      return u ? /* @__PURE__ */ e(u, { className: "w-4 h-4" }) : null;
    } else if (t.fieldType === "timeDimension") {
      const u = pr("time");
      return u ? /* @__PURE__ */ e(u, { className: "w-4 h-4" }) : null;
    } else {
      const u = pr("dimension");
      return u ? /* @__PURE__ */ e(u, { className: "w-4 h-4" }) : null;
    }
  }, h = () => t.fieldType === "measure" ? "bg-dc-measure text-dc-measure-text" : t.fieldType === "timeDimension" ? "bg-dc-time-dimension text-dc-time-dimension-text" : "bg-dc-dimension text-dc-dimension-text", o = () => t.fieldType === "measure" ? t.type.charAt(0).toUpperCase() + t.type.slice(1) : t.fieldType === "timeDimension" ? "Time" : "Dim";
  return /* @__PURE__ */ s(
    "button",
    {
      onClick: a,
      onMouseEnter: c,
      className: `w-full text-left px-3 py-2 rounded-lg flex items-center gap-3 transition-colors group ${n ? "bg-dc-primary/10 ring-1 ring-dc-primary" : r ? "bg-dc-success/10" : "hover:bg-dc-surface-hover"}`,
      ...l,
      children: [
        /* @__PURE__ */ e(
          "span",
          {
            className: `shrink-0 w-8 h-8 flex items-center justify-center rounded-md ${t.fieldType === "measure" ? "bg-dc-measure text-dc-measure-text" : t.fieldType === "timeDimension" ? "bg-dc-time-dimension text-dc-time-dimension-text" : "bg-dc-dimension text-dc-dimension-text"}`,
            children: d()
          }
        ),
        /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
          /* @__PURE__ */ e("div", { className: "text-sm font-medium text-dc-text truncate", children: t.title }),
          /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: t.name })
        ] }),
        /* @__PURE__ */ e(
          "span",
          {
            className: `shrink-0 px-2 py-0.5 rounded text-xs font-medium ${h()}`,
            children: o()
          }
        ),
        r && /* @__PURE__ */ e("span", { className: "shrink-0 w-5 h-5 flex items-center justify-center rounded-full bg-dc-success text-white", children: /* @__PURE__ */ e(ma, { className: "w-3 h-3" }) })
      ]
    }
  );
}
const cn = gt(fa);
function ha({ field: t }) {
  if (!t)
    return /* @__PURE__ */ e("div", { className: "p-6 text-center text-dc-text-muted", children: /* @__PURE__ */ e("p", { className: "text-sm", children: "Hover over a field to see details" }) });
  const r = () => {
    if (t.fieldType === "measure") {
      const c = qt(t.type);
      return c ? /* @__PURE__ */ e(c, { className: "w-6 h-6" }) : null;
    } else if (t.fieldType === "timeDimension") {
      const c = pr("time");
      return c ? /* @__PURE__ */ e(c, { className: "w-6 h-6" }) : null;
    } else {
      const c = pr("dimension");
      return c ? /* @__PURE__ */ e(c, { className: "w-6 h-6" }) : null;
    }
  }, n = () => t.fieldType === "measure" ? "bg-dc-measure text-dc-measure-text" : t.fieldType === "timeDimension" ? "bg-dc-time-dimension text-dc-time-dimension-text" : "bg-dc-dimension text-dc-dimension-text", a = () => t.fieldType === "measure" ? {
    count: "Count",
    countDistinct: "Count Distinct",
    countDistinctApprox: "Count Distinct (Approx)",
    sum: "Sum",
    avg: "Average",
    min: "Minimum",
    max: "Maximum",
    runningTotal: "Running Total",
    number: "Number"
  }[t.type] || t.type : t.fieldType === "timeDimension" ? "Time Dimension" : {
    string: "Text",
    number: "Number",
    boolean: "Boolean",
    geo: "Geographic"
  }[t.type] || "Dimension";
  return /* @__PURE__ */ s("div", { className: "p-4", children: [
    /* @__PURE__ */ s("div", { className: "flex items-start gap-3 mb-4", children: [
      /* @__PURE__ */ e(
        "span",
        {
          className: `shrink-0 w-12 h-12 flex items-center justify-center rounded-lg ${n()}`,
          children: r()
        }
      ),
      /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
        /* @__PURE__ */ e("h3", { className: "text-base font-semibold text-dc-text leading-tight", children: t.title }),
        /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted mt-0.5 truncate", children: t.name })
      ] })
    ] }),
    t.description && /* @__PURE__ */ e("div", { className: "mb-4", children: /* @__PURE__ */ e("p", { className: "text-sm text-dc-text-secondary leading-relaxed", children: t.description }) }),
    /* @__PURE__ */ s("div", { className: "space-y-3 pt-4 border-t border-dc-border", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted", children: "Type" }),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text font-medium", children: a() })
      ] }),
      /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted", children: "Cube" }),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text font-medium", children: t.cubeName })
      ] }),
      /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted", children: "Category" }),
        /* @__PURE__ */ e(
          "span",
          {
            className: `text-xs px-2 py-0.5 rounded font-medium ${t.fieldType === "measure" ? "bg-dc-measure text-dc-measure-text" : t.fieldType === "timeDimension" ? "bg-dc-time-dimension text-dc-time-dimension-text" : "bg-dc-dimension text-dc-dimension-text"}`,
            children: t.fieldType === "measure" ? "Measure" : t.fieldType === "timeDimension" ? "Time Dimension" : "Dimension"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ e("div", { className: "mt-6 p-3 bg-dc-surface rounded-lg", children: /* @__PURE__ */ s("p", { className: "text-xs text-dc-text-muted", children: [
      "Press ",
      /* @__PURE__ */ e("kbd", { className: "px-1 py-0.5 bg-dc-surface-tertiary rounded text-xs", children: "Enter" }),
      " or click to add this field to your query."
    ] }) })
  ] });
}
const pa = gt(ha), xa = z("search"), ba = z("close");
function zn({
  isOpen: t,
  onClose: r,
  onSelect: n,
  mode: a,
  schema: c,
  selectedFields: l,
  recentFields: d
}) {
  const [h, o] = H(""), [u, m] = H(null), [x, f] = H(null), [S, T] = H(-1), [D, k] = H(null), A = Te(null), _ = Te(null), O = Oe(() => {
    if (d) return d;
    const E = Hn();
    return a === "metrics" ? E.metrics : E.breakdowns;
  }, [d, a]), R = a, y = Oe(() => qn(c, R), [c, R]), i = Oe(() => ua(c), [c]), g = Oe(() => ca(y, h, u), [y, h, u]), p = Oe(() => la(g), [g]), b = Oe(() => h.trim() ? [] : da(c, R, O).filter(
    (E) => !u || E.cubeName === u
  ), [c, R, O, h, u]), w = Oe(() => {
    const E = [...b];
    return p.forEach((K) => {
      E.push(...K);
    }), E;
  }, [b, p]);
  Ce(() => {
    t && A.current && A.current.focus();
  }, [t]), Ce(() => {
    t || (o(""), m(null), f(null), T(-1), k(null));
  }, [t]);
  const v = F(
    (E, K = !1) => {
      oa(E.name, a === "metrics" ? "metrics" : "breakdowns");
      const P = {
        name: E.name,
        title: E.title,
        shortTitle: E.shortTitle,
        type: E.type,
        description: E.description
      };
      n(P, E.fieldType, E.cubeName, K);
    },
    [a, n]
  ), M = F(
    (E, K, P = !1) => {
      if (P && D !== null && D !== K) {
        const Ne = Math.min(D, K), ye = Math.max(D, K);
        for (let Ue = Ne; Ue <= ye; Ue++) {
          const Q = w[Ue];
          Q && !l.includes(Q.name) && v(Q, !0);
        }
      } else P ? v(E, !0) : v(E, !1);
      k(K);
    },
    [w, D, v, l]
  ), $ = F(
    (E) => {
      if (w.length !== 0)
        switch (E.key) {
          case "ArrowDown":
            E.preventDefault(), T((K) => {
              const P = Math.min(K + 1, w.length - 1);
              return f(w[P]), P;
            });
            break;
          case "ArrowUp":
            E.preventDefault(), T((K) => {
              const P = Math.max(K - 1, 0);
              return f(w[P]), P;
            });
            break;
          case "Enter":
            E.preventDefault(), S >= 0 && w[S] && M(w[S], S, E.shiftKey);
            break;
          case "Escape":
            E.preventDefault(), r();
            break;
        }
    },
    [w, S, M, r]
  );
  if (Ce(() => {
    if (S >= 0 && _.current) {
      const E = _.current.querySelector(
        `[data-field-index="${S}"]`
      );
      E && E.scrollIntoView({ block: "nearest", behavior: "smooth" });
    }
  }, [S]), !t) return null;
  const C = a === "metrics" ? "Search metrics..." : a === "filter" ? "Search fields to filter..." : "Search dimensions...", L = a === "metrics" ? "Select a Metric" : a === "filter" ? "Select a Field to Filter" : "Select a Dimension", I = S >= 0 && w[S] ? `field-option-${w[S].name.replace(/\./g, "-")}` : void 0;
  return /* @__PURE__ */ e(
    "div",
    {
      className: "fixed inset-0 z-50 flex items-center justify-center",
      style: { backgroundColor: "var(--dc-overlay)" },
      onClick: r,
      role: "presentation",
      children: /* @__PURE__ */ s(
        "div",
        {
          role: "dialog",
          "aria-modal": "true",
          "aria-label": L,
          className: "bg-dc-surface shadow-xl w-full h-full md:rounded-lg md:w-[900px] md:max-w-[900px] md:h-[80vh] md:max-h-[700px] flex flex-col overflow-hidden",
          onClick: (E) => E.stopPropagation(),
          onKeyDown: $,
          children: [
            /* @__PURE__ */ s("div", { className: "shrink-0 border-b border-dc-border", children: [
              /* @__PURE__ */ s("div", { className: "flex items-center px-4 py-3 gap-3", children: [
                /* @__PURE__ */ e(xa, { className: "w-5 h-5 text-dc-text-muted", "aria-hidden": !0 }),
                /* @__PURE__ */ e(
                  "input",
                  {
                    ref: A,
                    type: "text",
                    value: h,
                    onChange: (E) => {
                      o(E.target.value), T(-1);
                    },
                    placeholder: C,
                    className: "flex-1 bg-transparent border-none outline-none text-dc-text placeholder-dc-text-muted text-lg",
                    "aria-label": C,
                    "aria-controls": "field-search-results",
                    "aria-activedescendant": I,
                    role: "combobox",
                    "aria-expanded": "true",
                    "aria-autocomplete": "list"
                  }
                ),
                /* @__PURE__ */ e(
                  "button",
                  {
                    onClick: r,
                    className: "p-1 text-dc-text-secondary hover:text-dc-text rounded",
                    "aria-label": "Close dialog",
                    children: /* @__PURE__ */ e(ba, { className: "w-5 h-5", "aria-hidden": !0 })
                  }
                )
              ] }),
              i.length > 1 && /* @__PURE__ */ e("div", { className: "md:hidden px-4 pb-3", children: /* @__PURE__ */ s(
                "select",
                {
                  value: u || "",
                  onChange: (E) => m(E.target.value || null),
                  className: "w-full px-3 py-2 bg-dc-surface border border-dc-border rounded-lg text-sm text-dc-text focus:outline-none focus:ring-1 focus:ring-dc-primary",
                  "aria-label": "Filter by cube",
                  children: [
                    /* @__PURE__ */ e("option", { value: "", children: "All Cubes" }),
                    i.map((E) => /* @__PURE__ */ e("option", { value: E, children: cr(E, c) }, E))
                  ]
                }
              ) })
            ] }),
            /* @__PURE__ */ s("div", { className: "flex-1 flex overflow-hidden", children: [
              /* @__PURE__ */ e(
                "nav",
                {
                  className: "hidden md:block w-48 shrink-0 border-r border-dc-border overflow-y-auto bg-dc-surface-secondary",
                  "aria-label": "Filter by cube",
                  children: /* @__PURE__ */ s("div", { className: "p-2", role: "group", "aria-label": "Cube categories", children: [
                    /* @__PURE__ */ e(
                      "button",
                      {
                        onClick: () => m(null),
                        className: `w-full text-left px-3 py-2 rounded-md text-sm transition-colors ${u === null ? "bg-dc-primary/10 text-dc-primary font-medium" : "text-dc-text hover:bg-dc-surface-hover"}`,
                        "aria-pressed": u === null,
                        children: "All"
                      }
                    ),
                    i.map((E) => /* @__PURE__ */ e(
                      "button",
                      {
                        onClick: () => m(E),
                        className: `w-full text-left px-3 py-2 rounded-md text-sm transition-colors truncate ${u === E ? "bg-dc-primary/10 text-dc-primary font-medium" : "text-dc-text hover:bg-dc-surface-hover"}`,
                        title: cr(E, c),
                        "aria-pressed": u === E,
                        children: cr(E, c)
                      },
                      E
                    ))
                  ] })
                }
              ),
              /* @__PURE__ */ e(
                "div",
                {
                  id: "field-search-results",
                  ref: _,
                  className: "flex-1 overflow-y-auto p-4",
                  role: "listbox",
                  "aria-label": "Available fields",
                  children: g.length === 0 && b.length === 0 ? /* @__PURE__ */ s("div", { className: "text-center py-12 text-dc-text-muted", children: [
                    /* @__PURE__ */ e("p", { className: "text-lg mb-2", children: "No fields found" }),
                    /* @__PURE__ */ e("p", { className: "text-sm", children: h ? `No ${a === "metrics" ? "metrics" : "dimensions"} match "${h}"` : `No ${a === "metrics" ? "metrics" : "dimensions"} available` })
                  ] }) : /* @__PURE__ */ s("div", { className: "space-y-6", children: [
                    b.length > 0 && /* @__PURE__ */ s("div", { children: [
                      /* @__PURE__ */ e("h3", { className: "text-xs font-semibold text-dc-text-muted uppercase tracking-wider mb-2", children: "Recents" }),
                      /* @__PURE__ */ e("div", { className: "space-y-1", children: b.map((E, K) => /* @__PURE__ */ e(
                        cn,
                        {
                          field: E,
                          isSelected: l.includes(E.name),
                          isFocused: S === K,
                          onClick: (P) => M(E, K, P.shiftKey),
                          onMouseEnter: () => {
                            f(E), T(K);
                          },
                          "data-field-index": K
                        },
                        `recent-${E.name}`
                      )) })
                    ] }),
                    Array.from(p.entries()).map(([E, K]) => /* @__PURE__ */ s("div", { children: [
                      /* @__PURE__ */ e("h3", { className: "text-xs font-semibold text-dc-text-muted uppercase tracking-wider mb-2", children: cr(E, c) }),
                      /* @__PURE__ */ e("div", { className: "space-y-1", children: K.map((P) => {
                        const Ne = b.length + Array.from(p.entries()).slice(
                          0,
                          Array.from(p.keys()).indexOf(E)
                        ).reduce((ye, [, Ue]) => ye + Ue.length, 0) + K.indexOf(P);
                        return /* @__PURE__ */ e(
                          cn,
                          {
                            field: P,
                            isSelected: l.includes(P.name),
                            isFocused: S === Ne,
                            onClick: (ye) => M(P, Ne, ye.shiftKey),
                            onMouseEnter: () => {
                              f(P), T(Ne);
                            },
                            "data-field-index": Ne
                          },
                          P.name
                        );
                      }) })
                    ] }, E))
                  ] })
                }
              ),
              /* @__PURE__ */ e("div", { className: "hidden md:block w-72 shrink-0 border-l border-dc-border bg-dc-surface-secondary overflow-y-auto", children: /* @__PURE__ */ e(pa, { field: x }) })
            ] }),
            /* @__PURE__ */ s("div", { className: "shrink-0 border-t border-dc-border px-4 py-3 flex items-center justify-between text-sm text-dc-text-muted", children: [
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("span", { className: "text-dc-text-secondary", children: g.length }),
                " ",
                a === "metrics" ? "metrics" : a === "filter" ? "fields" : "dimensions",
                " available"
              ] }),
              /* @__PURE__ */ s("div", { className: "hidden md:flex items-center gap-4", children: [
                /* @__PURE__ */ s("span", { children: [
                  /* @__PURE__ */ e("kbd", { className: "px-1.5 py-0.5 bg-dc-surface-tertiary rounded text-xs", children: "↑↓" }),
                  " Navigate"
                ] }),
                /* @__PURE__ */ s("span", { children: [
                  /* @__PURE__ */ e("kbd", { className: "px-1.5 py-0.5 bg-dc-surface-tertiary rounded text-xs", children: "Enter" }),
                  " Select"
                ] }),
                /* @__PURE__ */ s("span", { children: [
                  /* @__PURE__ */ e("kbd", { className: "px-1.5 py-0.5 bg-dc-surface-tertiary rounded text-xs", children: "Shift" }),
                  "+Click Multi-select"
                ] }),
                /* @__PURE__ */ s("span", { children: [
                  /* @__PURE__ */ e("kbd", { className: "px-1.5 py-0.5 bg-dc-surface-tertiary rounded text-xs", children: "Esc" }),
                  " Close"
                ] })
              ] })
            ] })
          ]
        }
      )
    }
  );
}
const Zt = {
  // String operators
  equals: {
    label: "equals",
    description: "Exact match",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "any",
    fieldTypes: ["string", "number", "boolean", "time"]
  },
  notEquals: {
    label: "not equals",
    description: "Does not match",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "any",
    fieldTypes: ["string", "number", "boolean", "time"]
  },
  contains: {
    label: "contains",
    description: "Contains text (case insensitive)",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  notContains: {
    label: "not contains",
    description: "Does not contain text",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  startsWith: {
    label: "starts with",
    description: "Starts with text",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  notStartsWith: {
    label: "not starts with",
    description: "Does not start with text",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  endsWith: {
    label: "ends with",
    description: "Ends with text",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  notEndsWith: {
    label: "not ends with",
    description: "Does not end with text",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  like: {
    label: "like",
    description: "SQL LIKE pattern matching (case sensitive)",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  notLike: {
    label: "not like",
    description: "SQL NOT LIKE pattern matching (case sensitive)",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  ilike: {
    label: "ilike",
    description: "SQL ILIKE pattern matching (case insensitive)",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  // Numeric operators
  gt: {
    label: "greater than",
    description: "Greater than value",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "number",
    fieldTypes: ["number", "count", "sum", "avg", "min", "max"]
  },
  gte: {
    label: "greater than or equal",
    description: "Greater than or equal to value",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "number",
    fieldTypes: ["number", "count", "sum", "avg", "min", "max"]
  },
  lt: {
    label: "less than",
    description: "Less than value",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "number",
    fieldTypes: ["number", "count", "sum", "avg", "min", "max"]
  },
  lte: {
    label: "less than or equal",
    description: "Less than or equal to value",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "number",
    fieldTypes: ["number", "count", "sum", "avg", "min", "max"]
  },
  between: {
    label: "between",
    description: "Between two values (inclusive)",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "number",
    fieldTypes: ["number", "count", "sum", "avg", "min", "max"]
  },
  notBetween: {
    label: "not between",
    description: "Not between two values",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "number",
    fieldTypes: ["number", "count", "sum", "avg", "min", "max"]
  },
  // Array operators
  in: {
    label: "in",
    description: "Matches any of the provided values",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "any",
    fieldTypes: ["string", "number", "boolean"]
  },
  notIn: {
    label: "not in",
    description: "Does not match any of the provided values",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "any",
    fieldTypes: ["string", "number", "boolean"]
  },
  // Null/Empty operators
  set: {
    label: "is set",
    description: "Is not null/empty",
    requiresValues: !1,
    supportsMultipleValues: !1,
    valueType: "any",
    fieldTypes: ["string", "number", "time", "boolean"]
  },
  notSet: {
    label: "is not set",
    description: "Is null/empty",
    requiresValues: !1,
    supportsMultipleValues: !1,
    valueType: "any",
    fieldTypes: ["string", "number", "time", "boolean"]
  },
  isEmpty: {
    label: "is empty",
    description: "Is empty string or null",
    requiresValues: !1,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  isNotEmpty: {
    label: "is not empty",
    description: "Is not empty string and not null",
    requiresValues: !1,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  // Date operators
  inDateRange: {
    label: "in date range",
    description: "Between two dates",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "date",
    fieldTypes: ["time"]
  },
  beforeDate: {
    label: "before date",
    description: "Before specified date",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "date",
    fieldTypes: ["time"]
  },
  afterDate: {
    label: "after date",
    description: "After specified date",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "date",
    fieldTypes: ["time"]
  },
  // Regex operators
  regex: {
    label: "matches regex",
    description: "Matches regular expression pattern",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  notRegex: {
    label: "not matches regex",
    description: "Does not match regular expression pattern",
    requiresValues: !0,
    supportsMultipleValues: !1,
    valueType: "string",
    fieldTypes: ["string"]
  },
  // PostgreSQL array operators
  arrayContains: {
    label: "array contains all",
    description: "Array field contains all specified values (PostgreSQL only)",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "string",
    fieldTypes: ["string"]
  },
  arrayOverlaps: {
    label: "array contains any",
    description: "Array field contains any of the specified values (PostgreSQL only)",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "string",
    fieldTypes: ["string"]
  },
  arrayContained: {
    label: "array values in",
    description: "All array field values are within specified values (PostgreSQL only)",
    requiresValues: !0,
    supportsMultipleValues: !0,
    valueType: "string",
    fieldTypes: ["string"]
  }
}, bt = [
  { value: "custom", label: "Custom" },
  { value: "today", label: "Today" },
  { value: "yesterday", label: "Yesterday" },
  { value: "this_week", label: "This week" },
  { value: "this_month", label: "This month" },
  { value: "this_quarter", label: "This quarter" },
  { value: "this_year", label: "This year" },
  { value: "last_7_days", label: "Last 7 days" },
  { value: "last_30_days", label: "Last 30 days" },
  { value: "last_n_days", label: "Last N days" },
  { value: "last_week", label: "Last week" },
  { value: "last_n_weeks", label: "Last N weeks" },
  { value: "last_month", label: "Last month" },
  { value: "last_12_months", label: "Last 12 months" },
  { value: "last_n_months", label: "Last N months" },
  { value: "last_quarter", label: "Last quarter" },
  { value: "last_n_quarters", label: "Last N quarters" },
  { value: "last_year", label: "Last year" },
  { value: "last_n_years", label: "Last N years" }
];
function ga(t) {
  return "member" in t && "operator" in t && "values" in t;
}
function ya(t) {
  return "type" in t && "filters" in t;
}
function va(t) {
  const r = (n) => {
    if (ga(n))
      return n;
    if (ya(n)) {
      const a = n.filters.map(r);
      return n.type === "and" ? { and: a } : { or: a };
    }
    return n;
  };
  return t.map(r);
}
function Na(t) {
  const r = {};
  return t.measures && t.measures.length > 0 && (r.measures = t.measures), t.dimensions && t.dimensions.length > 0 && (r.dimensions = t.dimensions), t.timeDimensions && t.timeDimensions.length > 0 && (r.timeDimensions = t.timeDimensions), t.filters && t.filters.length > 0 && (r.filters = t.filters), t.order && (r.order = t.order), t.limit && (r.limit = t.limit), t.offset && (r.offset = t.offset), t.segments && t.segments.length > 0 && (r.segments = t.segments), r;
}
function wa(t) {
  const r = Na(t);
  return r.filters && r.filters.length > 0 && (r.filters = va(r.filters)), r;
}
function ka(t) {
  const r = [];
  for (const [n, a] of Object.entries(Zt))
    a.fieldTypes.includes(t) && r.push({
      operator: n,
      label: a.label
    });
  return r;
}
function Kt(t, r) {
  const n = {
    today: "today",
    yesterday: "yesterday",
    this_week: "this week",
    this_month: "this month",
    this_quarter: "this quarter",
    this_year: "this year",
    last_7_days: "last 7 days",
    last_30_days: "last 30 days",
    last_week: "last week",
    last_month: "last month",
    last_quarter: "last quarter",
    last_year: "last year",
    last_12_months: "last 12 months"
  };
  if (t.startsWith("last_n_") && r !== void 0 && r > 0) {
    const a = t.replace("last_n_", ""), c = a.slice(0, -1);
    return r === 1 ? `last ${c}` : `last ${r} ${a}`;
  }
  return n[t] || t;
}
function lr(t) {
  return t.startsWith("last_n_");
}
function ln(t) {
  return t.replace(/_/g, " ");
}
function Ca(t) {
  switch (t) {
    case "most_dimensions":
      return "bg-dc-info-bg text-dc-info";
    case "most_connected":
      return "bg-dc-accent-bg text-dc-accent";
    case "alphabetical_fallback":
      return "bg-dc-warning-bg text-dc-warning";
    case "single_cube":
      return "bg-dc-success-bg text-dc-success";
    default:
      return "bg-dc-muted-bg text-dc-muted";
  }
}
const Da = ({ analysis: t }) => {
  const r = z("info"), n = z("chevronRight"), a = z("warning"), c = z("table"), l = z("link"), d = z("success"), h = z("error");
  return /* @__PURE__ */ s("div", { className: "bg-dc-surface-secondary border border-dc-border rounded-lg p-4 space-y-4", children: [
    /* @__PURE__ */ s("div", { className: "border-b border-dc-border pb-3", children: [
      /* @__PURE__ */ s("h4", { className: "text-sm font-semibold text-dc-text mb-2 flex items-center", children: [
        /* @__PURE__ */ e(r, { className: "w-4 h-4 mr-2" }),
        "Query Summary"
      ] }),
      /* @__PURE__ */ s("div", { className: "grid grid-cols-2 md:grid-cols-4 gap-2 text-xs", children: [
        /* @__PURE__ */ s("div", { className: "bg-dc-surface p-2 rounded", children: [
          /* @__PURE__ */ e("span", { className: "text-dc-text-muted", children: "Type:" }),
          /* @__PURE__ */ e("span", { className: "ml-1 font-medium text-dc-text", children: ln(t.querySummary.queryType) })
        ] }),
        /* @__PURE__ */ s("div", { className: "bg-dc-surface p-2 rounded", children: [
          /* @__PURE__ */ e("span", { className: "text-dc-text-muted", children: "Cubes:" }),
          /* @__PURE__ */ e("span", { className: "ml-1 font-medium text-dc-text", children: t.cubeCount })
        ] }),
        /* @__PURE__ */ s("div", { className: "bg-dc-surface p-2 rounded", children: [
          /* @__PURE__ */ e("span", { className: "text-dc-text-muted", children: "Joins:" }),
          /* @__PURE__ */ e("span", { className: "ml-1 font-medium text-dc-text", children: t.querySummary.joinCount })
        ] }),
        /* @__PURE__ */ s("div", { className: "bg-dc-surface p-2 rounded", children: [
          /* @__PURE__ */ e("span", { className: "text-dc-text-muted", children: "CTEs:" }),
          /* @__PURE__ */ e("span", { className: "ml-1 font-medium text-dc-text", children: t.querySummary.cteCount })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ s("div", { className: "border-b border-dc-border pb-3", children: [
      /* @__PURE__ */ s("h4", { className: "text-sm font-semibold text-dc-text mb-2 flex items-center", children: [
        /* @__PURE__ */ e(c, { className: "w-4 h-4 mr-2" }),
        "Primary Cube (FROM table)"
      ] }),
      /* @__PURE__ */ s("div", { className: "bg-dc-surface p-3 rounded text-sm", children: [
        /* @__PURE__ */ s("div", { className: "flex items-center gap-2 mb-2 flex-wrap", children: [
          /* @__PURE__ */ e("span", { className: "font-mono font-medium text-dc-primary", children: t.primaryCube.selectedCube }),
          /* @__PURE__ */ e("span", { className: `text-xs px-2 py-0.5 rounded ${Ca(t.primaryCube.reason)}`, children: ln(t.primaryCube.reason) })
        ] }),
        /* @__PURE__ */ e("p", { className: "text-dc-text-secondary text-xs", children: t.primaryCube.explanation }),
        t.primaryCube.candidates && t.primaryCube.candidates.length > 1 && /* @__PURE__ */ s("details", { className: "mt-2", children: [
          /* @__PURE__ */ s("summary", { className: "text-xs text-dc-text-muted cursor-pointer hover:text-dc-text", children: [
            "Show candidates (",
            t.primaryCube.candidates.length,
            ")"
          ] }),
          /* @__PURE__ */ e("div", { className: "mt-2 space-y-1 ml-2", children: t.primaryCube.candidates.map((o, u) => /* @__PURE__ */ s("div", { className: "text-xs flex items-center gap-2 flex-wrap", children: [
            /* @__PURE__ */ e("span", { className: `font-mono ${o.cubeName === t.primaryCube.selectedCube ? "font-bold text-dc-primary" : "text-dc-text-muted"}`, children: o.cubeName }),
            /* @__PURE__ */ s("span", { className: "text-dc-text-muted", children: [
              "dims: ",
              o.dimensionCount,
              ", joins: ",
              o.joinCount
            ] }),
            o.canReachAll ? /* @__PURE__ */ s("span", { className: "text-dc-success flex items-center gap-0.5", children: [
              /* @__PURE__ */ e(d, { className: "w-3 h-3" }),
              "reachable"
            ] }) : /* @__PURE__ */ s("span", { className: "text-dc-error flex items-center gap-0.5", children: [
              /* @__PURE__ */ e(h, { className: "w-3 h-3" }),
              "cannot reach all"
            ] })
          ] }, u)) })
        ] })
      ] })
    ] }),
    t.joinPaths.length > 0 && /* @__PURE__ */ s("div", { className: "border-b border-dc-border pb-3", children: [
      /* @__PURE__ */ s("h4", { className: "text-sm font-semibold text-dc-text mb-2 flex items-center", children: [
        /* @__PURE__ */ e(l, { className: "w-4 h-4 mr-2" }),
        "Join Paths"
      ] }),
      /* @__PURE__ */ e("div", { className: "space-y-2", children: t.joinPaths.map((o, u) => /* @__PURE__ */ s("div", { className: "bg-dc-surface p-3 rounded text-sm", children: [
        /* @__PURE__ */ s("div", { className: "flex items-center gap-2 mb-2 flex-wrap", children: [
          /* @__PURE__ */ e("span", { className: "font-mono text-dc-text-secondary", children: t.primaryCube.selectedCube }),
          /* @__PURE__ */ e(n, { className: "w-4 h-4 text-dc-text-muted" }),
          /* @__PURE__ */ e("span", { className: "font-mono font-medium text-dc-text", children: o.targetCube }),
          o.pathFound ? /* @__PURE__ */ s("span", { className: "text-xs px-2 py-0.5 bg-dc-success-bg text-dc-success rounded", children: [
            o.pathLength,
            " step",
            o.pathLength !== 1 ? "s" : ""
          ] }) : /* @__PURE__ */ e("span", { className: "text-xs px-2 py-0.5 bg-dc-error-bg text-dc-error rounded", children: "No path" })
        ] }),
        o.pathFound && o.path && o.path.length > 0 && /* @__PURE__ */ e("div", { className: "space-y-1 ml-2", children: o.path.map((m, x) => /* @__PURE__ */ s("div", { className: "flex items-center gap-1 text-xs flex-wrap", children: [
          /* @__PURE__ */ e("span", { className: "font-mono text-dc-text-secondary", children: m.fromCube }),
          /* @__PURE__ */ e(n, { className: "w-3 h-3 text-dc-text-muted" }),
          /* @__PURE__ */ e("span", { className: "font-mono text-dc-text", children: m.toCube }),
          /* @__PURE__ */ s("span", { className: "text-dc-text-muted", children: [
            "(",
            m.relationship,
            ", ",
            m.joinType,
            " join)"
          ] }),
          m.joinColumns.length > 0 && /* @__PURE__ */ s("span", { className: "text-dc-text-muted", children: [
            "on ",
            m.joinColumns.map((f) => `${f.sourceColumn}=${f.targetColumn}`).join(", ")
          ] })
        ] }, x)) }),
        !o.pathFound && o.error && /* @__PURE__ */ e("p", { className: "text-xs text-dc-error mt-1", children: o.error }),
        o.visitedCubes && o.visitedCubes.length > 0 && !o.pathFound && /* @__PURE__ */ s("details", { className: "mt-1", children: [
          /* @__PURE__ */ s("summary", { className: "text-xs text-dc-text-muted cursor-pointer hover:text-dc-text", children: [
            "Cubes visited during search (",
            o.visitedCubes.length,
            ")"
          ] }),
          /* @__PURE__ */ e("div", { className: "mt-1 text-xs text-dc-text-muted ml-2", children: o.visitedCubes.join(" → ") })
        ] })
      ] }, u)) })
    ] }),
    t.preAggregations.length > 0 && /* @__PURE__ */ s("div", { className: "border-b border-dc-border pb-3", children: [
      /* @__PURE__ */ s("h4", { className: "text-sm font-semibold text-dc-text mb-2 flex items-center", children: [
        /* @__PURE__ */ e(c, { className: "w-4 h-4 mr-2" }),
        "Pre-Aggregation CTEs"
      ] }),
      /* @__PURE__ */ e("div", { className: "space-y-2", children: t.preAggregations.map((o, u) => /* @__PURE__ */ s("div", { className: "bg-dc-surface p-3 rounded text-sm", children: [
        /* @__PURE__ */ s("div", { className: "flex items-center gap-2 mb-1 flex-wrap", children: [
          /* @__PURE__ */ e("span", { className: "font-mono font-medium text-dc-text", children: o.cubeName }),
          /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted", children: "as" }),
          /* @__PURE__ */ e("code", { className: "text-xs bg-dc-surface-secondary px-1 rounded font-mono", children: o.cteAlias })
        ] }),
        /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-secondary", children: o.reason }),
        /* @__PURE__ */ s("div", { className: "mt-1 text-xs text-dc-text-muted", children: [
          /* @__PURE__ */ e("span", { className: "font-medium", children: "Measures:" }),
          " ",
          o.measures.join(", ")
        ] }),
        o.joinKeys.length > 0 && /* @__PURE__ */ s("div", { className: "mt-1 text-xs text-dc-text-muted", children: [
          /* @__PURE__ */ e("span", { className: "font-medium", children: "Join keys:" }),
          " ",
          o.joinKeys.map((m) => `${m.sourceColumn}=${m.targetColumn}`).join(", ")
        ] })
      ] }, u)) })
    ] }),
    t.warnings && t.warnings.length > 0 && /* @__PURE__ */ s("div", { children: [
      /* @__PURE__ */ s("h4", { className: "text-sm font-semibold text-dc-warning mb-2 flex items-center", children: [
        /* @__PURE__ */ e(a, { className: "w-4 h-4 mr-2" }),
        "Warnings"
      ] }),
      /* @__PURE__ */ e("ul", { className: "list-disc list-inside text-xs text-dc-warning space-y-1", children: t.warnings.map((o, u) => /* @__PURE__ */ e("li", { children: o }, u)) })
    ] }),
    t.cubesInvolved.length > 0 && /* @__PURE__ */ s("div", { className: "text-xs text-dc-text-muted pt-2 border-t border-dc-border", children: [
      /* @__PURE__ */ e("span", { className: "font-medium", children: "Cubes involved:" }),
      " ",
      t.cubesInvolved.join(", ")
    ] })
  ] });
};
function Ta(t) {
  return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
}
var kr, on;
function Sa() {
  if (on) return kr;
  on = 1;
  function t(N) {
    return N instanceof Map ? N.clear = N.delete = N.set = function() {
      throw new Error("map is read-only");
    } : N instanceof Set && (N.add = N.clear = N.delete = function() {
      throw new Error("set is read-only");
    }), Object.freeze(N), Object.getOwnPropertyNames(N).forEach((q) => {
      const Z = N[q], we = typeof Z;
      (we === "object" || we === "function") && !Object.isFrozen(Z) && t(Z);
    }), N;
  }
  class r {
    /**
     * @param {CompiledMode} mode
     */
    constructor(q) {
      q.data === void 0 && (q.data = {}), this.data = q.data, this.isMatchIgnored = !1;
    }
    ignoreMatch() {
      this.isMatchIgnored = !0;
    }
  }
  function n(N) {
    return N.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
  }
  function a(N, ...q) {
    const Z = /* @__PURE__ */ Object.create(null);
    for (const we in N)
      Z[we] = N[we];
    return q.forEach(function(we) {
      for (const Ve in we)
        Z[Ve] = we[Ve];
    }), /** @type {T} */
    Z;
  }
  const c = "</span>", l = (N) => !!N.scope, d = (N, { prefix: q }) => {
    if (N.startsWith("language:"))
      return N.replace("language:", "language-");
    if (N.includes(".")) {
      const Z = N.split(".");
      return [
        `${q}${Z.shift()}`,
        ...Z.map((we, Ve) => `${we}${"_".repeat(Ve + 1)}`)
      ].join(" ");
    }
    return `${q}${N}`;
  };
  class h {
    /**
     * Creates a new HTMLRenderer
     *
     * @param {Tree} parseTree - the parse tree (must support `walk` API)
     * @param {{classPrefix: string}} options
     */
    constructor(q, Z) {
      this.buffer = "", this.classPrefix = Z.classPrefix, q.walk(this);
    }
    /**
     * Adds texts to the output stream
     *
     * @param {string} text */
    addText(q) {
      this.buffer += n(q);
    }
    /**
     * Adds a node open to the output stream (if needed)
     *
     * @param {Node} node */
    openNode(q) {
      if (!l(q)) return;
      const Z = d(
        q.scope,
        { prefix: this.classPrefix }
      );
      this.span(Z);
    }
    /**
     * Adds a node close to the output stream (if needed)
     *
     * @param {Node} node */
    closeNode(q) {
      l(q) && (this.buffer += c);
    }
    /**
     * returns the accumulated buffer
    */
    value() {
      return this.buffer;
    }
    // helpers
    /**
     * Builds a span element
     *
     * @param {string} className */
    span(q) {
      this.buffer += `<span class="${q}">`;
    }
  }
  const o = (N = {}) => {
    const q = { children: [] };
    return Object.assign(q, N), q;
  };
  class u {
    constructor() {
      this.rootNode = o(), this.stack = [this.rootNode];
    }
    get top() {
      return this.stack[this.stack.length - 1];
    }
    get root() {
      return this.rootNode;
    }
    /** @param {Node} node */
    add(q) {
      this.top.children.push(q);
    }
    /** @param {string} scope */
    openNode(q) {
      const Z = o({ scope: q });
      this.add(Z), this.stack.push(Z);
    }
    closeNode() {
      if (this.stack.length > 1)
        return this.stack.pop();
    }
    closeAllNodes() {
      for (; this.closeNode(); ) ;
    }
    toJSON() {
      return JSON.stringify(this.rootNode, null, 4);
    }
    /**
     * @typedef { import("./html_renderer").Renderer } Renderer
     * @param {Renderer} builder
     */
    walk(q) {
      return this.constructor._walk(q, this.rootNode);
    }
    /**
     * @param {Renderer} builder
     * @param {Node} node
     */
    static _walk(q, Z) {
      return typeof Z == "string" ? q.addText(Z) : Z.children && (q.openNode(Z), Z.children.forEach((we) => this._walk(q, we)), q.closeNode(Z)), q;
    }
    /**
     * @param {Node} node
     */
    static _collapse(q) {
      typeof q != "string" && q.children && (q.children.every((Z) => typeof Z == "string") ? q.children = [q.children.join("")] : q.children.forEach((Z) => {
        u._collapse(Z);
      }));
    }
  }
  class m extends u {
    /**
     * @param {*} options
     */
    constructor(q) {
      super(), this.options = q;
    }
    /**
     * @param {string} text
     */
    addText(q) {
      q !== "" && this.add(q);
    }
    /** @param {string} scope */
    startScope(q) {
      this.openNode(q);
    }
    endScope() {
      this.closeNode();
    }
    /**
     * @param {Emitter & {root: DataNode}} emitter
     * @param {string} name
     */
    __addSublanguage(q, Z) {
      const we = q.root;
      Z && (we.scope = `language:${Z}`), this.add(we);
    }
    toHTML() {
      return new h(this, this.options).value();
    }
    finalize() {
      return this.closeAllNodes(), !0;
    }
  }
  function x(N) {
    return N ? typeof N == "string" ? N : N.source : null;
  }
  function f(N) {
    return D("(?=", N, ")");
  }
  function S(N) {
    return D("(?:", N, ")*");
  }
  function T(N) {
    return D("(?:", N, ")?");
  }
  function D(...N) {
    return N.map((Z) => x(Z)).join("");
  }
  function k(N) {
    const q = N[N.length - 1];
    return typeof q == "object" && q.constructor === Object ? (N.splice(N.length - 1, 1), q) : {};
  }
  function A(...N) {
    return "(" + (k(N).capture ? "" : "?:") + N.map((we) => x(we)).join("|") + ")";
  }
  function _(N) {
    return new RegExp(N.toString() + "|").exec("").length - 1;
  }
  function O(N, q) {
    const Z = N && N.exec(q);
    return Z && Z.index === 0;
  }
  const R = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
  function y(N, { joinWith: q }) {
    let Z = 0;
    return N.map((we) => {
      Z += 1;
      const Ve = Z;
      let Qe = x(we), oe = "";
      for (; Qe.length > 0; ) {
        const le = R.exec(Qe);
        if (!le) {
          oe += Qe;
          break;
        }
        oe += Qe.substring(0, le.index), Qe = Qe.substring(le.index + le[0].length), le[0][0] === "\\" && le[1] ? oe += "\\" + String(Number(le[1]) + Ve) : (oe += le[0], le[0] === "(" && Z++);
      }
      return oe;
    }).map((we) => `(${we})`).join(q);
  }
  const i = /\b\B/, g = "[a-zA-Z]\\w*", p = "[a-zA-Z_]\\w*", b = "\\b\\d+(\\.\\d+)?", w = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)", v = "\\b(0b[01]+)", M = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", $ = (N = {}) => {
    const q = /^#![ ]*\//;
    return N.binary && (N.begin = D(
      q,
      /.*\b/,
      N.binary,
      /\b.*/
    )), a({
      scope: "meta",
      begin: q,
      end: /$/,
      relevance: 0,
      /** @type {ModeCallback} */
      "on:begin": (Z, we) => {
        Z.index !== 0 && we.ignoreMatch();
      }
    }, N);
  }, C = {
    begin: "\\\\[\\s\\S]",
    relevance: 0
  }, L = {
    scope: "string",
    begin: "'",
    end: "'",
    illegal: "\\n",
    contains: [C]
  }, I = {
    scope: "string",
    begin: '"',
    end: '"',
    illegal: "\\n",
    contains: [C]
  }, E = {
    begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
  }, K = function(N, q, Z = {}) {
    const we = a(
      {
        scope: "comment",
        begin: N,
        end: q,
        contains: []
      },
      Z
    );
    we.contains.push({
      scope: "doctag",
      // hack to avoid the space from being included. the space is necessary to
      // match here to prevent the plain text rule below from gobbling up doctags
      begin: "[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",
      end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
      excludeBegin: !0,
      relevance: 0
    });
    const Ve = A(
      // list of common 1 and 2 letter words in English
      "I",
      "a",
      "is",
      "so",
      "us",
      "to",
      "at",
      "if",
      "in",
      "it",
      "on",
      // note: this is not an exhaustive list of contractions, just popular ones
      /[A-Za-z]+['](d|ve|re|ll|t|s|n)/,
      // contractions - can't we'd they're let's, etc
      /[A-Za-z]+[-][a-z]+/,
      // `no-way`, etc.
      /[A-Za-z][a-z]{2,}/
      // allow capitalized words at beginning of sentences
    );
    return we.contains.push(
      {
        // TODO: how to include ", (, ) without breaking grammars that use these for
        // comment delimiters?
        // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
        // ---
        // this tries to find sequences of 3 english words in a row (without any
        // "programming" type syntax) this gives us a strong signal that we've
        // TRULY found a comment - vs perhaps scanning with the wrong language.
        // It's possible to find something that LOOKS like the start of the
        // comment - but then if there is no readable text - good chance it is a
        // false match and not a comment.
        //
        // for a visual example please see:
        // https://github.com/highlightjs/highlight.js/issues/2827
        begin: D(
          /[ ]+/,
          // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
          "(",
          Ve,
          /[.]?[:]?([.][ ]|[ ])/,
          "){3}"
        )
        // look for 3 words in a row
      }
    ), we;
  }, P = K("//", "$"), Ne = K("/\\*", "\\*/"), ye = K("#", "$"), Ue = {
    scope: "number",
    begin: b,
    relevance: 0
  }, Q = {
    scope: "number",
    begin: w,
    relevance: 0
  }, ue = {
    scope: "number",
    begin: v,
    relevance: 0
  }, me = {
    scope: "regexp",
    begin: /\/(?=[^/\n]*\/)/,
    end: /\/[gimuy]*/,
    contains: [
      C,
      {
        begin: /\[/,
        end: /\]/,
        relevance: 0,
        contains: [C]
      }
    ]
  }, J = {
    scope: "title",
    begin: g,
    relevance: 0
  }, Y = {
    scope: "title",
    begin: p,
    relevance: 0
  }, ge = {
    // excludes method names from keyword processing
    begin: "\\.\\s*" + p,
    relevance: 0
  };
  var j = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    APOS_STRING_MODE: L,
    BACKSLASH_ESCAPE: C,
    BINARY_NUMBER_MODE: ue,
    BINARY_NUMBER_RE: v,
    COMMENT: K,
    C_BLOCK_COMMENT_MODE: Ne,
    C_LINE_COMMENT_MODE: P,
    C_NUMBER_MODE: Q,
    C_NUMBER_RE: w,
    END_SAME_AS_BEGIN: function(N) {
      return Object.assign(
        N,
        {
          /** @type {ModeCallback} */
          "on:begin": (q, Z) => {
            Z.data._beginMatch = q[1];
          },
          /** @type {ModeCallback} */
          "on:end": (q, Z) => {
            Z.data._beginMatch !== q[1] && Z.ignoreMatch();
          }
        }
      );
    },
    HASH_COMMENT_MODE: ye,
    IDENT_RE: g,
    MATCH_NOTHING_RE: i,
    METHOD_GUARD: ge,
    NUMBER_MODE: Ue,
    NUMBER_RE: b,
    PHRASAL_WORDS_MODE: E,
    QUOTE_STRING_MODE: I,
    REGEXP_MODE: me,
    RE_STARTERS_RE: M,
    SHEBANG: $,
    TITLE_MODE: J,
    UNDERSCORE_IDENT_RE: p,
    UNDERSCORE_TITLE_MODE: Y
  });
  function re(N, q) {
    N.input[N.index - 1] === "." && q.ignoreMatch();
  }
  function xe(N, q) {
    N.className !== void 0 && (N.scope = N.className, delete N.className);
  }
  function $e(N, q) {
    q && N.beginKeywords && (N.begin = "\\b(" + N.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)", N.__beforeBegin = re, N.keywords = N.keywords || N.beginKeywords, delete N.beginKeywords, N.relevance === void 0 && (N.relevance = 0));
  }
  function Me(N, q) {
    Array.isArray(N.illegal) && (N.illegal = A(...N.illegal));
  }
  function ze(N, q) {
    if (N.match) {
      if (N.begin || N.end) throw new Error("begin & end are not supported with match");
      N.begin = N.match, delete N.match;
    }
  }
  function ve(N, q) {
    N.relevance === void 0 && (N.relevance = 1);
  }
  const Be = (N, q) => {
    if (!N.beforeMatch) return;
    if (N.starts) throw new Error("beforeMatch cannot be used with starts");
    const Z = Object.assign({}, N);
    Object.keys(N).forEach((we) => {
      delete N[we];
    }), N.keywords = Z.keywords, N.begin = D(Z.beforeMatch, f(Z.begin)), N.starts = {
      relevance: 0,
      contains: [
        Object.assign(Z, { endsParent: !0 })
      ]
    }, N.relevance = 0, delete Z.beforeMatch;
  }, U = [
    "of",
    "and",
    "for",
    "in",
    "not",
    "or",
    "if",
    "then",
    "parent",
    // common variable name
    "list",
    // common variable name
    "value"
    // common variable name
  ], fe = "keyword";
  function ae(N, q, Z = fe) {
    const we = /* @__PURE__ */ Object.create(null);
    return typeof N == "string" ? Ve(Z, N.split(" ")) : Array.isArray(N) ? Ve(Z, N) : Object.keys(N).forEach(function(Qe) {
      Object.assign(
        we,
        ae(N[Qe], q, Qe)
      );
    }), we;
    function Ve(Qe, oe) {
      q && (oe = oe.map((le) => le.toLowerCase())), oe.forEach(function(le) {
        const B = le.split("|");
        we[B[0]] = [Qe, Ae(B[0], B[1])];
      });
    }
  }
  function Ae(N, q) {
    return q ? Number(q) : ke(N) ? 0 : 1;
  }
  function ke(N) {
    return U.includes(N.toLowerCase());
  }
  const Fe = {}, Ke = (N) => {
    console.error(N);
  }, yt = (N, ...q) => {
    console.log(`WARN: ${N}`, ...q);
  }, it = (N, q) => {
    Fe[`${N}/${q}`] || (console.log(`Deprecated as of ${N}. ${q}`), Fe[`${N}/${q}`] = !0);
  }, pt = new Error();
  function Dt(N, q, { key: Z }) {
    let we = 0;
    const Ve = N[Z], Qe = {}, oe = {};
    for (let le = 1; le <= q.length; le++)
      oe[le + we] = Ve[le], Qe[le + we] = !0, we += _(q[le - 1]);
    N[Z] = oe, N[Z]._emit = Qe, N[Z]._multi = !0;
  }
  function Mt(N) {
    if (Array.isArray(N.begin)) {
      if (N.skip || N.excludeBegin || N.returnBegin)
        throw Ke("skip, excludeBegin, returnBegin not compatible with beginScope: {}"), pt;
      if (typeof N.beginScope != "object" || N.beginScope === null)
        throw Ke("beginScope must be object"), pt;
      Dt(N, N.begin, { key: "beginScope" }), N.begin = y(N.begin, { joinWith: "" });
    }
  }
  function Vt(N) {
    if (Array.isArray(N.end)) {
      if (N.skip || N.excludeEnd || N.returnEnd)
        throw Ke("skip, excludeEnd, returnEnd not compatible with endScope: {}"), pt;
      if (typeof N.endScope != "object" || N.endScope === null)
        throw Ke("endScope must be object"), pt;
      Dt(N, N.end, { key: "endScope" }), N.end = y(N.end, { joinWith: "" });
    }
  }
  function Ht(N) {
    N.scope && typeof N.scope == "object" && N.scope !== null && (N.beginScope = N.scope, delete N.scope);
  }
  function zt(N) {
    Ht(N), typeof N.beginScope == "string" && (N.beginScope = { _wrap: N.beginScope }), typeof N.endScope == "string" && (N.endScope = { _wrap: N.endScope }), Mt(N), Vt(N);
  }
  function Qt(N) {
    function q(oe, le) {
      return new RegExp(
        x(oe),
        "m" + (N.case_insensitive ? "i" : "") + (N.unicodeRegex ? "u" : "") + (le ? "g" : "")
      );
    }
    class Z {
      constructor() {
        this.matchIndexes = {}, this.regexes = [], this.matchAt = 1, this.position = 0;
      }
      // @ts-ignore
      addRule(le, B) {
        B.position = this.position++, this.matchIndexes[this.matchAt] = B, this.regexes.push([B, le]), this.matchAt += _(le) + 1;
      }
      compile() {
        this.regexes.length === 0 && (this.exec = () => null);
        const le = this.regexes.map((B) => B[1]);
        this.matcherRe = q(y(le, { joinWith: "|" }), !0), this.lastIndex = 0;
      }
      /** @param {string} s */
      exec(le) {
        this.matcherRe.lastIndex = this.lastIndex;
        const B = this.matcherRe.exec(le);
        if (!B)
          return null;
        const te = B.findIndex((ie, Le) => Le > 0 && ie !== void 0), W = this.matchIndexes[te];
        return B.splice(0, te), Object.assign(B, W);
      }
    }
    class we {
      constructor() {
        this.rules = [], this.multiRegexes = [], this.count = 0, this.lastIndex = 0, this.regexIndex = 0;
      }
      // @ts-ignore
      getMatcher(le) {
        if (this.multiRegexes[le]) return this.multiRegexes[le];
        const B = new Z();
        return this.rules.slice(le).forEach(([te, W]) => B.addRule(te, W)), B.compile(), this.multiRegexes[le] = B, B;
      }
      resumingScanAtSamePosition() {
        return this.regexIndex !== 0;
      }
      considerAll() {
        this.regexIndex = 0;
      }
      // @ts-ignore
      addRule(le, B) {
        this.rules.push([le, B]), B.type === "begin" && this.count++;
      }
      /** @param {string} s */
      exec(le) {
        const B = this.getMatcher(this.regexIndex);
        B.lastIndex = this.lastIndex;
        let te = B.exec(le);
        if (this.resumingScanAtSamePosition() && !(te && te.index === this.lastIndex)) {
          const W = this.getMatcher(0);
          W.lastIndex = this.lastIndex + 1, te = W.exec(le);
        }
        return te && (this.regexIndex += te.position + 1, this.regexIndex === this.count && this.considerAll()), te;
      }
    }
    function Ve(oe) {
      const le = new we();
      return oe.contains.forEach((B) => le.addRule(B.begin, { rule: B, type: "begin" })), oe.terminatorEnd && le.addRule(oe.terminatorEnd, { type: "end" }), oe.illegal && le.addRule(oe.illegal, { type: "illegal" }), le;
    }
    function Qe(oe, le) {
      const B = (
        /** @type CompiledMode */
        oe
      );
      if (oe.isCompiled) return B;
      [
        xe,
        // do this early so compiler extensions generally don't have to worry about
        // the distinction between match/begin
        ze,
        zt,
        Be
      ].forEach((W) => W(oe, le)), N.compilerExtensions.forEach((W) => W(oe, le)), oe.__beforeBegin = null, [
        $e,
        // do this later so compiler extensions that come earlier have access to the
        // raw array if they wanted to perhaps manipulate it, etc.
        Me,
        // default to 1 relevance if not specified
        ve
      ].forEach((W) => W(oe, le)), oe.isCompiled = !0;
      let te = null;
      return typeof oe.keywords == "object" && oe.keywords.$pattern && (oe.keywords = Object.assign({}, oe.keywords), te = oe.keywords.$pattern, delete oe.keywords.$pattern), te = te || /\w+/, oe.keywords && (oe.keywords = ae(oe.keywords, N.case_insensitive)), B.keywordPatternRe = q(te, !0), le && (oe.begin || (oe.begin = /\B|\b/), B.beginRe = q(B.begin), !oe.end && !oe.endsWithParent && (oe.end = /\B|\b/), oe.end && (B.endRe = q(B.end)), B.terminatorEnd = x(B.end) || "", oe.endsWithParent && le.terminatorEnd && (B.terminatorEnd += (oe.end ? "|" : "") + le.terminatorEnd)), oe.illegal && (B.illegalRe = q(
        /** @type {RegExp | string} */
        oe.illegal
      )), oe.contains || (oe.contains = []), oe.contains = [].concat(...oe.contains.map(function(W) {
        return Tt(W === "self" ? oe : W);
      })), oe.contains.forEach(function(W) {
        Qe(
          /** @type Mode */
          W,
          B
        );
      }), oe.starts && Qe(oe.starts, le), B.matcher = Ve(B), B;
    }
    if (N.compilerExtensions || (N.compilerExtensions = []), N.contains && N.contains.includes("self"))
      throw new Error("ERR: contains `self` is not supported at the top-level of a language.  See documentation.");
    return N.classNameAliases = a(N.classNameAliases || {}), Qe(
      /** @type Mode */
      N
    );
  }
  function It(N) {
    return N ? N.endsWithParent || It(N.starts) : !1;
  }
  function Tt(N) {
    return N.variants && !N.cachedVariants && (N.cachedVariants = N.variants.map(function(q) {
      return a(N, { variants: null }, q);
    })), N.cachedVariants ? N.cachedVariants : It(N) ? a(N, { starts: N.starts ? a(N.starts) : null }) : Object.isFrozen(N) ? a(N) : N;
  }
  var $t = "11.11.1";
  class Ft extends Error {
    constructor(q, Z) {
      super(q), this.name = "HTMLInjectionError", this.html = Z;
    }
  }
  const ot = n, St = a, At = /* @__PURE__ */ Symbol("nomatch"), _t = 7, Et = function(N) {
    const q = /* @__PURE__ */ Object.create(null), Z = /* @__PURE__ */ Object.create(null), we = [];
    let Ve = !0;
    const Qe = "Could not find the language '{}', did you forget to load/include a language module?", oe = { disableAutodetect: !0, name: "Plain text", contains: [] };
    let le = {
      ignoreUnescapedHTML: !1,
      throwUnescapedHTML: !1,
      noHighlightRe: /^(no-?highlight)$/i,
      languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
      classPrefix: "hljs-",
      cssSelector: "pre code",
      languages: null,
      // beta configuration options, subject to change, welcome to discuss
      // https://github.com/highlightjs/highlight.js/issues/1086
      __emitter: m
    };
    function B(X) {
      return le.noHighlightRe.test(X);
    }
    function te(X) {
      let pe = X.className + " ";
      pe += X.parentNode ? X.parentNode.className : "";
      const Re = le.languageDetectRe.exec(pe);
      if (Re) {
        const qe = je(Re[1]);
        return qe || (yt(Qe.replace("{}", Re[1])), yt("Falling back to no-highlight mode for this block.", X)), qe ? Re[1] : "no-highlight";
      }
      return pe.split(/\s+/).find((qe) => B(qe) || je(qe));
    }
    function W(X, pe, Re) {
      let qe = "", We = "";
      typeof pe == "object" ? (qe = X, Re = pe.ignoreIllegals, We = pe.language) : (it("10.7.0", "highlight(lang, code, ...args) has been deprecated."), it("10.7.0", `Please use highlight(code, options) instead.
https://github.com/highlightjs/highlight.js/issues/2277`), We = X, qe = pe), Re === void 0 && (Re = !0);
      const et = {
        code: qe,
        language: We
      };
      st("before:highlight", et);
      const Nt = et.result ? et.result : ie(et.language, et.code, Re);
      return Nt.code = et.code, st("after:highlight", Nt), Nt;
    }
    function ie(X, pe, Re, qe) {
      const We = /* @__PURE__ */ Object.create(null);
      function et(ce, be) {
        return ce.keywords[be];
      }
      function Nt() {
        if (!Se.keywords) {
          Xe.addText(He);
          return;
        }
        let ce = 0;
        Se.keywordPatternRe.lastIndex = 0;
        let be = Se.keywordPatternRe.exec(He), Ee = "";
        for (; be; ) {
          Ee += He.substring(ce, be.index);
          const Pe = ft.case_insensitive ? be[0].toLowerCase() : be[0], Ze = et(Se, Pe);
          if (Ze) {
            const [xt, ps] = Ze;
            if (Xe.addText(Ee), Ee = "", We[Pe] = (We[Pe] || 0) + 1, We[Pe] <= _t && (nr += ps), xt.startsWith("_"))
              Ee += be[0];
            else {
              const xs = ft.classNameAliases[xt] || xt;
              mt(be[0], xs);
            }
          } else
            Ee += be[0];
          ce = Se.keywordPatternRe.lastIndex, be = Se.keywordPatternRe.exec(He);
        }
        Ee += He.substring(ce), Xe.addText(Ee);
      }
      function tr() {
        if (He === "") return;
        let ce = null;
        if (typeof Se.subLanguage == "string") {
          if (!q[Se.subLanguage]) {
            Xe.addText(He);
            return;
          }
          ce = ie(Se.subLanguage, He, !0, Xr[Se.subLanguage]), Xr[Se.subLanguage] = /** @type {CompiledMode} */
          ce._top;
        } else
          ce = Ge(He, Se.subLanguage.length ? Se.subLanguage : null);
        Se.relevance > 0 && (nr += ce.relevance), Xe.__addSublanguage(ce._emitter, ce.language);
      }
      function tt() {
        Se.subLanguage != null ? tr() : Nt(), He = "";
      }
      function mt(ce, be) {
        ce !== "" && (Xe.startScope(be), Xe.addText(ce), Xe.endScope());
      }
      function Wr(ce, be) {
        let Ee = 1;
        const Pe = be.length - 1;
        for (; Ee <= Pe; ) {
          if (!ce._emit[Ee]) {
            Ee++;
            continue;
          }
          const Ze = ft.classNameAliases[ce[Ee]] || ce[Ee], xt = be[Ee];
          Ze ? mt(xt, Ze) : (He = xt, Nt(), He = ""), Ee++;
        }
      }
      function Jr(ce, be) {
        return ce.scope && typeof ce.scope == "string" && Xe.openNode(ft.classNameAliases[ce.scope] || ce.scope), ce.beginScope && (ce.beginScope._wrap ? (mt(He, ft.classNameAliases[ce.beginScope._wrap] || ce.beginScope._wrap), He = "") : ce.beginScope._multi && (Wr(ce.beginScope, be), He = "")), Se = Object.create(ce, { parent: { value: Se } }), Se;
      }
      function Yr(ce, be, Ee) {
        let Pe = O(ce.endRe, Ee);
        if (Pe) {
          if (ce["on:end"]) {
            const Ze = new r(ce);
            ce["on:end"](be, Ze), Ze.isMatchIgnored && (Pe = !1);
          }
          if (Pe) {
            for (; ce.endsParent && ce.parent; )
              ce = ce.parent;
            return ce;
          }
        }
        if (ce.endsWithParent)
          return Yr(ce.parent, be, Ee);
      }
      function ds(ce) {
        return Se.matcher.regexIndex === 0 ? (He += ce[0], 1) : (wr = !0, 0);
      }
      function us(ce) {
        const be = ce[0], Ee = ce.rule, Pe = new r(Ee), Ze = [Ee.__beforeBegin, Ee["on:begin"]];
        for (const xt of Ze)
          if (xt && (xt(ce, Pe), Pe.isMatchIgnored))
            return ds(be);
        return Ee.skip ? He += be : (Ee.excludeBegin && (He += be), tt(), !Ee.returnBegin && !Ee.excludeBegin && (He = be)), Jr(Ee, ce), Ee.returnBegin ? 0 : be.length;
      }
      function ms(ce) {
        const be = ce[0], Ee = pe.substring(ce.index), Pe = Yr(Se, ce, Ee);
        if (!Pe)
          return At;
        const Ze = Se;
        Se.endScope && Se.endScope._wrap ? (tt(), mt(be, Se.endScope._wrap)) : Se.endScope && Se.endScope._multi ? (tt(), Wr(Se.endScope, ce)) : Ze.skip ? He += be : (Ze.returnEnd || Ze.excludeEnd || (He += be), tt(), Ze.excludeEnd && (He = be));
        do
          Se.scope && Xe.closeNode(), !Se.skip && !Se.subLanguage && (nr += Se.relevance), Se = Se.parent;
        while (Se !== Pe.parent);
        return Pe.starts && Jr(Pe.starts, ce), Ze.returnEnd ? 0 : be.length;
      }
      function fs() {
        const ce = [];
        for (let be = Se; be !== ft; be = be.parent)
          be.scope && ce.unshift(be.scope);
        ce.forEach((be) => Xe.openNode(be));
      }
      let rr = {};
      function Kr(ce, be) {
        const Ee = be && be[0];
        if (He += ce, Ee == null)
          return tt(), 0;
        if (rr.type === "begin" && be.type === "end" && rr.index === be.index && Ee === "") {
          if (He += pe.slice(be.index, be.index + 1), !Ve) {
            const Pe = new Error(`0 width match regex (${X})`);
            throw Pe.languageName = X, Pe.badRule = rr.rule, Pe;
          }
          return 1;
        }
        if (rr = be, be.type === "begin")
          return us(be);
        if (be.type === "illegal" && !Re) {
          const Pe = new Error('Illegal lexeme "' + Ee + '" for mode "' + (Se.scope || "<unnamed>") + '"');
          throw Pe.mode = Se, Pe;
        } else if (be.type === "end") {
          const Pe = ms(be);
          if (Pe !== At)
            return Pe;
        }
        if (be.type === "illegal" && Ee === "")
          return He += `
`, 1;
        if (Nr > 1e5 && Nr > be.index * 3)
          throw new Error("potential infinite loop, way more iterations than matches");
        return He += Ee, Ee.length;
      }
      const ft = je(X);
      if (!ft)
        throw Ke(Qe.replace("{}", X)), new Error('Unknown language: "' + X + '"');
      const hs = Qt(ft);
      let vr = "", Se = qe || hs;
      const Xr = {}, Xe = new le.__emitter(le);
      fs();
      let He = "", nr = 0, Rt = 0, Nr = 0, wr = !1;
      try {
        if (ft.__emitTokens)
          ft.__emitTokens(pe, Xe);
        else {
          for (Se.matcher.considerAll(); ; ) {
            Nr++, wr ? wr = !1 : Se.matcher.considerAll(), Se.matcher.lastIndex = Rt;
            const ce = Se.matcher.exec(pe);
            if (!ce) break;
            const be = pe.substring(Rt, ce.index), Ee = Kr(be, ce);
            Rt = ce.index + Ee;
          }
          Kr(pe.substring(Rt));
        }
        return Xe.finalize(), vr = Xe.toHTML(), {
          language: X,
          value: vr,
          relevance: nr,
          illegal: !1,
          _emitter: Xe,
          _top: Se
        };
      } catch (ce) {
        if (ce.message && ce.message.includes("Illegal"))
          return {
            language: X,
            value: ot(pe),
            illegal: !0,
            relevance: 0,
            _illegalBy: {
              message: ce.message,
              index: Rt,
              context: pe.slice(Rt - 100, Rt + 100),
              mode: ce.mode,
              resultSoFar: vr
            },
            _emitter: Xe
          };
        if (Ve)
          return {
            language: X,
            value: ot(pe),
            illegal: !1,
            relevance: 0,
            errorRaised: ce,
            _emitter: Xe,
            _top: Se
          };
        throw ce;
      }
    }
    function Le(X) {
      const pe = {
        value: ot(X),
        illegal: !1,
        relevance: 0,
        _top: oe,
        _emitter: new le.__emitter(le)
      };
      return pe._emitter.addText(X), pe;
    }
    function Ge(X, pe) {
      pe = pe || le.languages || Object.keys(q);
      const Re = Le(X), qe = pe.filter(je).filter(nt).map(
        (tt) => ie(tt, X, !1)
      );
      qe.unshift(Re);
      const We = qe.sort((tt, mt) => {
        if (tt.relevance !== mt.relevance) return mt.relevance - tt.relevance;
        if (tt.language && mt.language) {
          if (je(tt.language).supersetOf === mt.language)
            return 1;
          if (je(mt.language).supersetOf === tt.language)
            return -1;
        }
        return 0;
      }), [et, Nt] = We, tr = et;
      return tr.secondBest = Nt, tr;
    }
    function V(X, pe, Re) {
      const qe = pe && Z[pe] || Re;
      X.classList.add("hljs"), X.classList.add(`language-${qe}`);
    }
    function G(X) {
      let pe = null;
      const Re = te(X);
      if (B(Re)) return;
      if (st(
        "before:highlightElement",
        { el: X, language: Re }
      ), X.dataset.highlighted) {
        console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", X);
        return;
      }
      if (X.children.length > 0 && (le.ignoreUnescapedHTML || (console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."), console.warn("https://github.com/highlightjs/highlight.js/wiki/security"), console.warn("The element with unescaped HTML:"), console.warn(X)), le.throwUnescapedHTML))
        throw new Ft(
          "One of your code blocks includes unescaped HTML.",
          X.innerHTML
        );
      pe = X;
      const qe = pe.textContent, We = Re ? W(qe, { language: Re, ignoreIllegals: !0 }) : Ge(qe);
      X.innerHTML = We.value, X.dataset.highlighted = "yes", V(X, Re, We.language), X.result = {
        language: We.language,
        // TODO: remove with version 11.0
        re: We.relevance,
        relevance: We.relevance
      }, We.secondBest && (X.secondBest = {
        language: We.secondBest.language,
        relevance: We.secondBest.relevance
      }), st("after:highlightElement", { el: X, result: We, text: qe });
    }
    function ne(X) {
      le = St(le, X);
    }
    const se = () => {
      de(), it("10.6.0", "initHighlighting() deprecated.  Use highlightAll() now.");
    };
    function he() {
      de(), it("10.6.0", "initHighlightingOnLoad() deprecated.  Use highlightAll() now.");
    }
    let _e = !1;
    function de() {
      function X() {
        de();
      }
      if (document.readyState === "loading") {
        _e || window.addEventListener("DOMContentLoaded", X, !1), _e = !0;
        return;
      }
      document.querySelectorAll(le.cssSelector).forEach(G);
    }
    function De(X, pe) {
      let Re = null;
      try {
        Re = pe(N);
      } catch (qe) {
        if (Ke("Language definition for '{}' could not be registered.".replace("{}", X)), Ve)
          Ke(qe);
        else
          throw qe;
        Re = oe;
      }
      Re.name || (Re.name = X), q[X] = Re, Re.rawDefinition = pe.bind(null, N), Re.aliases && rt(Re.aliases, { languageName: X });
    }
    function Ye(X) {
      delete q[X];
      for (const pe of Object.keys(Z))
        Z[pe] === X && delete Z[pe];
    }
    function Je() {
      return Object.keys(q);
    }
    function je(X) {
      return X = (X || "").toLowerCase(), q[X] || q[Z[X]];
    }
    function rt(X, { languageName: pe }) {
      typeof X == "string" && (X = [X]), X.forEach((Re) => {
        Z[Re.toLowerCase()] = pe;
      });
    }
    function nt(X) {
      const pe = je(X);
      return pe && !pe.disableAutodetect;
    }
    function ut(X) {
      X["before:highlightBlock"] && !X["before:highlightElement"] && (X["before:highlightElement"] = (pe) => {
        X["before:highlightBlock"](
          Object.assign({ block: pe.el }, pe)
        );
      }), X["after:highlightBlock"] && !X["after:highlightElement"] && (X["after:highlightElement"] = (pe) => {
        X["after:highlightBlock"](
          Object.assign({ block: pe.el }, pe)
        );
      });
    }
    function Ut(X) {
      ut(X), we.push(X);
    }
    function Gt(X) {
      const pe = we.indexOf(X);
      pe !== -1 && we.splice(pe, 1);
    }
    function st(X, pe) {
      const Re = X;
      we.forEach(function(qe) {
        qe[Re] && qe[Re](pe);
      });
    }
    function vt(X) {
      return it("10.7.0", "highlightBlock will be removed entirely in v12.0"), it("10.7.0", "Please use highlightElement now."), G(X);
    }
    Object.assign(N, {
      highlight: W,
      highlightAuto: Ge,
      highlightAll: de,
      highlightElement: G,
      // TODO: Remove with v12 API
      highlightBlock: vt,
      configure: ne,
      initHighlighting: se,
      initHighlightingOnLoad: he,
      registerLanguage: De,
      unregisterLanguage: Ye,
      listLanguages: Je,
      getLanguage: je,
      registerAliases: rt,
      autoDetection: nt,
      inherit: St,
      addPlugin: Ut,
      removePlugin: Gt
    }), N.debugMode = function() {
      Ve = !1;
    }, N.safeMode = function() {
      Ve = !0;
    }, N.versionString = $t, N.regex = {
      concat: D,
      lookahead: f,
      either: A,
      optional: T,
      anyNumberOfTimes: S
    };
    for (const X in j)
      typeof j[X] == "object" && t(j[X]);
    return Object.assign(N, j), N;
  }, dt = Et({});
  return dt.newInstance = () => Et({}), kr = dt, dt.HighlightJS = dt, dt.default = dt, kr;
}
var Aa = /* @__PURE__ */ Sa();
const qr = /* @__PURE__ */ Ta(Aa);
function Qn(t) {
  const r = {
    className: "attr",
    begin: /"(\\.|[^\\"\r\n])*"(?=\s*:)/,
    relevance: 1.01
  }, n = {
    match: /[{}[\],:]/,
    className: "punctuation",
    relevance: 0
  }, a = [
    "true",
    "false",
    "null"
  ], c = {
    scope: "literal",
    beginKeywords: a.join(" ")
  };
  return {
    name: "JSON",
    aliases: ["jsonc"],
    keywords: {
      literal: a
    },
    contains: [
      r,
      n,
      t.QUOTE_STRING_MODE,
      c,
      t.C_NUMBER_MODE,
      t.C_LINE_COMMENT_MODE,
      t.C_BLOCK_COMMENT_MODE
    ],
    illegal: "\\S"
  };
}
const _a = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Qn
}, Symbol.toStringTag, { value: "Module" }));
function Un(t) {
  const r = t.regex, n = t.COMMENT("--", "$"), a = {
    scope: "string",
    variants: [
      {
        begin: /'/,
        end: /'/,
        contains: [{ match: /''/ }]
      }
    ]
  }, c = {
    begin: /"/,
    end: /"/,
    contains: [{ match: /""/ }]
  }, l = [
    "true",
    "false",
    // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way.
    // "null",
    "unknown"
  ], d = [
    "double precision",
    "large object",
    "with timezone",
    "without timezone"
  ], h = [
    "bigint",
    "binary",
    "blob",
    "boolean",
    "char",
    "character",
    "clob",
    "date",
    "dec",
    "decfloat",
    "decimal",
    "float",
    "int",
    "integer",
    "interval",
    "nchar",
    "nclob",
    "national",
    "numeric",
    "real",
    "row",
    "smallint",
    "time",
    "timestamp",
    "varchar",
    "varying",
    // modifier (character varying)
    "varbinary"
  ], o = [
    "add",
    "asc",
    "collation",
    "desc",
    "final",
    "first",
    "last",
    "view"
  ], u = [
    "abs",
    "acos",
    "all",
    "allocate",
    "alter",
    "and",
    "any",
    "are",
    "array",
    "array_agg",
    "array_max_cardinality",
    "as",
    "asensitive",
    "asin",
    "asymmetric",
    "at",
    "atan",
    "atomic",
    "authorization",
    "avg",
    "begin",
    "begin_frame",
    "begin_partition",
    "between",
    "bigint",
    "binary",
    "blob",
    "boolean",
    "both",
    "by",
    "call",
    "called",
    "cardinality",
    "cascaded",
    "case",
    "cast",
    "ceil",
    "ceiling",
    "char",
    "char_length",
    "character",
    "character_length",
    "check",
    "classifier",
    "clob",
    "close",
    "coalesce",
    "collate",
    "collect",
    "column",
    "commit",
    "condition",
    "connect",
    "constraint",
    "contains",
    "convert",
    "copy",
    "corr",
    "corresponding",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "create",
    "cross",
    "cube",
    "cume_dist",
    "current",
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_row",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_path",
    "current_role",
    "current_transform_group_for_type",
    "current_user",
    "cursor",
    "cycle",
    "date",
    "day",
    "deallocate",
    "dec",
    "decimal",
    "decfloat",
    "declare",
    "default",
    "define",
    "delete",
    "dense_rank",
    "deref",
    "describe",
    "deterministic",
    "disconnect",
    "distinct",
    "double",
    "drop",
    "dynamic",
    "each",
    "element",
    "else",
    "empty",
    "end",
    "end_frame",
    "end_partition",
    "end-exec",
    "equals",
    "escape",
    "every",
    "except",
    "exec",
    "execute",
    "exists",
    "exp",
    "external",
    "extract",
    "false",
    "fetch",
    "filter",
    "first_value",
    "float",
    "floor",
    "for",
    "foreign",
    "frame_row",
    "free",
    "from",
    "full",
    "function",
    "fusion",
    "get",
    "global",
    "grant",
    "group",
    "grouping",
    "groups",
    "having",
    "hold",
    "hour",
    "identity",
    "in",
    "indicator",
    "initial",
    "inner",
    "inout",
    "insensitive",
    "insert",
    "int",
    "integer",
    "intersect",
    "intersection",
    "interval",
    "into",
    "is",
    "join",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "language",
    "large",
    "last_value",
    "lateral",
    "lead",
    "leading",
    "left",
    "like",
    "like_regex",
    "listagg",
    "ln",
    "local",
    "localtime",
    "localtimestamp",
    "log",
    "log10",
    "lower",
    "match",
    "match_number",
    "match_recognize",
    "matches",
    "max",
    "member",
    "merge",
    "method",
    "min",
    "minute",
    "mod",
    "modifies",
    "module",
    "month",
    "multiset",
    "national",
    "natural",
    "nchar",
    "nclob",
    "new",
    "no",
    "none",
    "normalize",
    "not",
    "nth_value",
    "ntile",
    "null",
    "nullif",
    "numeric",
    "octet_length",
    "occurrences_regex",
    "of",
    "offset",
    "old",
    "omit",
    "on",
    "one",
    "only",
    "open",
    "or",
    "order",
    "out",
    "outer",
    "over",
    "overlaps",
    "overlay",
    "parameter",
    "partition",
    "pattern",
    "per",
    "percent",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "period",
    "portion",
    "position",
    "position_regex",
    "power",
    "precedes",
    "precision",
    "prepare",
    "primary",
    "procedure",
    "ptf",
    "range",
    "rank",
    "reads",
    "real",
    "recursive",
    "ref",
    "references",
    "referencing",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "release",
    "result",
    "return",
    "returns",
    "revoke",
    "right",
    "rollback",
    "rollup",
    "row",
    "row_number",
    "rows",
    "running",
    "savepoint",
    "scope",
    "scroll",
    "search",
    "second",
    "seek",
    "select",
    "sensitive",
    "session_user",
    "set",
    "show",
    "similar",
    "sin",
    "sinh",
    "skip",
    "smallint",
    "some",
    "specific",
    "specifictype",
    "sql",
    "sqlexception",
    "sqlstate",
    "sqlwarning",
    "sqrt",
    "start",
    "static",
    "stddev_pop",
    "stddev_samp",
    "submultiset",
    "subset",
    "substring",
    "substring_regex",
    "succeeds",
    "sum",
    "symmetric",
    "system",
    "system_time",
    "system_user",
    "table",
    "tablesample",
    "tan",
    "tanh",
    "then",
    "time",
    "timestamp",
    "timezone_hour",
    "timezone_minute",
    "to",
    "trailing",
    "translate",
    "translate_regex",
    "translation",
    "treat",
    "trigger",
    "trim",
    "trim_array",
    "true",
    "truncate",
    "uescape",
    "union",
    "unique",
    "unknown",
    "unnest",
    "update",
    "upper",
    "user",
    "using",
    "value",
    "values",
    "value_of",
    "var_pop",
    "var_samp",
    "varbinary",
    "varchar",
    "varying",
    "versioning",
    "when",
    "whenever",
    "where",
    "width_bucket",
    "window",
    "with",
    "within",
    "without",
    "year"
  ], m = [
    "abs",
    "acos",
    "array_agg",
    "asin",
    "atan",
    "avg",
    "cast",
    "ceil",
    "ceiling",
    "coalesce",
    "corr",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "cume_dist",
    "dense_rank",
    "deref",
    "element",
    "exp",
    "extract",
    "first_value",
    "floor",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "last_value",
    "lead",
    "listagg",
    "ln",
    "log",
    "log10",
    "lower",
    "max",
    "min",
    "mod",
    "nth_value",
    "ntile",
    "nullif",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "position",
    "position_regex",
    "power",
    "rank",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "row_number",
    "sin",
    "sinh",
    "sqrt",
    "stddev_pop",
    "stddev_samp",
    "substring",
    "substring_regex",
    "sum",
    "tan",
    "tanh",
    "translate",
    "translate_regex",
    "treat",
    "trim",
    "trim_array",
    "unnest",
    "upper",
    "value_of",
    "var_pop",
    "var_samp",
    "width_bucket"
  ], x = [
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_schema",
    "current_transform_group_for_type",
    "current_user",
    "session_user",
    "system_time",
    "system_user",
    "current_time",
    "localtime",
    "current_timestamp",
    "localtimestamp"
  ], f = [
    "create table",
    "insert into",
    "primary key",
    "foreign key",
    "not null",
    "alter table",
    "add constraint",
    "grouping sets",
    "on overflow",
    "character set",
    "respect nulls",
    "ignore nulls",
    "nulls first",
    "nulls last",
    "depth first",
    "breadth first"
  ], S = m, T = [
    ...u,
    ...o
  ].filter((y) => !m.includes(y)), D = {
    scope: "variable",
    match: /@[a-z0-9][a-z0-9_]*/
  }, k = {
    scope: "operator",
    match: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,
    relevance: 0
  }, A = {
    match: r.concat(/\b/, r.either(...S), /\s*\(/),
    relevance: 0,
    keywords: { built_in: S }
  };
  function _(y) {
    return r.concat(
      /\b/,
      r.either(...y.map((i) => i.replace(/\s+/, "\\s+"))),
      /\b/
    );
  }
  const O = {
    scope: "keyword",
    match: _(f),
    relevance: 0
  };
  function R(y, {
    exceptions: i,
    when: g
  } = {}) {
    const p = g;
    return i = i || [], y.map((b) => b.match(/\|\d+$/) || i.includes(b) ? b : p(b) ? `${b}|0` : b);
  }
  return {
    name: "SQL",
    case_insensitive: !0,
    // does not include {} or HTML tags `</`
    illegal: /[{}]|<\//,
    keywords: {
      $pattern: /\b[\w\.]+/,
      keyword: R(T, { when: (y) => y.length < 3 }),
      literal: l,
      type: h,
      built_in: x
    },
    contains: [
      {
        scope: "type",
        match: _(d)
      },
      O,
      A,
      D,
      a,
      c,
      t.C_NUMBER_MODE,
      t.C_BLOCK_COMMENT_MODE,
      n,
      k
    ]
  };
}
const Ea = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Un
}, Symbol.toStringTag, { value: "Module" }));
qr.registerLanguage("json", Qn);
qr.registerLanguage("sql", Un);
const dn = ({
  code: t,
  language: r,
  title: n,
  maxHeight: a = "16rem",
  className: c = ""
}) => {
  const [l, d] = H(!1), h = Te(null), o = z("copy"), u = z("check");
  Ce(() => {
    h.current && t && (h.current.innerHTML = qr.highlight(t, { language: r }).value);
  }, [t, r]);
  const m = async () => {
    try {
      await navigator.clipboard.writeText(t), d(!0), setTimeout(() => d(!1), 2e3);
    } catch {
      const x = document.createElement("textarea");
      x.value = t, x.style.position = "fixed", x.style.left = "-999999px", document.body.appendChild(x), x.select(), document.execCommand("copy"), document.body.removeChild(x), d(!0), setTimeout(() => d(!1), 2e3);
    }
  };
  return /* @__PURE__ */ s("div", { className: `relative ${c}`, children: [
    /* @__PURE__ */ s("div", { className: "flex items-center justify-between mb-2", children: [
      n && /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-text", children: n }),
      /* @__PURE__ */ e(
        "button",
        {
          onClick: m,
          className: "ml-auto px-2 py-1 text-xs rounded hover:bg-dc-surface-secondary border border-dc-border transition-colors flex items-center gap-1.5",
          title: l ? "Copied!" : "Copy to clipboard",
          children: l ? /* @__PURE__ */ s(Ie, { children: [
            /* @__PURE__ */ e(u, { className: "w-3.5 h-3.5 text-dc-success" }),
            /* @__PURE__ */ e("span", { className: "text-dc-success", children: "Copied" })
          ] }) : /* @__PURE__ */ s(Ie, { children: [
            /* @__PURE__ */ e(o, { className: "w-3.5 h-3.5 text-dc-text-secondary" }),
            /* @__PURE__ */ e("span", { className: "text-dc-text-secondary", children: "Copy" })
          ] })
        }
      )
    ] }),
    /* @__PURE__ */ e(
      "div",
      {
        className: "bg-dc-surface-secondary border border-dc-border rounded overflow-auto",
        style: { maxHeight: a },
        children: /* @__PURE__ */ e("pre", { className: "p-3 text-xs m-0", children: /* @__PURE__ */ e(
          "code",
          {
            ref: h,
            className: `hljs language-${r}`,
            children: t
          }
        ) })
      }
    )
  ] });
};
function Gn(t) {
  return t.isTimeDimension;
}
function Ra(t) {
  return t.find(Gn);
}
function Oa(t) {
  return t.find((r) => !r.isTimeDimension);
}
function Vr(t) {
  return t.filter((r) => !r.isTimeDimension);
}
function Wn(t) {
  return t.filter(Gn);
}
function Hr(t, r, n) {
  const a = r.length, c = Vr(n).length, l = Wn(n).length, d = n.length;
  switch (t) {
    // Always available charts
    case "table":
    case "markdown":
      return { available: !0 };
    // Measure-only charts (KPI Number, KPI Text)
    case "kpiNumber":
    case "kpiText":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : { available: !0 };
    // Bar chart - needs dimension for categories + measure for values
    case "bar":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : d < 1 ? { available: !1, reason: "Requires at least 1 breakdown for categories" } : { available: !0 };
    // KPI Delta - needs dimension for ordering + measure for values
    case "kpiDelta":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : d < 1 ? { available: !1, reason: "Requires at least 1 breakdown for ordering" } : { available: !0 };
    // Line and area charts - need dimension/time + measure
    case "line":
    case "area":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : d < 1 ? { available: !1, reason: "Requires a breakdown (dimension or time)" } : { available: !0 };
    // Pie chart - needs dimension (not time) + measure
    case "pie":
      return a < 1 ? { available: !1, reason: "Requires 1 measure" } : c < 1 ? { available: !1, reason: "Requires 1 dimension (not time dimension)" } : { available: !0 };
    // Scatter - needs measure + any breakdown
    case "scatter":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : a < 2 && d < 1 ? { available: !1, reason: "Requires 2 measures or 1 measure + 1 breakdown" } : { available: !0 };
    // Bubble - needs 2+ measures and 1+ breakdown (dimension or time dimension for series)
    case "bubble":
      return a < 2 ? { available: !1, reason: "Requires at least 2 measures" } : d < 1 ? { available: !1, reason: "Requires at least 1 breakdown for series grouping" } : { available: !0 };
    // Radar - needs dimension + measure
    case "radar":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : c < 1 ? { available: !1, reason: "Requires at least 1 dimension" } : { available: !0 };
    // Radial Bar - needs dimension + measure
    case "radialBar":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : c < 1 ? { available: !1, reason: "Requires at least 1 dimension" } : { available: !0 };
    // Treemap - needs dimension + measure
    case "treemap":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : c < 1 ? { available: !1, reason: "Requires at least 1 dimension" } : { available: !0 };
    // Activity Grid - needs time dimension + measure
    case "activityGrid":
      return a < 1 ? { available: !1, reason: "Requires at least 1 measure" } : l < 1 ? { available: !1, reason: "Requires a time dimension" } : { available: !0 };
    default:
      return { available: !0 };
  }
}
function Ma(t, r) {
  const n = [
    "activityGrid",
    "area",
    "bar",
    "bubble",
    "kpiDelta",
    "kpiNumber",
    "kpiText",
    "line",
    "markdown",
    "pie",
    "radar",
    "radialBar",
    "scatter",
    "table",
    "treemap"
  ], a = {};
  for (const c of n)
    a[c] = Hr(c, t, r);
  return a;
}
function Jn(t, r, n) {
  if (Hr(n, t, r).available || t.length === 0 && r.length === 0)
    return n;
  const c = Wn(r).length > 0, l = Vr(r).length > 0, d = t.length > 0;
  return c && d ? "line" : l && d ? "bar" : d && !l && !c ? "kpiNumber" : "table";
}
function Cr(t, r, n) {
  const a = Jn(t, r, n), c = Ia(a, t, r);
  return { chartType: a, chartConfig: c };
}
function Ia(t, r, n) {
  const a = Ra(n), c = Oa(n), l = Vr(n), d = n;
  switch (t) {
    case "line":
    case "area":
      return {
        xAxis: a ? [a.field] : c ? [c.field] : [],
        yAxis: r.map((h) => h.field),
        series: l.length > 1 ? [l[1].field] : c && a ? [c.field] : []
      };
    case "bar":
      return {
        xAxis: c ? [c.field] : a ? [a.field] : [],
        yAxis: r.map((h) => h.field),
        series: l.length > 1 ? [l[1].field] : a && c ? [a.field] : []
      };
    case "pie":
      return {
        xAxis: c ? [c.field] : [],
        yAxis: r.length > 0 ? [r[0].field] : []
      };
    case "scatter":
      return r.length >= 2 ? {
        xAxis: [r[0].field],
        yAxis: [r[1].field],
        series: c ? [c.field] : []
      } : {
        xAxis: d.length > 0 ? [d[0].field] : [],
        yAxis: r.length > 0 ? [r[0].field] : [],
        series: l.length > 1 ? [l[1].field] : []
      };
    case "bubble":
      return {
        xAxis: r.length > 0 ? [r[0].field] : [],
        yAxis: r.length > 1 ? [r[1].field] : [],
        sizeField: r.length > 2 ? r[2].field : r.length > 1 ? r[1].field : void 0,
        series: c ? [c.field] : a ? [a.field] : []
      };
    case "radar":
    case "radialBar":
    case "treemap":
      return {
        xAxis: c ? [c.field] : [],
        yAxis: r.length > 0 ? [r[0].field] : []
      };
    case "activityGrid":
      return {
        dateField: a ? [a.field] : [],
        valueField: r.length > 0 ? [r[0].field] : []
      };
    case "kpiNumber":
    case "kpiDelta":
    case "kpiText":
      return {
        yAxis: r.length > 0 ? [r[0].field] : []
      };
    case "table":
      return {
        xAxis: [
          ...n.map((h) => h.field),
          ...r.map((h) => h.field)
        ]
      };
    case "markdown":
      return {};
    default:
      return {
        xAxis: d.length > 0 ? [d[0].field] : [],
        yAxis: r.map((h) => h.field)
      };
  }
}
function $a(t, r, n, a) {
  if (a && Hr(n, t, r).available)
    return null;
  const c = Jn(t, r, n);
  return c !== n ? c : null;
}
const fr = [
  {
    name: "default",
    label: "Default",
    colors: [
      "#3b82f6",
      // blue
      "#10b981",
      // green
      "#f59e0b",
      // yellow
      "#ef4444",
      // red
      "#8b5cf6",
      // purple
      "#f97316",
      // orange
      "#06b6d4",
      // cyan
      "#84cc16"
      // lime
    ],
    gradient: [
      "#440154",
      // dark purple
      "#414487",
      // purple-blue
      "#2a788e",
      // teal
      "#22a884",
      // green-teal  
      "#7ad151",
      // green
      "#fde725"
      // yellow
    ]
  },
  {
    name: "ocean",
    label: "Ocean",
    colors: [
      "#1e3a8a",
      // deep blue
      "#1e40af",
      // blue
      "#2563eb",
      // bright blue
      "#3b82f6",
      // light blue
      "#06b6d4",
      // cyan
      "#0891b2",
      // dark cyan
      "#0e7490",
      // teal
      "#0f766e"
      // dark teal
    ],
    gradient: [
      "#0c4a6e",
      // very dark blue
      "#075985",
      // dark blue
      "#0369a1",
      // medium blue
      "#0284c7",
      // bright blue
      "#0ea5e9",
      // light blue
      "#38bdf8"
      // cyan blue
    ]
  },
  {
    name: "sunset",
    label: "Sunset",
    colors: [
      "#dc2626",
      // red
      "#ea580c",
      // orange-red
      "#f59e0b",
      // orange
      "#eab308",
      // yellow-orange
      "#d97706",
      // amber
      "#b45309",
      // dark amber
      "#92400e",
      // brown
      "#7c2d12"
      // dark brown
    ],
    gradient: [
      "#7c2d12",
      // dark brown
      "#92400e",
      // brown
      "#b45309",
      // dark amber
      "#d97706",
      // amber
      "#f59e0b",
      // orange
      "#fbbf24"
      // light orange
    ]
  },
  {
    name: "forest",
    label: "Forest",
    colors: [
      "#166534",
      // dark green
      "#15803d",
      // green
      "#16a34a",
      // bright green
      "#22c55e",
      // light green
      "#4ade80",
      // lighter green
      "#65a30d",
      // lime green
      "#84cc16",
      // lime
      "#a3e635"
      // light lime
    ],
    gradient: [
      "#14532d",
      // very dark green
      "#166534",
      // dark green
      "#15803d",
      // green
      "#16a34a",
      // bright green
      "#22c55e",
      // light green
      "#4ade80"
      // lighter green
    ]
  },
  {
    name: "purple",
    label: "Purple",
    colors: [
      "#581c87",
      // dark purple
      "#7c3aed",
      // purple
      "#8b5cf6",
      // bright purple
      "#a855f7",
      // light purple
      "#c084fc",
      // lighter purple
      "#e879f9",
      // magenta
      "#f0abfc",
      // light magenta
      "#fbbf24"
      // accent yellow
    ],
    gradient: [
      "#4c1d95",
      // very dark purple
      "#581c87",
      // dark purple
      "#6d28d9",
      // medium purple
      "#7c3aed",
      // purple
      "#8b5cf6",
      // bright purple
      "#a855f7"
      // light purple
    ]
  },
  {
    name: "monochrome",
    label: "Monochrome",
    colors: [
      "#1f2937",
      // very dark gray
      "#374151",
      // dark gray
      "#4b5563",
      // medium gray
      "#6b7280",
      // gray
      "#9ca3af",
      // light gray
      "#d1d5db",
      // lighter gray
      "#e5e7eb",
      // very light gray
      "#f3f4f6"
      // almost white
    ],
    gradient: [
      "#111827",
      // black
      "#1f2937",
      // very dark gray
      "#374151",
      // dark gray
      "#4b5563",
      // medium gray
      "#6b7280",
      // gray
      "#9ca3af"
      // light gray
    ]
  },
  {
    name: "pastel",
    label: "Pastel",
    colors: [
      "#93c5fd",
      // light blue
      "#86efac",
      // light green
      "#fde047",
      // light yellow
      "#fca5a5",
      // light red
      "#c4b5fd",
      // light purple
      "#fdba74",
      // light orange
      "#67e8f9",
      // light cyan
      "#bef264"
      // light lime
    ],
    gradient: [
      "#bfdbfe",
      // very light blue
      "#a7f3d0",
      // very light green
      "#fef08a",
      // very light yellow
      "#fecaca",
      // very light red
      "#ddd6fe",
      // very light purple
      "#fed7aa"
      // very light orange
    ]
  },
  {
    name: "vibrant",
    label: "Vibrant",
    colors: [
      "#0000ff",
      // pure blue
      "#00ff00",
      // pure green
      "#ffff00",
      // pure yellow
      "#ff0000",
      // pure red
      "#ff00ff",
      // pure magenta
      "#ff8000",
      // pure orange
      "#00ffff",
      // pure cyan
      "#8000ff"
      // pure violet
    ],
    gradient: [
      "#4000ff",
      // blue-violet
      "#0080ff",
      // blue
      "#00ffff",
      // cyan
      "#00ff80",
      // green
      "#80ff00",
      // lime
      "#ffff00"
      // yellow
    ]
  },
  {
    name: "d3Category10",
    label: "D3 Category 10",
    colors: [
      "#1f77b4",
      // blue
      "#ff7f0e",
      // orange
      "#2ca02c",
      // green
      "#d62728",
      // red
      "#9467bd",
      // purple
      "#8c564b",
      // brown
      "#e377c2",
      // pink
      "#7f7f7f",
      // gray
      "#bcbd22",
      // olive
      "#17becf"
      // cyan
    ],
    gradient: [
      "#1f77b4",
      // blue
      "#2ca02c",
      // green
      "#bcbd22",
      // olive
      "#ff7f0e",
      // orange
      "#d62728",
      // red
      "#9467bd"
      // purple
    ]
  },
  {
    name: "d3Tableau10",
    label: "D3 Tableau 10",
    colors: [
      "#4e79a7",
      // blue
      "#f28e2c",
      // orange
      "#e15759",
      // red
      "#76b7b2",
      // teal
      "#59a14f",
      // green
      "#edc949",
      // yellow
      "#af7aa1",
      // purple
      "#ff9da7",
      // pink
      "#9c755f",
      // brown
      "#bab0ab"
      // gray
    ],
    gradient: [
      "#4e79a7",
      // blue
      "#76b7b2",
      // teal
      "#59a14f",
      // green
      "#edc949",
      // yellow
      "#f28e2c",
      // orange
      "#e15759"
      // red
    ]
  },
  {
    name: "colorBrewerSet1",
    label: "ColorBrewer Set 1",
    colors: [
      "#e41a1c",
      // red
      "#377eb8",
      // blue
      "#4daf4a",
      // green
      "#984ea3",
      // purple
      "#ff7f00",
      // orange
      "#ffff33",
      // yellow
      "#a65628",
      // brown
      "#f781bf",
      // pink
      "#999999"
      // gray
    ],
    gradient: [
      "#377eb8",
      // blue
      "#4daf4a",
      // green
      "#ffff33",
      // yellow
      "#ff7f00",
      // orange
      "#e41a1c",
      // red
      "#984ea3"
      // purple
    ]
  },
  {
    name: "colorBrewerSet2",
    label: "ColorBrewer Set 2",
    colors: [
      "#66c2a5",
      // teal
      "#fc8d62",
      // orange
      "#8da0cb",
      // blue
      "#e78ac3",
      // pink
      "#a6d854",
      // lime
      "#ffd92f",
      // yellow
      "#e5c494",
      // tan
      "#b3b3b3"
      // gray
    ],
    gradient: [
      "#8da0cb",
      // blue
      "#66c2a5",
      // teal
      "#a6d854",
      // lime
      "#ffd92f",
      // yellow
      "#fc8d62",
      // orange
      "#e78ac3"
      // pink
    ]
  },
  {
    name: "colorBrewerDark2",
    label: "ColorBrewer Dark 2",
    colors: [
      "#1b9e77",
      // dark teal
      "#d95f02",
      // dark orange
      "#7570b3",
      // dark blue
      "#e7298a",
      // dark pink
      "#66a61e",
      // dark green
      "#e6ab02",
      // dark yellow
      "#a6761d",
      // dark brown
      "#666666"
      // dark gray
    ],
    gradient: [
      "#7570b3",
      // dark blue
      "#1b9e77",
      // dark teal
      "#66a61e",
      // dark green
      "#e6ab02",
      // dark yellow
      "#d95f02",
      // dark orange
      "#e7298a"
      // dark pink
    ]
  },
  {
    name: "colorBrewerPaired",
    label: "ColorBrewer Paired",
    colors: [
      "#a6cee3",
      // light blue
      "#1f78b4",
      // blue
      "#b2df8a",
      // light green
      "#33a02c",
      // green
      "#fb9a99",
      // light red
      "#e31a1c",
      // red
      "#fdbf6f",
      // light orange
      "#ff7f00",
      // orange
      "#cab2d6",
      // light purple
      "#6a3d9a",
      // purple
      "#ffff99",
      // light yellow
      "#b15928"
      // brown
    ],
    gradient: [
      "#1f78b4",
      // blue
      "#33a02c",
      // green
      "#ffff99",
      // light yellow
      "#ff7f00",
      // orange
      "#e31a1c",
      // red
      "#6a3d9a"
      // purple
    ]
  },
  {
    name: "viridis",
    label: "Viridis",
    colors: [
      "#440154",
      // dark purple
      "#482677",
      // purple
      "#3f4a8a",
      // blue-purple
      "#31678e",
      // blue
      "#26838f",
      // teal
      "#1f9d8a",
      // green-teal
      "#6cce5a",
      // green
      "#b6de2b"
      // yellow-green
    ],
    gradient: [
      "#440154",
      // dark purple
      "#482677",
      // purple
      "#3f4a8a",
      // blue-purple
      "#31678e",
      // blue
      "#26838f",
      // teal
      "#1f9d8a",
      // green-teal
      "#6cce5a",
      // green
      "#b6de2b"
      // yellow-green
    ]
  },
  {
    name: "plasma",
    label: "Plasma",
    colors: [
      "#0c0786",
      // dark blue
      "#5c01a6",
      // purple
      "#900da4",
      // magenta
      "#bf3984",
      // pink
      "#e16462",
      // coral
      "#f99b45",
      // orange
      "#fcce25",
      // yellow
      "#f0f921"
      // bright yellow
    ],
    gradient: [
      "#0c0786",
      // dark blue
      "#5c01a6",
      // purple
      "#900da4",
      // magenta
      "#bf3984",
      // pink
      "#e16462",
      // coral
      "#f99b45",
      // orange
      "#fcce25",
      // yellow
      "#f0f921"
      // bright yellow
    ]
  },
  {
    name: "inferno",
    label: "Inferno",
    colors: [
      "#000003",
      // black
      "#1f0c47",
      // dark blue
      "#550f6d",
      // purple
      "#88226a",
      // magenta
      "#a83655",
      // red
      "#cc4f39",
      // orange-red
      "#e6862a",
      // orange
      "#fec228"
      // yellow
    ],
    gradient: [
      "#000003",
      // black
      "#1f0c47",
      // dark blue
      "#550f6d",
      // purple
      "#88226a",
      // magenta
      "#a83655",
      // red
      "#cc4f39",
      // orange-red
      "#e6862a",
      // orange
      "#fec228"
      // yellow
    ]
  },
  {
    name: "magma",
    label: "Magma",
    colors: [
      "#000003",
      // black
      "#140b34",
      // dark purple
      "#3b0f6f",
      // purple
      "#641a80",
      // magenta
      "#8b2981",
      // pink
      "#b63679",
      // coral
      "#de4968",
      // red
      "#fd9f6c"
      // orange
    ],
    gradient: [
      "#000003",
      // black
      "#140b34",
      // dark purple
      "#3b0f6f",
      // purple
      "#641a80",
      // magenta
      "#8b2981",
      // pink
      "#b63679",
      // coral
      "#de4968",
      // red
      "#fd9f6c"
      // orange
    ]
  },
  {
    name: "cividis",
    label: "Cividis",
    colors: [
      "#00204c",
      // dark blue
      "#003f5c",
      // blue
      "#2c4b7a",
      // blue
      "#51576f",
      // blue-gray
      "#7f6874",
      // gray
      "#a8786e",
      // brown
      "#d2906d",
      // orange
      "#ffb570"
      // yellow
    ],
    gradient: [
      "#00204c",
      // dark blue
      "#003f5c",
      // blue
      "#2c4b7a",
      // blue
      "#51576f",
      // blue-gray
      "#7f6874",
      // gray
      "#a8786e",
      // brown
      "#d2906d",
      // orange
      "#ffb570"
      // yellow
    ]
  },
  {
    name: "turbo",
    label: "Turbo",
    colors: [
      "#30123b",
      // purple
      "#4454c4",
      // blue
      "#1dd3c0",
      // cyan
      "#42f465",
      // green
      "#b2df22",
      // lime
      "#faba39",
      // yellow
      "#f66c19",
      // orange
      "#c42e02"
      // red
    ],
    gradient: [
      "#30123b",
      // purple
      "#4454c4",
      // blue
      "#1dd3c0",
      // cyan
      "#42f465",
      // green
      "#b2df22",
      // lime
      "#faba39",
      // yellow
      "#f66c19",
      // orange
      "#c42e02"
      // red
    ]
  },
  {
    name: "warm",
    label: "Warm",
    colors: [
      "#8b0000",
      // dark red
      "#b22222",
      // red
      "#cd5c5c",
      // light red
      "#ff6347",
      // tomato
      "#ff8c00",
      // dark orange
      "#ffa500",
      // orange
      "#ffd700",
      // gold
      "#ffff00"
      // yellow
    ],
    gradient: [
      "#8b0000",
      // dark red
      "#b22222",
      // red
      "#ff6347",
      // tomato
      "#ff8c00",
      // dark orange
      "#ffa500",
      // orange
      "#ffd700"
      // gold
    ]
  },
  {
    name: "cool",
    label: "Cool",
    colors: [
      "#000080",
      // navy
      "#0000ff",
      // blue
      "#4169e1",
      // royal blue
      "#00bfff",
      // deep sky blue
      "#00ffff",
      // cyan
      "#40e0d0",
      // turquoise
      "#20b2aa",
      // light sea green
      "#008b8b"
      // dark cyan
    ],
    gradient: [
      "#000080",
      // navy
      "#0000ff",
      // blue
      "#4169e1",
      // royal blue
      "#00bfff",
      // deep sky blue
      "#00ffff",
      // cyan
      "#40e0d0"
      // turquoise
    ]
  },
  {
    name: "earth",
    label: "Earth",
    colors: [
      "#8b4513",
      // saddle brown
      "#a0522d",
      // sienna
      "#cd853f",
      // peru
      "#daa520",
      // goldenrod
      "#d2691e",
      // chocolate
      "#bc8f8f",
      // rosy brown
      "#f4a460",
      // sandy brown
      "#deb887"
      // burlywood
    ],
    gradient: [
      "#8b4513",
      // saddle brown
      "#a0522d",
      // sienna
      "#cd853f",
      // peru
      "#daa520",
      // goldenrod
      "#d2691e",
      // chocolate
      "#f4a460"
      // sandy brown
    ]
  },
  {
    name: "autumn",
    label: "Autumn",
    colors: [
      "#8b0000",
      // dark red
      "#a0522d",
      // sienna
      "#cd853f",
      // peru
      "#daa520",
      // goldenrod
      "#ff8c00",
      // dark orange
      "#ff4500",
      // orange red
      "#dc143c",
      // crimson
      "#b22222"
      // fire brick
    ],
    gradient: [
      "#8b0000",
      // dark red
      "#a0522d",
      // sienna
      "#cd853f",
      // peru
      "#daa520",
      // goldenrod
      "#ff8c00",
      // dark orange
      "#ff4500"
      // orange red
    ]
  },
  {
    name: "spring",
    label: "Spring",
    colors: [
      "#32cd32",
      // lime green
      "#98fb98",
      // pale green
      "#90ee90",
      // light green
      "#ffb6c1",
      // light pink
      "#ffc0cb",
      // pink
      "#ffffe0",
      // light yellow
      "#f0fff0",
      // honeydew
      "#e0ffff"
      // light cyan
    ],
    gradient: [
      "#32cd32",
      // lime green
      "#98fb98",
      // pale green
      "#ffffe0",
      // light yellow
      "#ffb6c1",
      // light pink
      "#ffc0cb",
      // pink
      "#e0ffff"
      // light cyan
    ]
  },
  {
    name: "winter",
    label: "Winter",
    colors: [
      "#191970",
      // midnight blue
      "#4682b4",
      // steel blue
      "#87ceeb",
      // sky blue
      "#b0e0e6",
      // powder blue
      "#e0ffff",
      // light cyan
      "#f0f8ff",
      // alice blue
      "#c0c0c0",
      // silver
      "#708090"
      // slate gray
    ],
    gradient: [
      "#191970",
      // midnight blue
      "#4682b4",
      // steel blue
      "#87ceeb",
      // sky blue
      "#b0e0e6",
      // powder blue
      "#e0ffff",
      // light cyan
      "#f0f8ff"
      // alice blue
    ]
  },
  {
    name: "neon",
    label: "Neon",
    colors: [
      "#ff0080",
      // neon pink
      "#00ff80",
      // neon green
      "#8000ff",
      // neon purple
      "#ff8000",
      // neon orange
      "#0080ff",
      // neon blue
      "#80ff00",
      // neon lime
      "#ff0040",
      // neon red
      "#40ff00"
      // bright green
    ],
    gradient: [
      "#8000ff",
      // neon purple
      "#0080ff",
      // neon blue
      "#00ff80",
      // neon green
      "#80ff00",
      // neon lime
      "#ff8000",
      // neon orange
      "#ff0080"
      // neon pink
    ]
  },
  {
    name: "retro",
    label: "Retro",
    colors: [
      "#ff69b4",
      // hot pink
      "#ffd700",
      // gold
      "#32cd32",
      // lime green
      "#00ced1",
      // dark turquoise
      "#ff6347",
      // tomato
      "#9370db",
      // medium purple
      "#ffa500",
      // orange
      "#20b2aa"
      // light sea green
    ],
    gradient: [
      "#9370db",
      // medium purple
      "#ff69b4",
      // hot pink
      "#ff6347",
      // tomato
      "#ffd700",
      // gold
      "#32cd32",
      // lime green
      "#00ced1"
      // dark turquoise
    ]
  },
  {
    name: "corporate",
    label: "Corporate",
    colors: [
      "#003366",
      // dark blue
      "#0066cc",
      // blue
      "#336699",
      // steel blue
      "#6699cc",
      // light blue
      "#4d4d4d",
      // dark gray
      "#808080",
      // gray
      "#b3b3b3",
      // light gray
      "#cccccc"
      // very light gray
    ],
    gradient: [
      "#003366",
      // dark blue
      "#0066cc",
      // blue
      "#336699",
      // steel blue
      "#6699cc",
      // light blue
      "#808080",
      // gray
      "#b3b3b3"
      // light gray
    ]
  },
  {
    name: "material",
    label: "Material Design",
    colors: [
      "#f44336",
      // red
      "#e91e63",
      // pink
      "#9c27b0",
      // purple
      "#673ab7",
      // deep purple
      "#3f51b5",
      // indigo
      "#2196f3",
      // blue
      "#03a9f4",
      // light blue
      "#00bcd4"
      // cyan
    ],
    gradient: [
      "#673ab7",
      // deep purple
      "#3f51b5",
      // indigo
      "#2196f3",
      // blue
      "#00bcd4",
      // cyan
      "#03a9f4",
      // light blue
      "#e91e63"
      // pink
    ]
  }
];
function zr(t) {
  return t && fr.find((n) => n.name === t) || fr[0];
}
const Fa = z("chevronDown");
function Yn({
  currentPalette: t = "default",
  onPaletteChange: r,
  className: n = ""
}) {
  const [a, c] = H(!1), l = Te(null), d = zr(t);
  Ce(() => {
    function o(u) {
      l.current && !l.current.contains(u.target) && c(!1);
    }
    if (a)
      return document.addEventListener("mousedown", o), () => document.removeEventListener("mousedown", o);
  }, [a]);
  const h = (o) => {
    r(o), c(!1);
  };
  return /* @__PURE__ */ s("div", { className: `relative ${n}`, ref: l, children: [
    /* @__PURE__ */ s(
      "button",
      {
        type: "button",
        onClick: () => c(!a),
        className: "inline-flex items-center gap-2 px-3 py-1.5 bg-dc-surface border border-dc-border rounded-md shadow-xs text-sm font-medium text-dc-text-secondary hover:bg-dc-surface-hover focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-dc-accent",
        children: [
          /* @__PURE__ */ s("div", { className: "hidden md:flex items-center gap-1.5", children: [
            /* @__PURE__ */ e("div", { className: "flex gap-0.5", children: d.colors.slice(0, 4).map((o, u) => /* @__PURE__ */ e(
              "div",
              {
                className: "w-3 h-3 rounded-xs border border-dc-border",
                style: { backgroundColor: o },
                title: `Series Color ${u + 1}`
              },
              u
            )) }),
            /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-secondary", children: "|" }),
            /* @__PURE__ */ e("div", { className: "flex gap-0.5", children: d.gradient.slice(0, 3).map((o, u) => /* @__PURE__ */ e(
              "div",
              {
                className: "w-2 h-3 border-r first:rounded-l-sm last:rounded-r-sm last:border-r-0",
                style: {
                  backgroundColor: o,
                  borderColor: "var(--dc-border)"
                },
                title: `Gradient Color ${u + 1}`
              },
              u
            )) })
          ] }),
          /* @__PURE__ */ e("span", { children: d.label }),
          /* @__PURE__ */ e(
            Fa,
            {
              className: `w-4 h-4 transition-transform ${a ? "rotate-180" : ""}`
            }
          )
        ]
      }
    ),
    a && /* @__PURE__ */ e("div", { className: "absolute top-full left-0 mt-1 w-72 md:w-80 lg:w-96 bg-dc-surface border border-dc-border rounded-md shadow-lg z-50 max-h-80 overflow-y-auto", children: /* @__PURE__ */ e("div", { className: "py-1", children: fr.slice().sort((o, u) => o.label.localeCompare(u.label)).map((o) => /* @__PURE__ */ e(
      "button",
      {
        type: "button",
        onClick: () => h(o.name),
        className: `w-full px-3 py-2 text-left text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover ${o.name === t ? "bg-dc-surface-secondary" : "text-dc-text-secondary"}`,
        style: o.name === t ? { color: "var(--dc-primary)" } : void 0,
        children: /* @__PURE__ */ s("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ s("div", { className: "hidden md:flex items-center gap-2", children: [
            /* @__PURE__ */ e("div", { className: "flex gap-0.5", children: o.colors.slice(0, 6).map((u, m) => /* @__PURE__ */ e(
              "div",
              {
                className: "w-3 h-3 rounded-xs border border-dc-border",
                style: { backgroundColor: u }
              },
              `series-${m}`
            )) }),
            /* @__PURE__ */ e("div", { className: "w-px h-4 bg-dc-border" }),
            /* @__PURE__ */ e("div", { className: "flex", children: o.gradient.map((u, m) => /* @__PURE__ */ e(
              "div",
              {
                className: "w-2 h-4 first:rounded-l-sm last:rounded-r-sm",
                style: { backgroundColor: u }
              },
              `gradient-${m}`
            )) })
          ] }),
          /* @__PURE__ */ e("span", { className: "font-medium", children: o.label }),
          o.name === t && /* @__PURE__ */ e("div", { className: "ml-auto", children: /* @__PURE__ */ e("div", { className: "w-2 h-2 rounded-full", style: { backgroundColor: "var(--dc-primary)" } }) })
        ] })
      },
      o.name
    )) }) })
  ] });
}
const La = gt(function({
  executionStatus: r,
  executionResults: n,
  executionError: a,
  totalRowCount: c,
  resultsStale: l = !1,
  chartType: d = "line",
  chartConfig: h = {},
  displayConfig: o = {},
  colorPalette: u,
  currentPaletteName: m,
  onColorPaletteChange: x,
  query: f,
  activeView: S = "chart",
  onActiveViewChange: T,
  displayLimit: D = 100,
  onDisplayLimitChange: k,
  hasMetrics: A = !1,
  // Debug props
  debugQuery: _,
  debugSql: O,
  debugAnalysis: R,
  debugLoading: y,
  debugError: i,
  // Share props
  onShareClick: g,
  canShare: p = !1,
  shareButtonState: b = "idle",
  // Clear functionality
  onClearClick: w,
  canClear: v = !1,
  // AI functionality
  enableAI: M = !1,
  isAIOpen: $ = !1,
  onAIToggle: C
}) {
  const [L, I] = H(!1);
  Ce(() => {
    !A && S === "chart" && T("table");
  }, [A, S, T]);
  const E = z("success"), K = z("error"), P = z("warning"), Ne = z("table"), ye = z("measure"), Ue = z("codeBracket"), Q = z("share"), ue = z("check"), me = z("delete"), J = z("sparkles"), Y = () => /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
    /* @__PURE__ */ e(
      "div",
      {
        className: "animate-spin rounded-full h-12 w-12 border-b-2 mx-auto mb-4",
        style: { borderBottomColor: "var(--dc-primary)" }
      }
    ),
    /* @__PURE__ */ e("div", { className: "text-sm font-semibold text-dc-text-secondary mb-1", children: "Executing Query..." }),
    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted", children: "Running your query against the cube API" })
  ] }) }), ge = () => /* @__PURE__ */ s("div", { className: "h-full flex flex-col", children: [
    Be(),
    /* @__PURE__ */ e("div", { className: "flex-1 flex items-center justify-center p-4", children: L ? /* @__PURE__ */ e("div", { className: "w-full h-full overflow-auto", children: Me() }) : /* @__PURE__ */ s("div", { className: "text-center max-w-md", children: [
      /* @__PURE__ */ e(K, { className: "w-12 h-12 mx-auto text-dc-error mb-4" }),
      /* @__PURE__ */ e("div", { className: "text-sm font-semibold text-dc-text mb-2", children: "Query Execution Failed" }),
      /* @__PURE__ */ e("div", { className: "text-sm text-dc-text-secondary mb-4", children: "There was an error executing your query. Please check the query and try again." }),
      a && /* @__PURE__ */ e("div", { className: "bg-dc-danger-bg border border-dc-error rounded-lg p-3 text-left", children: /* @__PURE__ */ e("div", { className: "text-xs font-mono text-dc-error break-words", children: a }) })
    ] }) })
  ] }), ee = !!(f.measures && f.measures.length > 0 || f.dimensions && f.dimensions.length > 0 || f.timeDimensions && f.timeDimensions.length > 0), j = () => /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
    /* @__PURE__ */ e(
      "div",
      {
        className: "animate-spin rounded-full h-12 w-12 border-b-2 mx-auto mb-4",
        style: { borderBottomColor: "var(--dc-primary)" }
      }
    ),
    /* @__PURE__ */ e("div", { className: "text-sm font-semibold text-dc-text-secondary mb-1", children: "Preparing Query..." }),
    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted", children: "Your query will execute shortly" })
  ] }) }), re = () => /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center pt-6", children: /* @__PURE__ */ s("div", { className: "text-center mb-16", children: [
    /* @__PURE__ */ e(ye, { className: "w-12 h-12 mx-auto text-dc-text-muted mb-3" }),
    /* @__PURE__ */ e("div", { className: "text-sm font-semibold text-dc-text-secondary mb-1", children: "No Results Yet" }),
    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted mb-4", children: "Add metrics or breakdowns from the panel on the right to see results" }),
    M && C && /* @__PURE__ */ s(
      "button",
      {
        onClick: C,
        className: "inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-dc-accent hover:bg-dc-accent rounded-lg transition-colors shadow-sm",
        children: [
          /* @__PURE__ */ e(J, { className: "w-4 h-4" }),
          "Analyse with AI"
        ]
      }
    )
  ] }) }), xe = () => /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
    /* @__PURE__ */ e(E, { className: "w-12 h-12 mx-auto text-dc-success mb-3" }),
    /* @__PURE__ */ e("div", { className: "text-sm font-semibold text-dc-text mb-1", children: "Query Successful" }),
    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted", children: "No data returned from the query" })
  ] }) }), $e = () => !n || n.length === 0 ? /* @__PURE__ */ e("div", { className: "flex items-center justify-center h-full text-dc-text-muted", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
    /* @__PURE__ */ e(ye, { className: "w-12 h-12 mx-auto mb-3 opacity-50" }),
    /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "No data to display" }),
    /* @__PURE__ */ e("div", { className: "text-xs", children: "Run a query to see chart visualization" })
  ] }) }) : $n(d) ? /* @__PURE__ */ e(
    Mr,
    {
      chartType: d,
      data: n,
      chartConfig: h,
      displayConfig: o,
      colorPalette: u,
      queryObject: f,
      height: "100%",
      fallback: /* @__PURE__ */ e("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ e("div", { className: "animate-pulse bg-dc-surface-secondary rounded w-full h-full" }) })
    }
  ) : /* @__PURE__ */ e("div", { className: "flex items-center justify-center h-full text-dc-text-muted", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
    /* @__PURE__ */ e(P, { className: "w-12 h-12 mx-auto mb-3 opacity-50" }),
    /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "Unsupported chart type" }),
    /* @__PURE__ */ e("div", { className: "text-xs", children: d })
  ] }) }), Me = () => /* @__PURE__ */ s("div", { className: "p-4 space-y-4 overflow-auto h-full", children: [
    a && /* @__PURE__ */ s("div", { className: "bg-dc-danger-bg dark:bg-dc-danger-bg border border-dc-error dark:border-dc-error rounded p-3", children: [
      /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-error dark:text-dc-error mb-1", children: "Execution Error" }),
      /* @__PURE__ */ e("p", { className: "text-sm text-dc-error dark:text-dc-error", children: a })
    ] }),
    /* @__PURE__ */ s("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
      /* @__PURE__ */ e("div", { children: _ ? /* @__PURE__ */ e(
        dn,
        {
          code: JSON.stringify(_, null, 2),
          language: "json",
          title: "JSON Query",
          maxHeight: "16rem"
        }
      ) : /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-text mb-2", children: "JSON Query" }),
        /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary border border-dc-border rounded p-3 text-dc-text-muted text-sm", children: "No query" })
      ] }) }),
      /* @__PURE__ */ e("div", { children: y ? /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-text mb-2", children: "Generated SQL" }),
        /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary border border-dc-border rounded p-3 text-dc-text-muted text-sm", children: "Loading..." })
      ] }) : i ? /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-text mb-2", children: "Generated SQL" }),
        /* @__PURE__ */ e("div", { className: "text-dc-error text-sm bg-dc-danger-bg dark:bg-dc-danger-bg p-3 rounded border border-dc-error dark:border-dc-error", children: i })
      ] }) : O ? /* @__PURE__ */ e(
        dn,
        {
          code: O.sql + (O.params && O.params.length > 0 ? `

-- Parameters:
` + JSON.stringify(O.params, null, 2) : ""),
          language: "sql",
          title: "Generated SQL",
          maxHeight: "16rem"
        }
      ) : /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-text mb-2", children: "Generated SQL" }),
        /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary border border-dc-border rounded p-3 text-dc-text-muted text-sm", children: "Add metrics to generate SQL" })
      ] }) })
    ] }),
    /* @__PURE__ */ s("div", { children: [
      /* @__PURE__ */ e("h4", { className: "text-sm font-semibold text-dc-text mb-2", children: "Query Analysis" }),
      y ? /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary border border-dc-border rounded p-3 text-dc-text-muted text-sm", children: "Loading..." }) : R ? /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary border border-dc-border rounded p-3", children: /* @__PURE__ */ e(Da, { analysis: R }) }) : /* @__PURE__ */ e("div", { className: "bg-dc-surface-secondary border border-dc-border rounded p-3 text-dc-text-muted text-sm", children: i ? "Analysis unavailable due to error" : "Add metrics to see analysis" })
    ] })
  ] }), ze = () => {
    if (!n || n.length === 0)
      return /* @__PURE__ */ e("div", { className: "flex items-center justify-center h-full text-dc-text-muted", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
        /* @__PURE__ */ e(Ne, { className: "w-12 h-12 mx-auto mb-3 opacity-50" }),
        /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "No data to display" }),
        /* @__PURE__ */ e("div", { className: "text-xs", children: "Run a query to see table data" })
      ] }) });
    const Ae = n.slice(0, D);
    return /* @__PURE__ */ e(
      Mr,
      {
        chartType: "table",
        data: Ae,
        colorPalette: u,
        queryObject: f,
        height: "100%",
        fallback: /* @__PURE__ */ e("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ e("div", { className: "animate-pulse bg-dc-surface-secondary rounded w-full h-full" }) })
      }
    );
  }, ve = () => /* @__PURE__ */ e("div", { className: "absolute inset-0 flex items-center justify-center bg-dc-surface bg-opacity-75 z-10", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
    /* @__PURE__ */ e(
      "div",
      {
        className: "animate-spin rounded-full h-10 w-10 border-b-2 mx-auto mb-2",
        style: { borderBottomColor: "var(--dc-primary)" }
      }
    ),
    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-secondary", children: "Refreshing results..." })
  ] }) }), Be = () => {
    const Ae = n && n.length > 0;
    return /* @__PURE__ */ s("div", { className: "px-4 py-2 border-b border-dc-border bg-dc-surface-secondary flex-shrink-0", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ s("div", { className: "flex items-center", children: [
          r === "refreshing" ? /* @__PURE__ */ e(
            "div",
            {
              className: "w-4 h-4 mr-2 rounded-full border-b-2 animate-spin",
              style: { borderBottomColor: "var(--dc-primary)" }
            }
          ) : Ae ? /* @__PURE__ */ e(E, { className: "w-4 h-4 text-dc-success mr-2" }) : r === "error" ? /* @__PURE__ */ e(K, { className: "w-4 h-4 text-dc-error mr-2" }) : /* @__PURE__ */ e(P, { className: "w-4 h-4 text-dc-text-muted mr-2" }),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text-secondary", children: Ae ? /* @__PURE__ */ s(Ie, { children: [
            n.length,
            " row",
            n.length !== 1 ? "s" : "",
            c !== null && c > n.length && /* @__PURE__ */ s("span", { className: "text-dc-text-muted", children: [
              " of ",
              c.toLocaleString()
            ] }),
            l && /* @__PURE__ */ e("span", { className: "text-dc-warning ml-2", children: "• Results may be outdated" })
          ] }) : r === "error" ? "Query failed" : r === "loading" ? "Executing..." : "No results" })
        ] }),
        /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
          Ae && S === "table" && !L && k && /* @__PURE__ */ s(
            "select",
            {
              value: D,
              onChange: (ke) => k(Number(ke.target.value)),
              className: "text-xs border border-dc-border rounded px-2 py-1 bg-dc-surface text-dc-text focus:outline-none focus:ring-1 focus:ring-dc-primary",
              children: [
                /* @__PURE__ */ e("option", { value: 50, children: "50 rows" }),
                /* @__PURE__ */ e("option", { value: 100, children: "100 rows" }),
                /* @__PURE__ */ e("option", { value: 250, children: "250 rows" }),
                /* @__PURE__ */ e("option", { value: 500, children: "500 rows" })
              ]
            }
          ),
          M && C && /* @__PURE__ */ s(
            "button",
            {
              onClick: C,
              className: `flex items-center gap-1 px-2 py-1.5 text-xs font-medium rounded transition-colors ${$ ? "text-white bg-dc-accent border border-dc-accent" : "text-dc-accent dark:text-dc-accent bg-dc-accent-bg dark:bg-dc-accent-bg border border-dc-accent dark:border-dc-accent hover:bg-dc-accent-bg dark:hover:bg-dc-accent-bg"}`,
              title: $ ? "Close AI assistant" : "Analyse with AI",
              children: [
                /* @__PURE__ */ e(J, { className: "w-3 h-3" }),
                /* @__PURE__ */ e("span", { className: "hidden sm:inline", children: "Analyse with AI" })
              ]
            }
          ),
          x && Ae && /* @__PURE__ */ e(
            Yn,
            {
              currentPalette: m || "default",
              onPaletteChange: x
            }
          ),
          g && /* @__PURE__ */ e(
            "button",
            {
              onClick: g,
              className: `flex items-center gap-1 px-2 py-1.5 text-xs font-medium rounded transition-colors ${b === "idle" && p ? "text-dc-accent dark:text-dc-accent bg-dc-accent-bg dark:bg-dc-accent-bg border border-dc-accent dark:border-dc-accent hover:bg-dc-accent-bg dark:hover:bg-dc-accent-bg" : b !== "idle" ? "text-dc-success dark:text-dc-success bg-dc-success-bg dark:bg-dc-success-bg border border-dc-success dark:border-dc-success" : "text-dc-text-muted bg-dc-surface-secondary border border-dc-border cursor-not-allowed"}`,
              title: b === "idle" ? "Share this analysis" : "Link copied!",
              disabled: !p || b !== "idle",
              children: b === "idle" ? /* @__PURE__ */ s(Ie, { children: [
                /* @__PURE__ */ e(Q, { className: "w-3 h-3" }),
                /* @__PURE__ */ e("span", { className: "hidden sm:inline", children: "Share" })
              ] }) : b === "copied" ? /* @__PURE__ */ s(Ie, { children: [
                /* @__PURE__ */ e(ue, { className: "w-3 h-3" }),
                /* @__PURE__ */ e("span", { className: "hidden sm:inline", children: "Copied!" })
              ] }) : /* @__PURE__ */ s(Ie, { children: [
                /* @__PURE__ */ e(ue, { className: "w-3 h-3" }),
                /* @__PURE__ */ e("span", { className: "hidden sm:inline", children: "Copied!" }),
                /* @__PURE__ */ e("span", { className: "hidden lg:inline text-[10px] opacity-75", children: "(no chart)" })
              ] })
            }
          ),
          w && v && /* @__PURE__ */ s(
            "button",
            {
              onClick: w,
              className: "flex items-center gap-1 px-2 py-1.5 text-xs font-medium text-dc-text-secondary hover:text-dc-text bg-dc-surface hover:bg-dc-surface-hover border border-dc-border rounded transition-colors",
              title: "Clear all query data",
              children: [
                /* @__PURE__ */ e(me, { className: "w-3 h-3" }),
                /* @__PURE__ */ e("span", { className: "hidden sm:inline", children: "Clear" })
              ]
            }
          ),
          /* @__PURE__ */ s(
            "button",
            {
              onClick: () => I(!L),
              className: `p-1.5 rounded transition-colors relative ${L ? "bg-dc-primary text-white" : "text-dc-text-secondary hover:text-dc-text hover:bg-dc-surface-hover"}`,
              title: L ? "Hide debug info" : "Show debug info",
              children: [
                /* @__PURE__ */ e(Ue, { className: "w-4 h-4" }),
                (a || i) && !L && /* @__PURE__ */ e("span", { className: "absolute -top-0.5 -right-0.5 w-2 h-2 bg-dc-danger-bg0 rounded-full" })
              ]
            }
          )
        ] })
      ] }),
      Ae && c !== null && c > 1e3 && /* @__PURE__ */ s("div", { className: "mt-2 bg-dc-warning-bg border border-dc-warning rounded-lg p-2 flex items-start", children: [
        /* @__PURE__ */ e(P, { className: "w-4 h-4 text-dc-warning mr-2 shrink-0 mt-0.5" }),
        /* @__PURE__ */ s("div", { className: "text-xs text-dc-warning", children: [
          /* @__PURE__ */ e("span", { className: "font-semibold", children: "Large dataset:" }),
          " ",
          c.toLocaleString(),
          " rows. Consider adding filters to improve performance."
        ] })
      ] })
    ] });
  }, U = () => n && n.length > 0 ? /* @__PURE__ */ s("div", { className: "h-full flex flex-col", children: [
    Be(),
    /* @__PURE__ */ e("div", { className: "flex-1 min-h-0 relative overflow-auto", children: L ? Me() : S === "chart" ? /* @__PURE__ */ e("div", { className: "p-4 h-full", children: $e() }) : /* @__PURE__ */ e("div", { className: "h-full", children: ze() }) }),
    !L && /* @__PURE__ */ e("div", { className: "px-4 py-3 border-t border-dc-border bg-dc-surface flex justify-center flex-shrink-0", children: /* @__PURE__ */ s("div", { className: "flex items-center bg-dc-surface-secondary border border-dc-border rounded-md overflow-hidden", children: [
      /* @__PURE__ */ s(
        "button",
        {
          onClick: () => A && T("chart"),
          disabled: !A,
          className: `flex items-center gap-1.5 px-4 py-1.5 text-sm font-medium transition-colors ${S === "chart" ? "bg-dc-primary text-white" : A ? "text-dc-text-secondary hover:bg-dc-surface-hover" : "text-dc-text-disabled bg-dc-surface-tertiary cursor-not-allowed"}`,
          title: A ? "Chart view" : "Add metrics to enable chart view",
          children: [
            /* @__PURE__ */ e(ye, { className: "w-4 h-4" }),
            "Chart"
          ]
        }
      ),
      /* @__PURE__ */ s(
        "button",
        {
          onClick: () => T("table"),
          className: `flex items-center gap-1.5 px-4 py-1.5 text-sm font-medium transition-colors ${S === "table" ? "bg-dc-primary text-white" : "text-dc-text-secondary hover:bg-dc-surface-hover"}`,
          title: "Table view",
          children: [
            /* @__PURE__ */ e(Ne, { className: "w-4 h-4" }),
            "Table"
          ]
        }
      )
    ] }) })
  ] }) : /* @__PURE__ */ s("div", { className: "h-full flex flex-col", children: [
    Be(),
    /* @__PURE__ */ e("div", { className: "flex-1 min-h-0 relative overflow-auto", children: L ? Me() : xe() })
  ] }), fe = n !== null, ae = fe && (r !== "idle" || ee);
  return /* @__PURE__ */ s("div", { className: "h-full min-h-[400px] flex flex-col bg-dc-surface relative", children: [
    r === "idle" && !ee && re(),
    r === "idle" && ee && !fe && j(),
    r === "loading" && !fe && Y(),
    r === "error" && !fe && ge(),
    (r === "success" || ae) && U(),
    (r === "loading" || r === "refreshing") && fe && ve()
  ] });
}), ja = gt(function({
  metric: r,
  fieldMeta: n,
  onRemove: a,
  sortDirection: c,
  sortPriority: l,
  onToggleSort: d,
  index: h,
  isDragging: o,
  onDragStart: u,
  onDragEnd: m
}) {
  const x = z("close"), f = z("chevronUp"), S = z("chevronDown"), T = z("chevronUpDown"), D = n?.type || "count", k = qt(D) || z("measure"), A = n?.shortTitle || n?.title || r.field.split(".").pop() || r.field, _ = r.field.split(".")[0], O = () => {
    switch (c) {
      case "asc":
        return f ? /* @__PURE__ */ e(f, { className: "w-4 h-4" }) : "↑";
      case "desc":
        return S ? /* @__PURE__ */ e(S, { className: "w-4 h-4" }) : "↓";
      default:
        return T ? /* @__PURE__ */ e(T, { className: "w-4 h-4" }) : "⇅";
    }
  }, R = () => {
    switch (c) {
      case "asc":
        return "Sorted ascending (click for descending)";
      case "desc":
        return "Sorted descending (click to remove)";
      default:
        return "Click to sort ascending";
    }
  }, y = typeof h == "number" && u && m;
  return /* @__PURE__ */ s(
    "div",
    {
      className: `flex items-center gap-2 p-2 bg-dc-surface-secondary rounded-lg group hover:bg-dc-surface-tertiary transition-all duration-150 ${y ? "cursor-grab active:cursor-grabbing" : ""} ${o ? "opacity-30" : ""}`,
      draggable: y ? !0 : void 0,
      onDragStart: y ? (i) => u(i, h) : void 0,
      onDragEnd: y ? m : void 0,
      children: [
        /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-measure text-dc-measure-text flex-shrink-0", children: k && /* @__PURE__ */ e(k, { className: "w-4 h-4" }) }),
        /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
          /* @__PURE__ */ e("div", { className: "text-sm text-dc-text truncate", title: r.field, children: A }),
          /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: _ })
        ] }),
        d && /* @__PURE__ */ s(
          "button",
          {
            onClick: d,
            className: `p-1 transition-opacity flex-shrink-0 flex items-center gap-0.5 ${c ? "opacity-100 text-dc-primary" : "opacity-100 sm:opacity-0 sm:group-hover:opacity-100 text-dc-text-muted hover:text-dc-primary"}`,
            title: R(),
            children: [
              O(),
              c && l && /* @__PURE__ */ s("span", { className: "text-xs font-medium", children: [
                "(",
                l,
                ")"
              ] })
            ]
          }
        ),
        /* @__PURE__ */ e(
          "button",
          {
            onClick: a,
            className: "p-1 text-dc-text-muted hover:text-dc-danger opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity flex-shrink-0",
            title: "Remove metric",
            children: /* @__PURE__ */ e(x, { className: "w-4 h-4" })
          }
        )
      ]
    }
  );
}), Pa = z("add");
function Ba(t, r) {
  if (!r?.cubes) return null;
  const [n] = t.split("."), a = r.cubes.find((c) => c.name === n);
  return a && a.measures?.find((c) => c.name === t) || null;
}
function qa(t) {
  switch (t) {
    case null:
      return "asc";
    case "asc":
      return "desc";
    case "desc":
      return null;
    default:
      return "asc";
  }
}
const Va = gt(function({
  metrics: r,
  schema: n,
  onAdd: a,
  onRemove: c,
  order: l,
  onOrderChange: d,
  onReorder: h
}) {
  const [o, u] = H(null), [m, x] = H(null), f = Te(null), S = Te(null), T = Oe(() => l ? Object.keys(l) : [], [l]), D = Oe(() => r.map((p, b) => {
    const w = l?.[p.field] || null, v = w ? T.indexOf(p.field) + 1 : void 0;
    return {
      metric: p,
      fieldMeta: Ba(p.field, n),
      sortDirection: w,
      sortPriority: v,
      index: b
    };
  }), [r, n, l, T]), k = Te(null), A = F((p, b) => {
    u(b), f.current = b, p.dataTransfer.effectAllowed = "move", p.dataTransfer.setData("text/plain", JSON.stringify({ type: "metric", index: b, field: r[b].field }));
    const w = p.currentTarget, v = w.cloneNode(!0);
    v.style.cssText = `
      position: absolute;
      top: -9999px;
      left: -9999px;
      width: ${w.offsetWidth}px;
      opacity: 0.7;
      transform: rotate(2deg);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      pointer-events: none;
    `, document.body.appendChild(v), k.current = v;
    const M = w.getBoundingClientRect(), $ = p.clientX - M.left, C = p.clientY - M.top;
    p.dataTransfer.setDragImage(v, $, C);
  }, [r]), _ = F(() => {
    u(null), x(null), f.current = null, S.current = null, k.current && (document.body.removeChild(k.current), k.current = null);
  }, []), O = F((p, b) => {
    p.preventDefault(), p.stopPropagation();
    const w = f.current;
    if (w === null) return;
    const v = p.currentTarget.getBoundingClientRect();
    let C = p.clientY - v.top < v.height / 2 ? b : b + 1;
    C === w || C === w + 1 ? (x(null), S.current = null) : (x(C), S.current = C);
  }, []), R = F((p) => {
    p.preventDefault(), p.stopPropagation();
    const b = f.current, w = S.current;
    if (u(null), x(null), f.current = null, S.current = null, b === null || w === null || !h)
      return;
    const v = w > b ? w - 1 : w;
    v !== b && h(b, v);
  }, [h]), y = F((p) => {
    const b = p.relatedTarget;
    (!b || !p.currentTarget.contains(b)) && x(null);
  }, []), i = F((p) => {
    if (o === null || m === null) return "";
    const b = 40;
    if (p === o) return "";
    if (o < m) {
      if (p > o && p < m)
        return "";
      if (p === m - 1)
        return `translateY(-${b / 2}px)`;
      if (p >= m)
        return `translateY(${b / 2}px)`;
    } else if (p >= m && p < o)
      return `translateY(${b / 2}px)`;
    return "";
  }, [o, m]), g = F((p) => o === null || m === null ? !1 : p === m, [o, m]);
  return /* @__PURE__ */ s("div", { children: [
    /* @__PURE__ */ s(
      "button",
      {
        onClick: a,
        className: "flex items-center justify-between mb-3 w-full py-1 px-2 -ml-2 rounded-lg hover:bg-dc-primary/10 transition-colors group",
        title: "Add metric",
        children: [
          /* @__PURE__ */ e(Ot, { children: "Metrics" }),
          /* @__PURE__ */ e(Pa, { className: "w-5 h-5 text-dc-text-secondary group-hover:text-dc-primary transition-colors" })
        ]
      }
    ),
    /* @__PURE__ */ s(
      "div",
      {
        className: "space-y-2",
        onDragLeave: h ? y : void 0,
        onDragOver: h ? (p) => p.preventDefault() : void 0,
        onDrop: h ? R : void 0,
        children: [
          D.map(({ metric: p, fieldMeta: b, sortDirection: w, sortPriority: v, index: M }) => {
            const $ = i(M), C = g(M);
            return /* @__PURE__ */ s(
              "div",
              {
                className: "relative",
                style: {
                  transform: $,
                  transition: o !== null ? "transform 0.15s ease-out" : "none"
                },
                onDragOver: h ? (L) => O(L, M) : void 0,
                onDrop: h ? R : void 0,
                children: [
                  C && /* @__PURE__ */ e("div", { className: "absolute -top-5 left-0 right-0 flex items-center justify-center pointer-events-none z-10", children: /* @__PURE__ */ e("div", { className: "h-0.5 w-full bg-dc-primary rounded-full" }) }),
                  /* @__PURE__ */ e(
                    ja,
                    {
                      metric: p,
                      fieldMeta: b,
                      onRemove: () => c(p.id),
                      sortDirection: w,
                      sortPriority: v,
                      onToggleSort: d ? () => {
                        const L = qa(w);
                        d(p.field, L);
                      } : void 0,
                      index: M,
                      isDragging: o === M,
                      onDragStart: h ? A : void 0,
                      onDragEnd: h ? _ : void 0
                    }
                  )
                ]
              },
              p.id
            );
          }),
          h && o !== null && m === r.length && /* @__PURE__ */ e("div", { className: "relative h-2", children: /* @__PURE__ */ e("div", { className: "absolute top-0 left-0 right-0 flex items-center justify-center pointer-events-none z-10", children: /* @__PURE__ */ e("div", { className: "h-0.5 w-full bg-dc-primary rounded-full" }) }) }),
          h && r.length > 0 && o !== null && /* @__PURE__ */ e(
            "div",
            {
              className: "h-8",
              onDragOver: (p) => {
                p.preventDefault();
                const b = r.length, w = f.current;
                S.current !== b && w !== b - 1 && (x(b), S.current = b);
              },
              onDrop: R
            }
          )
        ]
      }
    )
  ] });
}), Ha = [
  { value: "hour", label: "Hour" },
  { value: "day", label: "Day" },
  { value: "week", label: "Week" },
  { value: "month", label: "Month" },
  { value: "quarter", label: "Quarter" },
  { value: "year", label: "Year" }
], za = gt(function({
  breakdown: r,
  fieldMeta: n,
  onRemove: a,
  onGranularityChange: c,
  sortDirection: l,
  sortPriority: d,
  onToggleSort: h,
  index: o,
  isDragging: u,
  onDragStart: m,
  onDragEnd: x
}) {
  const f = z("dimension"), S = z("timeDimension"), T = z("close"), D = z("chevronUp"), k = z("chevronDown"), A = z("chevronUpDown"), _ = n?.shortTitle || n?.title || r.field.split(".").pop() || r.field, O = r.field.split(".")[0], R = r.isTimeDimension ? S : f, y = () => {
    switch (l) {
      case "asc":
        return D ? /* @__PURE__ */ e(D, { className: "w-4 h-4" }) : "↑";
      case "desc":
        return k ? /* @__PURE__ */ e(k, { className: "w-4 h-4" }) : "↓";
      default:
        return A ? /* @__PURE__ */ e(A, { className: "w-4 h-4" }) : "⇅";
    }
  }, i = () => {
    switch (l) {
      case "asc":
        return "Sorted ascending (click for descending)";
      case "desc":
        return "Sorted descending (click to remove)";
      default:
        return "Click to sort ascending";
    }
  }, g = typeof o == "number" && m && x;
  return /* @__PURE__ */ s(
    "div",
    {
      className: `flex items-center gap-2 p-2 bg-dc-surface-secondary rounded-lg group hover:bg-dc-surface-tertiary transition-all duration-150 ${g ? "cursor-grab active:cursor-grabbing" : ""} ${u ? "opacity-30" : ""}`,
      draggable: g ? !0 : void 0,
      onDragStart: g ? (p) => m(p, o) : void 0,
      onDragEnd: g ? x : void 0,
      children: [
        /* @__PURE__ */ e("span", { className: `w-6 h-6 flex items-center justify-center rounded flex-shrink-0 ${r.isTimeDimension ? "bg-dc-time-dimension text-dc-time-dimension-text" : "bg-dc-dimension text-dc-dimension-text"}`, children: /* @__PURE__ */ e(R, { className: "w-4 h-4" }) }),
        /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
          /* @__PURE__ */ e("div", { className: "text-sm text-dc-text truncate", title: r.field, children: _ }),
          /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: O })
        ] }),
        r.isTimeDimension && c && /* @__PURE__ */ e(
          "select",
          {
            value: r.granularity || "day",
            onChange: (p) => c(p.target.value),
            onClick: (p) => p.stopPropagation(),
            className: "text-xs bg-dc-surface border border-dc-border rounded px-2 py-1 text-dc-text focus:outline-none focus:ring-1 focus:ring-dc-primary flex-shrink-0",
            children: Ha.map((p) => /* @__PURE__ */ e("option", { value: p.value, children: p.label }, p.value))
          }
        ),
        h && /* @__PURE__ */ s(
          "button",
          {
            onClick: h,
            className: `p-1 transition-opacity flex-shrink-0 flex items-center gap-0.5 ${l ? "opacity-100 text-dc-primary" : "opacity-100 sm:opacity-0 sm:group-hover:opacity-100 text-dc-text-muted hover:text-dc-primary"}`,
            title: i(),
            children: [
              y(),
              l && d && /* @__PURE__ */ s("span", { className: "text-xs font-medium", children: [
                "(",
                d,
                ")"
              ] })
            ]
          }
        ),
        /* @__PURE__ */ e(
          "button",
          {
            onClick: a,
            className: "p-1 text-dc-text-muted hover:text-dc-danger opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity flex-shrink-0",
            title: "Remove breakdown",
            children: /* @__PURE__ */ e(T, { className: "w-4 h-4" })
          }
        )
      ]
    }
  );
}), Qa = z("add");
function Ua(t, r) {
  if (!r?.cubes) return null;
  const [n] = t.split("."), a = r.cubes.find((c) => c.name === n);
  return a && a.dimensions?.find((c) => c.name === t) || null;
}
function Ga(t) {
  switch (t) {
    case null:
      return "asc";
    case "asc":
      return "desc";
    case "desc":
      return null;
    default:
      return "asc";
  }
}
const Wa = gt(function({
  breakdowns: r,
  schema: n,
  onAdd: a,
  onRemove: c,
  onGranularityChange: l,
  order: d,
  onOrderChange: h,
  onReorder: o
}) {
  const [u, m] = H(null), [x, f] = H(null), S = Te(null), T = Te(null), D = Oe(() => d ? Object.keys(d) : [], [d]), k = Oe(() => r.map((b, w) => {
    const v = d?.[b.field] || null, M = v ? D.indexOf(b.field) + 1 : void 0;
    return {
      breakdown: b,
      fieldMeta: Ua(b.field, n),
      sortDirection: v,
      sortPriority: M,
      index: w
    };
  }), [r, n, d, D]), A = Te(null), _ = F((b, w) => {
    m(w), S.current = w, b.dataTransfer.effectAllowed = "move", b.dataTransfer.setData("text/plain", JSON.stringify({ type: "breakdown", index: w, field: r[w].field }));
    const v = b.currentTarget, M = v.cloneNode(!0);
    M.style.cssText = `
      position: absolute;
      top: -9999px;
      left: -9999px;
      width: ${v.offsetWidth}px;
      opacity: 0.7;
      transform: rotate(2deg);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      pointer-events: none;
    `, document.body.appendChild(M), A.current = M;
    const $ = v.getBoundingClientRect(), C = b.clientX - $.left, L = b.clientY - $.top;
    b.dataTransfer.setDragImage(M, C, L);
  }, [r]), O = F(() => {
    m(null), f(null), S.current = null, T.current = null, A.current && (document.body.removeChild(A.current), A.current = null);
  }, []), R = F((b, w) => {
    b.preventDefault(), b.stopPropagation();
    const v = S.current;
    if (v === null) return;
    const M = b.currentTarget.getBoundingClientRect();
    let L = b.clientY - M.top < M.height / 2 ? w : w + 1;
    L === v || L === v + 1 ? (f(null), T.current = null) : (f(L), T.current = L);
  }, []), y = F((b) => {
    b.preventDefault(), b.stopPropagation();
    const w = S.current, v = T.current;
    if (m(null), f(null), S.current = null, T.current = null, w === null || v === null || !o)
      return;
    const M = v > w ? v - 1 : v;
    M !== w && o(w, M);
  }, [o]), i = F((b) => {
    const w = b.relatedTarget;
    (!w || !b.currentTarget.contains(w)) && f(null);
  }, []), g = F((b) => {
    if (u === null || x === null) return "";
    const w = 40;
    if (b === u) return "";
    if (u < x) {
      if (b > u && b < x)
        return "";
      if (b === x - 1)
        return `translateY(-${w / 2}px)`;
      if (b >= x)
        return `translateY(${w / 2}px)`;
    } else if (b >= x && b < u)
      return `translateY(${w / 2}px)`;
    return "";
  }, [u, x]), p = F((b) => u === null || x === null ? !1 : b === x, [u, x]);
  return /* @__PURE__ */ s("div", { children: [
    /* @__PURE__ */ s(
      "button",
      {
        onClick: a,
        className: "flex items-center justify-between mb-3 w-full py-1 px-2 -ml-2 rounded-lg hover:bg-dc-primary/10 transition-colors group",
        title: "Add breakdown",
        children: [
          /* @__PURE__ */ e(Ot, { children: "Breakdown" }),
          /* @__PURE__ */ e(Qa, { className: "w-5 h-5 text-dc-text-secondary group-hover:text-dc-primary transition-colors" })
        ]
      }
    ),
    /* @__PURE__ */ s(
      "div",
      {
        className: "space-y-2",
        onDragLeave: o ? i : void 0,
        onDragOver: o ? (b) => b.preventDefault() : void 0,
        onDrop: o ? y : void 0,
        children: [
          k.map(({ breakdown: b, fieldMeta: w, sortDirection: v, sortPriority: M, index: $ }) => {
            const C = g($), L = p($);
            return /* @__PURE__ */ s(
              "div",
              {
                className: "relative",
                style: {
                  transform: C,
                  transition: u !== null ? "transform 0.15s ease-out" : "none"
                },
                onDragOver: o ? (I) => R(I, $) : void 0,
                onDrop: o ? y : void 0,
                children: [
                  L && /* @__PURE__ */ e("div", { className: "absolute -top-5 left-0 right-0 flex items-center justify-center pointer-events-none z-10", children: /* @__PURE__ */ e("div", { className: "h-0.5 w-full bg-dc-primary rounded-full" }) }),
                  /* @__PURE__ */ e(
                    za,
                    {
                      breakdown: b,
                      fieldMeta: w,
                      onRemove: () => c(b.id),
                      onGranularityChange: b.isTimeDimension ? (I) => l(b.id, I) : void 0,
                      sortDirection: v,
                      sortPriority: M,
                      onToggleSort: h ? () => {
                        const I = Ga(v);
                        h(b.field, I);
                      } : void 0,
                      index: $,
                      isDragging: u === $,
                      onDragStart: o ? _ : void 0,
                      onDragEnd: o ? O : void 0
                    }
                  )
                ]
              },
              b.id
            );
          }),
          o && u !== null && x === r.length && /* @__PURE__ */ e("div", { className: "relative h-2", children: /* @__PURE__ */ e("div", { className: "absolute top-0 left-0 right-0 flex items-center justify-center pointer-events-none z-10", children: /* @__PURE__ */ e("div", { className: "h-0.5 w-full bg-dc-primary rounded-full" }) }) }),
          o && r.length > 0 && u !== null && /* @__PURE__ */ e(
            "div",
            {
              className: "h-8",
              onDragOver: (b) => {
                b.preventDefault();
                const w = r.length, v = S.current;
                T.current !== w && v !== w - 1 && (f(w), T.current = w);
              },
              onDrop: y
            }
          )
        ]
      }
    )
  ] });
}), un = z("close"), Dr = z("chevronDown"), Ja = z("dimension"), Ya = z("timeDimension"), Ka = z("measure");
function Xa({
  filter: t,
  schema: r,
  onSave: n,
  onCancel: a,
  anchorElement: c
}) {
  const [l, d] = H(t), [h, o] = H(!1), [u, m] = H(!1), [x, f] = H(!1), [S, T] = H("this_month"), [D, k] = H(1), [A, _] = H(""), [O, R] = H(null), y = Te(null), i = On(A, 300), g = Br(l.member, r), p = g?.field.type || "string", b = p === "time", w = g?.fieldType === "measure", v = g?.fieldType === "dimension", M = Bn(l.member, r), $ = Zt[l.operator], C = ka(p), L = b && l.operator === "inDateRange", I = F(() => ["equals", "notEquals", "in", "notIn"].includes(l.operator) && v && !b, [l.operator, v, b])(), {
    values: E,
    loading: K,
    error: P,
    searchValues: Ne
  } = Mn(l.member, I);
  Ce(() => {
    if (!c) {
      R(null);
      return;
    }
    const U = c.getBoundingClientRect(), fe = 500, ae = U.top, Ae = window.innerHeight - U.bottom, ke = 400, Fe = ae > fe || ae > Ae, Ke = Math.max(16, Math.min(U.left, window.innerWidth - ke - 16));
    R(Fe ? {
      bottom: window.innerHeight - U.top + 8,
      left: Ke
    } : {
      top: U.bottom + 8,
      left: Ke
    });
  }, [c]), Ce(() => {
    const U = (fe) => {
      y.current && !y.current.contains(fe.target) && (o(!1), m(!1), f(!1));
    };
    return document.addEventListener("mousedown", U), () => document.removeEventListener("mousedown", U);
  }, []), Ce(() => {
    u && I && Ne && Ne("", !0);
  }, [u, I, Ne]), Ce(() => {
    u && I && Ne && i !== void 0 && Ne(i);
  }, [i, u, I, Ne]), Ce(() => {
    if (!(!L || !l.dateRange))
      if (Array.isArray(l.dateRange))
        T("custom");
      else {
        const U = l.dateRange.match(/^last (\d+) (days|weeks|months|quarters|years)$/), fe = !U && l.dateRange.match(/^last (day|week|month|quarter|year)$/);
        if (U) {
          const [, ae, Ae] = U;
          T(`last_n_${Ae}`), k(parseInt(ae) || 1);
        } else if (fe) {
          const [, ae] = fe;
          T(`last_n_${ae === "day" ? "days" : ae === "week" ? "weeks" : ae === "month" ? "months" : ae === "quarter" ? "quarters" : "years"}`), k(1);
        } else {
          let ae = !1;
          for (const Ae of bt)
            if (Ae.value !== "custom" && !lr(Ae.value) && Kt(Ae.value) === l.dateRange) {
              T(Ae.value), ae = !0;
              break;
            }
          ae || T("custom");
        }
      }
  }, [l.dateRange, L]);
  const ye = F((U) => {
    d({
      member: l.member,
      operator: U,
      values: []
    }), o(!1);
  }, [l.member]), Ue = F((U) => {
    const fe = l.values || [];
    $?.supportsMultipleValues ? fe.includes(U) || d({ ...l, values: [...fe, U] }) : (d({ ...l, values: [U] }), m(!1)), _("");
  }, [l, $?.supportsMultipleValues]), Q = F((U) => {
    const fe = (l.values || []).filter((ae) => ae !== U);
    d({ ...l, values: fe });
  }, [l]), ue = F((U) => {
    const fe = U.target.value;
    if ($?.valueType === "number") {
      const ae = parseFloat(fe);
      isNaN(ae) ? (fe === "" || fe === "-") && d({ ...l, values: [] }) : d({ ...l, values: [ae] });
    } else
      d({ ...l, values: fe ? [fe] : [] });
  }, [l, $?.valueType]), me = F((U) => {
    const fe = parseFloat(U.target.value), ae = l.values?.length >= 2 ? l.values : ["", ""], Ae = [isNaN(fe) ? "" : fe, ae[1]].filter((ke) => ke !== "");
    d({ ...l, values: Ae });
  }, [l]), J = F((U) => {
    const fe = parseFloat(U.target.value), Ae = [(l.values?.length >= 2 ? l.values : ["", ""])[0], isNaN(fe) ? "" : fe].filter((ke) => ke !== "");
    d({ ...l, values: Ae });
  }, [l]), Y = F((U) => {
    const fe = U.target.value;
    d({ ...l, values: fe ? [fe] : [] });
  }, [l]), ge = F((U) => {
    T(U), f(!1);
    let fe;
    if (U === "custom") {
      const ae = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
      fe = [ae, ae];
    } else lr(U) ? fe = Kt(U, D) : fe = Kt(U);
    d({ ...l, dateRange: fe });
  }, [l, D]), ee = F((U) => {
    if (k(U), lr(S)) {
      const fe = Kt(S, U);
      d({ ...l, dateRange: fe });
    }
  }, [l, S]), j = F((U) => {
    const fe = U.target.value, Ae = (Array.isArray(l.dateRange) ? l.dateRange : [l.dateRange || "", ""])[1] || fe;
    d({ ...l, dateRange: [fe, Ae] });
  }, [l]), re = F((U) => {
    const fe = U.target.value, Ae = (Array.isArray(l.dateRange) ? l.dateRange : ["", l.dateRange || ""])[0] || fe;
    d({ ...l, dateRange: [Ae, fe] });
  }, [l]), xe = C.find((U) => U.operator === l.operator)?.label || l.operator, $e = bt.find((U) => U.value === S)?.label || "Select range", Me = b ? Ya : w ? Ka : Ja, ze = () => $?.requiresValues ? L ? /* @__PURE__ */ s("div", { className: "space-y-2", children: [
    /* @__PURE__ */ s("div", { className: "relative", children: [
      /* @__PURE__ */ s(
        "button",
        {
          onClick: () => {
            o(!1), m(!1), f(!x);
          },
          className: "w-full flex items-center justify-between text-left text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text hover:bg-dc-surface-hover",
          children: [
            /* @__PURE__ */ e("span", { className: "truncate", children: $e }),
            /* @__PURE__ */ e(Dr, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-2 transition-transform ${x ? "rotate-180" : ""}` })
          ]
        }
      ),
      x && /* @__PURE__ */ e("div", { className: "absolute z-[60] left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded shadow-lg max-h-48 overflow-y-auto", children: bt.map((U) => /* @__PURE__ */ e(
        "button",
        {
          onClick: () => ge(U.value),
          className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover ${U.value === S ? "bg-dc-primary/10 text-dc-primary" : "text-dc-text"}`,
          children: U.label
        },
        U.value
      )) })
    ] }),
    lr(S) && /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ e(
        "input",
        {
          type: "number",
          min: "1",
          max: "1000",
          value: D,
          onChange: (U) => ee(Math.max(1, parseInt(U.target.value) || 1)),
          className: "flex-1 text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text w-20"
        }
      ),
      /* @__PURE__ */ e("span", { className: "text-sm text-dc-text-muted", children: S.replace("last_n_", "") })
    ] }),
    S === "custom" && /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ e(
        "input",
        {
          type: "date",
          value: Array.isArray(l.dateRange) ? l.dateRange[0] : "",
          onChange: j,
          className: "flex-1 text-sm border border-dc-border rounded px-2 py-2 bg-dc-surface text-dc-text"
        }
      ),
      /* @__PURE__ */ e("span", { className: "text-sm text-dc-text-muted", children: "to" }),
      /* @__PURE__ */ e(
        "input",
        {
          type: "date",
          value: Array.isArray(l.dateRange) ? l.dateRange[1] : "",
          onChange: re,
          className: "flex-1 text-sm border border-dc-border rounded px-2 py-2 bg-dc-surface text-dc-text"
        }
      )
    ] })
  ] }) : l.operator === "between" || l.operator === "notBetween" ? /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
    /* @__PURE__ */ e(
      "input",
      {
        type: "number",
        value: l.values?.[0] ?? "",
        onChange: me,
        placeholder: "Min",
        className: "flex-1 text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text"
      }
    ),
    /* @__PURE__ */ e("span", { className: "text-sm text-dc-text-muted", children: "to" }),
    /* @__PURE__ */ e(
      "input",
      {
        type: "number",
        value: l.values?.[1] ?? "",
        onChange: J,
        placeholder: "Max",
        className: "flex-1 text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text"
      }
    )
  ] }) : $?.valueType === "date" ? /* @__PURE__ */ e(
    "input",
    {
      type: "date",
      value: l.values?.[0] || "",
      onChange: Y,
      className: "w-full text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text"
    }
  ) : $?.valueType === "number" ? /* @__PURE__ */ e(
    "input",
    {
      type: "number",
      value: l.values?.[0] ?? "",
      onChange: ue,
      placeholder: "Enter number",
      className: "w-full text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text"
    }
  ) : I ? /* @__PURE__ */ s("div", { className: "space-y-2", children: [
    l.values && l.values.length > 0 && /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-1.5", children: l.values.map((U, fe) => /* @__PURE__ */ s(
      "span",
      {
        className: "inline-flex items-center gap-1 bg-dc-primary/10 text-dc-primary text-sm px-2 py-1 rounded",
        children: [
          /* @__PURE__ */ e("span", { className: "max-w-[150px] truncate", children: String(U) }),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => Q(U),
              className: "hover:text-dc-danger",
              children: /* @__PURE__ */ e(un, { className: "w-3.5 h-3.5" })
            }
          )
        ]
      },
      fe
    )) }),
    /* @__PURE__ */ s("div", { className: "relative", children: [
      /* @__PURE__ */ s(
        "button",
        {
          onClick: () => {
            o(!1), f(!1), m(!u);
          },
          className: "w-full flex items-center justify-between text-left text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text hover:bg-dc-surface-hover",
          children: [
            /* @__PURE__ */ e("span", { className: "text-dc-text-muted truncate", children: K ? "Loading..." : "Select value..." }),
            /* @__PURE__ */ e(Dr, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-2 transition-transform ${u ? "rotate-180" : ""}` })
          ]
        }
      ),
      u && /* @__PURE__ */ s("div", { className: "absolute z-[60] left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded shadow-lg max-h-56 overflow-hidden", children: [
        /* @__PURE__ */ e("div", { className: "p-2 border-b border-dc-border", children: /* @__PURE__ */ e(
          "input",
          {
            type: "text",
            value: A,
            onChange: (U) => _(U.target.value),
            placeholder: "Search...",
            className: "w-full text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text",
            autoFocus: !0
          }
        ) }),
        /* @__PURE__ */ e("div", { className: "max-h-40 overflow-y-auto", children: K ? /* @__PURE__ */ e("div", { className: "px-3 py-2 text-sm text-dc-text-muted", children: "Loading..." }) : P ? /* @__PURE__ */ s("div", { className: "px-3 py-2 text-sm text-dc-error", children: [
          "Error: ",
          P
        ] }) : E.length === 0 ? /* @__PURE__ */ e("div", { className: "px-3 py-2 text-sm text-dc-text-muted", children: "No values found" }) : E.map((U, fe) => {
          const ae = l.values?.includes(U);
          return /* @__PURE__ */ s(
            "button",
            {
              onClick: () => Ue(U),
              className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover ${ae ? "bg-dc-primary/10 text-dc-primary" : "text-dc-text"}`,
              children: [
                String(U),
                ae && /* @__PURE__ */ e("span", { className: "float-right", children: "✓" })
              ]
            },
            `${U}-${fe}`
          );
        }) })
      ] })
    ] })
  ] }) : /* @__PURE__ */ e(
    "input",
    {
      type: "text",
      value: l.values?.[0] ?? "",
      onChange: ue,
      placeholder: "Enter value...",
      className: "w-full text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text placeholder-dc-text-muted"
    }
  ) : /* @__PURE__ */ e("div", { className: "text-sm text-dc-text-muted italic py-2", children: "No value required" });
  return /* @__PURE__ */ e(Ie, { children: /* @__PURE__ */ e(
    "div",
    {
      className: `fixed inset-0 bg-dc-overlay z-50 ${O ? "" : "flex items-center justify-center p-4"}`,
      onClick: a,
      children: /* @__PURE__ */ s(
        "div",
        {
          ref: y,
          className: O ? "bg-dc-surface rounded-lg shadow-xl" : "bg-dc-surface rounded-lg shadow-xl max-w-md w-full",
          style: O ? {
            position: "fixed",
            ...O,
            maxWidth: "400px",
            width: "100%"
          } : {},
          onClick: (U) => U.stopPropagation(),
          children: [
            /* @__PURE__ */ s("div", { className: "flex items-center justify-between p-4 border-b border-dc-border", children: [
              /* @__PURE__ */ e("h2", { className: "text-lg font-semibold text-dc-text", children: "Edit Filter" }),
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: a,
                  className: "p-1 text-dc-text-muted hover:text-dc-text transition-colors",
                  children: /* @__PURE__ */ e(un, { className: "w-5 h-5" })
                }
              )
            ] }),
            /* @__PURE__ */ s("div", { className: "p-4 space-y-4", children: [
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("label", { className: "block text-sm font-medium text-dc-text-secondary mb-2", children: "Field" }),
                /* @__PURE__ */ s("div", { className: "flex items-center gap-2 p-3 bg-dc-surface-secondary rounded", children: [
                  /* @__PURE__ */ e(Me, { className: "w-5 h-5 text-dc-filter-text" }),
                  /* @__PURE__ */ e("span", { className: "text-sm font-medium text-dc-text", children: M })
                ] })
              ] }),
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("label", { className: "block text-sm font-medium text-dc-text-secondary mb-2", children: "Operator" }),
                /* @__PURE__ */ s("div", { className: "relative", children: [
                  /* @__PURE__ */ s(
                    "button",
                    {
                      onClick: () => {
                        m(!1), f(!1), o(!h);
                      },
                      className: "w-full flex items-center justify-between text-left text-sm border border-dc-border rounded px-3 py-2 bg-dc-surface text-dc-text hover:bg-dc-surface-hover",
                      children: [
                        /* @__PURE__ */ e("span", { className: "truncate", children: xe }),
                        /* @__PURE__ */ e(Dr, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-2 transition-transform ${h ? "rotate-180" : ""}` })
                      ]
                    }
                  ),
                  h && /* @__PURE__ */ e("div", { className: "absolute z-[60] left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded shadow-lg max-h-48 overflow-y-auto", children: C.map((U) => /* @__PURE__ */ e(
                    "button",
                    {
                      onClick: () => ye(U.operator),
                      className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover ${U.operator === l.operator ? "bg-dc-primary/10 text-dc-primary" : "text-dc-text"}`,
                      children: U.label
                    },
                    U.operator
                  )) })
                ] })
              ] }),
              /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e("label", { className: "block text-sm font-medium text-dc-text-secondary mb-2", children: "Value" }),
                ze()
              ] })
            ] }),
            /* @__PURE__ */ s("div", { className: "flex items-center justify-end gap-2 p-4 border-t border-dc-border", children: [
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: a,
                  className: "px-4 py-2 text-sm font-medium text-dc-text-secondary hover:text-dc-text transition-colors",
                  children: "Cancel"
                }
              ),
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: () => n(l),
                  className: "px-4 py-2 text-sm font-medium text-dc-primary-content bg-dc-primary hover:bg-dc-primary-hover rounded transition-colors",
                  children: "Save"
                }
              )
            ] })
          ]
        }
      )
    }
  ) });
}
const mn = z("close"), Za = z("dimension"), ec = z("timeDimension"), tc = z("measure");
function Kn({
  filter: t,
  schema: r,
  onRemove: n,
  onUpdate: a
}) {
  const [c, l] = H(!1), d = Te(null), h = Br(t.member, r), u = (h?.field.type || "string") === "time", m = h?.fieldType === "measure", x = Bn(t.member, r), f = Zt[t.operator], S = f?.label || t.operator, T = rc(t, f), D = u ? ec : m ? tc : Za;
  return /* @__PURE__ */ s(Ie, { children: [
    /* @__PURE__ */ s(
      "div",
      {
        className: "flex items-start gap-2 px-2 py-1.5 bg-dc-surface-secondary rounded-lg group hover:bg-dc-surface-tertiary transition-all duration-150 w-full",
        children: [
          /* @__PURE__ */ e("span", { className: `w-6 h-6 flex items-center justify-center rounded ${u ? "bg-dc-time-dimension" : m ? "bg-dc-measure" : "bg-dc-dimension"} ${u ? "text-dc-time-dimension-text" : m ? "text-dc-measure-text" : "text-dc-dimension-text"} flex-shrink-0 mt-0.5`, children: D && /* @__PURE__ */ e(D, { className: "w-4 h-4" }) }),
          /* @__PURE__ */ e(
            "button",
            {
              ref: d,
              onClick: () => l(!0),
              className: "flex-1 min-w-0 text-left",
              title: `${x} ${S} ${T}`,
              children: /* @__PURE__ */ s("div", { className: "text-sm text-dc-text break-words", children: [
                /* @__PURE__ */ e("span", { className: "font-medium", children: x }),
                /* @__PURE__ */ e("span", { className: "text-dc-text-muted mx-1", children: S }),
                /* @__PURE__ */ e("span", { className: "text-dc-primary", children: T })
              ] })
            }
          ),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: n,
              className: "p-1 text-dc-text-muted hover:text-dc-danger opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity flex-shrink-0 mt-0.5",
              title: "Remove filter",
              children: mn && /* @__PURE__ */ e(mn, { className: "w-4 h-4" })
            }
          )
        ]
      }
    ),
    c && /* @__PURE__ */ e(
      Xa,
      {
        filter: t,
        schema: r,
        onSave: (_) => {
          a(_), l(!1);
        },
        onCancel: () => l(!1),
        anchorElement: d.current
      }
    )
  ] });
}
function rc(t, r) {
  if (!r?.requiresValues)
    return "";
  if (t.dateRange)
    return Array.isArray(t.dateRange) ? `${t.dateRange[0]} to ${t.dateRange[1]}` : t.dateRange;
  const n = t.values || [];
  return n.length === 0 ? "(empty)" : n.length === 1 ? String(n[0]) : n.length === 2 ? `${n[0]}, ${n[1]}` : `${n[0]}, ${n[1]}, +${n.length - 2} more`;
}
const nc = z("add"), sc = z("close");
function ac(t) {
  return "member" in t && typeof t.member == "string";
}
function cc(t) {
  return "type" in t && (t.type === "and" || t.type === "or");
}
function Xn({
  group: t,
  schema: r,
  onUpdate: n,
  onRemove: a,
  onAddFilter: c,
  depth: l = 0,
  hideRemoveButton: d = !1
}) {
  const [h, o] = H(!1), u = Te(null);
  Ce(() => {
    const R = (y) => {
      u.current && !u.current.contains(y.target) && o(!1);
    };
    return document.addEventListener("mousedown", R), () => document.removeEventListener("mousedown", R);
  }, []);
  const m = F(() => {
    const R = t.type === "and" ? "or" : "and";
    n({ ...t, type: R });
  }, [t, n]), x = F((R, y) => {
    const i = [...t.filters];
    i[R] = y, n({ ...t, filters: i });
  }, [t, n]), f = F((R) => {
    const y = t.filters.filter((i, g) => g !== R);
    y.length === 0 ? a() : y.length === 1 && l > 0 ? n({ ...t, filters: y }) : n({ ...t, filters: y });
  }, [t, n, a, l]), S = F((R) => {
    const y = { type: R, filters: [] };
    n({ ...t, filters: [...t.filters, y] }), o(!1);
  }, [t, n]), T = F(() => {
    c([]), o(!1);
  }, [c]), D = F((R) => (y = []) => {
    c([R, ...y]);
  }, [c]), k = () => l % 2 === 0 ? "border-dc-border" : "border-dc-border dark:border-dc-border", A = () => t.type === "and" ? "bg-dc-info-bg/50" : "bg-dc-warning-bg/50", _ = t.filters.length, O = _ === 1 ? "condition" : "conditions";
  return /* @__PURE__ */ s("div", { className: `border ${k()} rounded-lg bg-dc-surface w-full`, children: [
    /* @__PURE__ */ s("div", { className: `flex items-center justify-between px-2 py-1.5 border-b border-dc-border/50 rounded-t-lg ${A()}`, children: [
      /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ e(
          "button",
          {
            onClick: m,
            className: `px-2 py-0.5 text-xs font-semibold rounded transition-colors ${t.type === "and" ? "bg-dc-info-bg text-dc-info hover:opacity-80" : "bg-dc-warning-bg text-dc-warning hover:opacity-80"}`,
            title: `Click to switch to ${t.type === "and" ? "OR" : "AND"}`,
            children: t.type.toUpperCase()
          }
        ),
        /* @__PURE__ */ s("span", { className: "text-xs text-dc-text-muted", children: [
          _,
          " ",
          O
        ] })
      ] }),
      /* @__PURE__ */ s("div", { className: "flex items-center gap-1", children: [
        /* @__PURE__ */ s("div", { className: "relative", ref: u, children: [
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => o(!h),
              className: "p-1 text-dc-text-secondary hover:text-dc-primary hover:bg-dc-surface-hover rounded transition-colors",
              title: "Add condition",
              children: /* @__PURE__ */ e(nc, { className: "w-4 h-4" })
            }
          ),
          h && /* @__PURE__ */ s("div", { className: "absolute right-0 mt-1 z-40 bg-dc-surface border border-dc-border rounded shadow-lg py-1 min-w-[120px]", children: [
            /* @__PURE__ */ e(
              "button",
              {
                onClick: T,
                className: "w-full text-left px-3 py-1.5 text-xs text-dc-text hover:bg-dc-surface-hover",
                children: "Add Filter"
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: () => S("and"),
                className: "w-full text-left px-3 py-1.5 text-xs text-dc-text hover:bg-dc-surface-hover",
                children: "Add AND Group"
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: () => S("or"),
                className: "w-full text-left px-3 py-1.5 text-xs text-dc-text hover:bg-dc-surface-hover",
                children: "Add OR Group"
              }
            )
          ] })
        ] }),
        !d && /* @__PURE__ */ e(
          "button",
          {
            onClick: a,
            className: "p-1 text-dc-text-muted hover:text-dc-danger transition-colors",
            title: "Remove group",
            children: /* @__PURE__ */ e(sc, { className: "w-4 h-4" })
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ e("div", { className: "p-1.5 flex flex-wrap gap-2", children: t.filters.length === 0 ? /* @__PURE__ */ s("div", { className: "text-center py-3", children: [
      /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted mb-1", children: "No conditions in this group" }),
      /* @__PURE__ */ e(
        "button",
        {
          onClick: () => c([]),
          className: "text-xs text-dc-primary hover:underline",
          children: "Add a filter"
        }
      )
    ] }) : t.filters.map((R, y) => ac(R) ? /* @__PURE__ */ e(
      Kn,
      {
        filter: R,
        schema: r,
        onUpdate: (i) => x(y, i),
        onRemove: () => f(y)
      },
      `filter-${y}`
    ) : cc(R) ? /* @__PURE__ */ e(
      Xn,
      {
        group: R,
        schema: r,
        onUpdate: (i) => x(y, i),
        onRemove: () => f(y),
        onAddFilter: D(y),
        depth: l + 1
      },
      `group-${y}`
    ) : null) })
  ] });
}
const lc = z("add");
function yr(t) {
  return "member" in t && typeof t.member == "string";
}
function Pt(t) {
  return "type" in t && (t.type === "and" || t.type === "or");
}
function Zn(t) {
  let r = 0;
  for (const n of t)
    yr(n) ? r++ : Pt(n) && (r += Zn(n.filters));
  return r;
}
function es(t) {
  const r = [];
  for (const n of t)
    yr(n) ? r.push(n.member) : Pt(n) && r.push(...es(n.filters));
  return r;
}
function ts(t, r, n) {
  if (r.length === 0)
    return t.length === 0 ? [n] : t.length === 1 && yr(t[0]) ? [{ type: "and", filters: [t[0], n] }] : t.length === 1 && Pt(t[0]) ? [{
      ...t[0],
      filters: [...t[0].filters, n]
    }] : [{ type: "and", filters: [...t, n] }];
  const [a, ...c] = r, l = [...t], d = l[a];
  return Pt(d) && (c.length === 0 ? l[a] = {
    ...d,
    filters: [...d.filters, n]
  } : l[a] = {
    ...d,
    filters: ts(d.filters, c, n)
  }), l;
}
function ic({
  filters: t,
  schema: r,
  onFiltersChange: n,
  onFieldDropped: a
}) {
  const [c, l] = H(!1), [d, h] = H(!1), o = Te([]), u = Zn(t), m = F((y) => {
    y.preventDefault(), y.stopPropagation(), h(!0);
  }, []), x = F((y) => {
    y.preventDefault(), y.stopPropagation(), h(!1);
  }, []), f = F((y) => {
    y.preventDefault(), y.stopPropagation(), h(!1);
    try {
      const i = JSON.parse(y.dataTransfer.getData("text/plain"));
      i.field && a && a(i.field);
    } catch {
    }
  }, [a]), S = es(t), T = F(
    (y, i, g) => {
      const p = y.type === "time", b = p ? "inDateRange" : "equals", w = {
        member: y.name,
        operator: b,
        values: []
      };
      p && b === "inDateRange" && (w.dateRange = Kt("this_month"));
      const v = ts(t, o.current, w);
      n(v), l(!1), o.current = [];
    },
    [t, n]
  ), D = F(
    (y, i) => {
      const g = [...t];
      g[y] = i, n(g);
    },
    [t, n]
  ), k = F(
    (y) => {
      const i = t.filter((g, p) => p !== y);
      if (i.length === 1 && Pt(i[0])) {
        const g = i[0];
        if (g.filters.length === 1) {
          n([g.filters[0]]);
          return;
        }
      }
      n(i);
    },
    [t, n]
  ), A = F(() => {
    n([]);
  }, [n]), _ = F(() => {
    o.current = [], l(!0);
  }, []), O = F((y) => (i = []) => {
    o.current = [...y, ...i], l(!0);
  }, []), R = (y, i, g = []) => {
    const p = [...g, i];
    return yr(y) ? /* @__PURE__ */ e(
      Kn,
      {
        filter: y,
        schema: r,
        onUpdate: (b) => D(i, b),
        onRemove: () => k(i)
      },
      `filter-${p.join("-")}`
    ) : Pt(y) ? /* @__PURE__ */ e(
      Xn,
      {
        group: y,
        schema: r,
        onUpdate: (b) => D(i, b),
        onRemove: () => k(i),
        onAddFilter: O(p),
        hideRemoveButton: t.length === 1
      },
      `group-${p.join("-")}`
    ) : null;
  };
  return /* @__PURE__ */ s("div", { children: [
    /* @__PURE__ */ s(
      "button",
      {
        onClick: _,
        className: "flex items-center justify-between mb-3 w-full py-1 px-2 -ml-2 rounded-lg hover:bg-dc-primary/10 transition-colors group",
        title: "Add filter",
        children: [
          /* @__PURE__ */ s(Ot, { children: [
            "Filter",
            u > 0 && /* @__PURE__ */ s("span", { className: "ml-1.5 text-xs font-normal text-dc-text-muted normal-case tracking-normal", children: [
              "(",
              u,
              ")"
            ] })
          ] }),
          /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
            u > 0 && /* @__PURE__ */ e(
              "span",
              {
                role: "button",
                tabIndex: 0,
                onClick: (y) => {
                  y.stopPropagation(), A();
                },
                onKeyDown: (y) => {
                  (y.key === "Enter" || y.key === " ") && (y.stopPropagation(), A());
                },
                className: "text-xs text-dc-text-muted hover:text-dc-error underline cursor-pointer",
                children: "Clear all"
              }
            ),
            /* @__PURE__ */ e(lc, { className: "w-5 h-5 text-dc-text-secondary group-hover:text-dc-primary transition-colors" })
          ] })
        ]
      }
    ),
    /* @__PURE__ */ e(
      "div",
      {
        onDragOver: a ? m : void 0,
        onDragLeave: a ? x : void 0,
        onDrop: a ? f : void 0,
        className: `p-2 -mx-2 rounded-lg border-2 border-dashed transition-all ${d ? "border-dc-primary bg-dc-primary/5" : "border-transparent"}`,
        children: t.length === 0 ? /* @__PURE__ */ e("p", { className: `text-sm ${d ? "text-dc-primary font-medium" : "text-dc-text-muted"}`, children: d ? "Drop to add filter" : "No filters applied" }) : /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-2", children: t.map((y, i) => R(y, i)) })
      }
    ),
    /* @__PURE__ */ e(
      zn,
      {
        isOpen: c,
        onClose: () => {
          l(!1), o.current = [];
        },
        onSelect: T,
        mode: "filter",
        schema: r,
        selectedFields: S
      }
    )
  ] });
}
const oc = z("close"), dc = z("dimension"), uc = z("timeDimension"), mc = z("measure");
function fc({
  config: t,
  fields: r,
  onDrop: n,
  onRemove: a,
  onDragStart: c,
  onDragEnd: l,
  onDragOver: d,
  onReorder: h,
  draggedItem: o,
  getFieldMeta: u,
  yAxisAssignment: m,
  onYAxisAssignmentChange: x
}) {
  const { key: f, label: S, description: T, mandatory: D, maxItems: k, emptyText: A } = t, [_, O] = H(null), [R, y] = H(!1), [i, g] = H(!1), p = Te(null), b = Te(null), w = Te(r);
  w.current = r;
  const v = Te(null), M = () => {
    let Q = r.length;
    return o && o.fromAxis === f && (Q = Math.max(0, r.length - 1)), !k || Q < k;
  }, $ = () => {
    let Q = r.length;
    return o && o.fromAxis === f && (Q = Math.max(0, r.length - 1)), k && Q >= k;
  }, C = M(), L = $();
  Ce(() => {
    const Q = () => {
      O(null), v.current = null, y(!1), g(!1), p.current = null;
    };
    return document.addEventListener("dragend", Q), () => {
      document.removeEventListener("dragend", Q);
    };
  }, []), Ce(() => {
    o ? o.fromAxis !== f ? (g(!1), O(null), v.current = null) : o.fromAxis === f && o.fromIndex !== void 0 && y(!1) : (O(null), v.current = null, y(!1), g(!1));
  }, [o, f]);
  const I = F((Q, ue) => {
    if (!o || o.fromAxis !== f || o.fromIndex === void 0) return;
    Q.preventDefault(), Q.stopPropagation();
    const me = Q.currentTarget.getBoundingClientRect(), Y = Q.clientY - me.top < me.height / 2, ge = o.fromIndex;
    let ee = Y ? ue : ue + 1;
    ee === ge || ee === ge + 1 ? (O(null), v.current = null) : (O(ee), v.current = ee, g(!0));
  }, [o, f]), E = F((Q) => {
    Q.preventDefault();
    const ue = v.current;
    if (!(o && o.fromAxis === f && o.fromIndex !== void 0 && ue !== null)) {
      O(null), v.current = null, g(!1);
      return;
    }
    Q.stopPropagation();
    const J = o.fromIndex, Y = ue > J ? ue - 1 : ue;
    h && Y !== J && h(J, Y, f), O(null), v.current = null, g(!1);
  }, [o, f, h]), K = F((Q, ue) => {
    const me = b.current;
    if (me && p.current === ue) {
      const J = me.getBoundingClientRect();
      Q.clientX >= J.left && Q.clientX <= J.right && Q.clientY >= J.top && Q.clientY <= J.bottom || setTimeout(() => {
        w.current.includes(ue) && a(ue, f);
      }, 0);
    }
    p.current = null, O(null), v.current = null, g(!1), l?.(Q);
  }, [f, a, l]), P = F((Q) => {
    if (!o || o.fromAxis !== f || o.fromIndex === void 0 || _ === null)
      return "";
    const ue = o.fromIndex, me = 40;
    if (Q === ue) return "";
    if (ue < _) {
      if (Q >= _)
        return `translateY(${me / 2}px)`;
    } else if (Q >= _ && Q < ue)
      return `translateY(${me / 2}px)`;
    return "";
  }, [o, f, _]), Ne = F((Q) => !o || o.fromAxis !== f || _ === null ? !1 : Q === _, [o, f, _]), ye = (Q) => {
    const ue = Q.split("."), me = ue[0] || Q, J = ue[1] || Q;
    return {
      title: J,
      shortTitle: J,
      cubeName: me,
      type: "dimension"
      // Default assumption
    };
  }, Ue = (Q) => {
    if (Q.type === "measure") {
      const ue = qt(Q.measureType || "count") || mc;
      return /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-measure text-dc-measure-text flex-shrink-0", children: /* @__PURE__ */ e(ue, { className: "w-4 h-4" }) });
    } else return Q.type === "timeDimension" ? /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-time-dimension text-dc-time-dimension-text flex-shrink-0", children: /* @__PURE__ */ e(uc, { className: "w-4 h-4" }) }) : /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-dimension text-dc-dimension-text flex-shrink-0", children: /* @__PURE__ */ e(dc, { className: "w-4 h-4" }) });
  };
  return /* @__PURE__ */ s("div", { className: "mb-3", children: [
    /* @__PURE__ */ s("div", { className: "mb-2", children: [
      /* @__PURE__ */ s("h4", { className: "text-sm font-medium text-dc-text flex items-center", children: [
        S,
        D && /* @__PURE__ */ e("span", { className: "text-dc-error ml-1", children: "*" })
      ] }),
      T && /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted mt-0.5", children: T })
    ] }),
    /* @__PURE__ */ e(
      "div",
      {
        ref: b,
        "data-axis-container": f,
        className: `min-h-[48px] border-2 border-dashed rounded-lg p-2 transition-all duration-200 ${R && (C || k === 1) || i ? "shadow-sm border-solid" : L ? "bg-dc-surface-secondary" : "bg-dc-surface-secondary hover:bg-dc-surface-hover"}`,
        style: {
          borderColor: R && (C || k === 1) || i ? "var(--dc-primary)" : "var(--dc-border)",
          backgroundColor: R && (C || k === 1) || i ? "rgba(var(--dc-primary-rgb), 0.1)" : void 0
        },
        onDragOver: (Q) => {
          if (o && o.fromAxis === f && o.fromIndex !== void 0)
            return;
          C || k === 1 ? (y(!0), d(Q)) : (Q.preventDefault(), Q.dataTransfer.dropEffect = "none");
        },
        onDragLeave: (Q) => {
          const ue = Q.currentTarget.getBoundingClientRect(), me = Q.clientX < ue.left || Q.clientX > ue.right || Q.clientY < ue.top || Q.clientY > ue.bottom, J = Q.relatedTarget, Y = J && !Q.currentTarget.contains(J);
          (me || Y || Q.currentTarget === Q.target) && (y(!1), g(!1));
        },
        onDrop: (Q) => {
          if (o && o.fromAxis === f && o.fromIndex !== void 0)
            return;
          C || k === 1 ? n(Q, f) : Q.preventDefault(), y(!1), g(!1);
        },
        children: r.length === 0 ? /* @__PURE__ */ e("div", { className: "text-sm text-dc-text-muted text-center py-2", children: L ? "Maximum items reached" : A || "Drop fields here" }) : /* @__PURE__ */ s(
          "div",
          {
            className: "space-y-2",
            onDragOver: (Q) => {
              o && o.fromAxis === f && Q.preventDefault();
            },
            onDrop: (Q) => {
              o && o.fromAxis === f && o.fromIndex !== void 0 && E(Q);
            },
            children: [
              r.map((Q, ue) => {
                const me = u ? u(Q) : ye(Q), J = o && o.field === Q && o.fromAxis === f, Y = P(ue), ge = Ne(ue);
                return /* @__PURE__ */ s(
                  "div",
                  {
                    className: "relative",
                    style: {
                      transform: Y,
                      transition: o && o.fromAxis === f ? "transform 0.15s ease-out" : "none"
                    },
                    children: [
                      ge && /* @__PURE__ */ e("div", { className: "absolute -top-5 left-0 right-0 flex items-center justify-center pointer-events-none z-10", children: /* @__PURE__ */ e("div", { className: "h-0.5 w-full bg-dc-primary rounded-full" }) }),
                      /* @__PURE__ */ s(
                        "div",
                        {
                          draggable: !0,
                          onDragStart: (ee) => {
                            p.current = Q, c(ee, Q, f, ue);
                          },
                          onDragEnd: (ee) => K(ee, Q),
                          onDragOver: (ee) => I(ee, ue),
                          onDrop: E,
                          className: `flex items-center gap-2 p-2 bg-dc-surface rounded-lg group hover:bg-dc-surface-tertiary transition-colors cursor-move ${J ? "opacity-30 cursor-grabbing" : ""}`,
                          children: [
                            Ue(me),
                            /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                              /* @__PURE__ */ e("div", { className: "text-sm text-dc-text truncate", title: Q, children: me.shortTitle || me.title || Q.split(".").pop() }),
                              /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: me.cubeName })
                            ] }),
                            t.enableDualAxis && x && /* @__PURE__ */ e(
                              "button",
                              {
                                type: "button",
                                onClick: (ee) => {
                                  ee.stopPropagation();
                                  const j = m?.[Q] || "left";
                                  x(Q, j === "left" ? "right" : "left");
                                },
                                className: `px-1.5 py-0.5 text-xs font-medium rounded transition-colors flex-shrink-0 ${(m?.[Q] || "left") === "left" ? "bg-dc-info-bg text-dc-info hover:opacity-80" : "bg-dc-accent-bg text-dc-accent hover:opacity-80"}`,
                                title: `Y-Axis: ${(m?.[Q] || "left") === "left" ? "Left" : "Right"} (click to toggle)`,
                                children: (m?.[Q] || "left") === "left" ? "L" : "R"
                              }
                            ),
                            /* @__PURE__ */ e(
                              "button",
                              {
                                type: "button",
                                onClick: () => a(Q, f),
                                className: "p-1 text-dc-text-muted hover:text-dc-danger opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0",
                                title: `Remove from ${S}`,
                                children: /* @__PURE__ */ e(oc, { className: "w-4 h-4" })
                              }
                            )
                          ]
                        }
                      )
                    ]
                  },
                  `${Q}-${ue}`
                );
              }),
              o && o.fromAxis === f && _ === r.length && /* @__PURE__ */ e("div", { className: "relative h-2", children: /* @__PURE__ */ e("div", { className: "absolute top-0 left-0 right-0 flex items-center justify-center pointer-events-none z-10", children: /* @__PURE__ */ e("div", { className: "h-0.5 w-full bg-dc-primary rounded-full" }) }) }),
              o && o.fromAxis === f && r.length > 1 && /* @__PURE__ */ e(
                "div",
                {
                  className: "h-6",
                  onDragOver: (Q) => {
                    if (o.fromIndex !== void 0) {
                      Q.preventDefault();
                      const ue = r.length;
                      v.current !== ue && o.fromIndex !== ue - 1 && (O(ue), v.current = ue, g(!0));
                    }
                  },
                  onDrop: E
                }
              )
            ]
          }
        )
      }
    ),
    D && r.length === 0 && /* @__PURE__ */ e("div", { className: "text-xs text-dc-error mt-1", children: "This field is required" })
  ] });
}
const Bt = {
  bar: Ls,
  line: Fs,
  area: $s,
  pie: Is,
  scatter: Ms,
  bubble: Os,
  radar: Rs,
  radialBar: Es,
  treemap: _s,
  table: As,
  activityGrid: Ss,
  kpiNumber: Ts,
  kpiDelta: Ds,
  kpiText: Cs,
  markdown: ks
}, ir = {
  activityGrid: "Activity Grid",
  area: "Area Chart",
  bar: "Bar Chart",
  bubble: "Bubble Chart",
  kpiDelta: "KPI Delta",
  kpiNumber: "KPI Number",
  kpiText: "KPI Text",
  line: "Line Chart",
  markdown: "Markdown",
  pie: "Pie Chart",
  radar: "Radar Chart",
  radialBar: "Radial Bar Chart",
  scatter: "Scatter Plot",
  table: "Data Table",
  treemap: "TreeMap"
};
function rs({
  selectedType: t,
  onTypeChange: r,
  className: n = "",
  compact: a = !1,
  availability: c
}) {
  const [l, d] = H(!1), h = Object.entries(Bt).sort((x, f) => {
    const S = ir[x[0]] || x[0], T = ir[f[0]] || f[0];
    return S.localeCompare(T);
  }), u = Bt[t]?.icon, m = ir[t];
  return /* @__PURE__ */ s("div", { className: `${n} relative`, children: [
    /* @__PURE__ */ s(
      "button",
      {
        type: "button",
        onClick: () => d(!l),
        className: "w-full flex items-center justify-between px-3 py-2 border border-dc-border rounded-md bg-dc-surface hover:bg-dc-surface-hover focus:outline-hidden focus:ring-2 focus:ring-dc-accent focus:border-dc-accent",
        children: [
          /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
            u && /* @__PURE__ */ e(u, { className: "h-5 w-5 text-dc-text-secondary" }),
            /* @__PURE__ */ e("span", { className: "text-sm font-medium text-dc-text", children: m })
          ] }),
          /* @__PURE__ */ e(
            "svg",
            {
              className: `h-4 w-4 text-dc-text-muted transform transition-transform ${l ? "rotate-180" : ""}`,
              fill: "none",
              viewBox: "0 0 24 24",
              stroke: "currentColor",
              children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M19 9l-7 7-7-7" })
            }
          )
        ]
      }
    ),
    l && /* @__PURE__ */ e("div", { className: `absolute z-10 mt-1 w-full bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-80 overflow-auto ${a ? "" : "min-w-max"}`, children: /* @__PURE__ */ e("div", { className: "p-2", children: /* @__PURE__ */ e("div", { className: `grid gap-1.5 ${a ? "grid-cols-2" : "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4"}`, children: h.map(([x, f]) => {
      const S = f.icon, T = ir[x], D = t === x, k = f.description, A = f.useCase, _ = c?.[x], O = _?.available ?? !0, R = _?.reason, y = !O && R ? R : [k, A].filter(Boolean).join(". ");
      return /* @__PURE__ */ s(
        "button",
        {
          type: "button",
          onClick: () => {
            O && (r(x), d(!1));
          },
          disabled: !O,
          className: `
                      relative p-1.5 rounded border transition-colors duration-150
                      text-left group min-h-[30px] flex items-center justify-start
                      ${O ? D ? "bg-dc-surface-secondary" : "bg-dc-surface hover:bg-dc-surface-hover" : "opacity-50 cursor-not-allowed bg-dc-surface"}
                    `,
          style: {
            borderColor: D && O ? "var(--dc-primary)" : "var(--dc-border)"
          },
          title: y,
          children: [
            /* @__PURE__ */ s("div", { className: "flex items-center space-x-1.5", children: [
              S && /* @__PURE__ */ e(
                S,
                {
                  className: `h-4 w-4 shrink-0 ${O ? D ? "text-dc-text" : "text-dc-text-secondary" : "text-dc-text-muted"}`
                }
              ),
              /* @__PURE__ */ e(
                "span",
                {
                  className: `text-xs font-medium leading-tight truncate ${O ? D ? "" : "text-dc-text" : "text-dc-text-muted"}`,
                  style: D && O ? { color: "var(--dc-primary)" } : void 0,
                  children: T
                }
              )
            ] }),
            D && O && /* @__PURE__ */ e("div", { className: "absolute top-0.5 right-0.5", children: /* @__PURE__ */ e("div", { className: "w-1.5 h-1.5 rounded-full", style: { backgroundColor: "var(--dc-primary)" } }) })
          ]
        },
        x
      );
    }) }) }) })
  ] });
}
const hc = z("measure"), pc = z("dimension"), xc = z("timeDimension");
function bc({
  chartType: t,
  chartConfig: r,
  metrics: n,
  breakdowns: a,
  schema: c,
  chartAvailability: l,
  onChartTypeChange: d,
  onChartConfigChange: h
}) {
  const [o, u] = H(null), m = Oe(
    () => ({
      measures: n.map((v) => v.field),
      dimensions: a.filter((v) => !v.isTimeDimension).map((v) => v.field),
      timeDimensions: a.filter((v) => v.isTimeDimension).map((v) => v.field)
    }),
    [n, a]
  ), x = Oe(
    () => br(t, Bt),
    [t]
  ), f = x.skipQuery === !0, S = (v) => {
    const M = r[v];
    return Array.isArray(M) ? M : typeof M == "string" ? [M] : [];
  };
  Ce(() => {
    const v = [
      ...m.dimensions,
      ...m.timeDimensions,
      ...m.measures
    ];
    let M = !1;
    const $ = { ...r };
    x.dropZones.forEach((C) => {
      const L = S(C.key), I = L.filter((E) => v.includes(E));
      I.length !== L.length && (M = !0, I.length === 0 ? delete $[C.key] : C.maxItems === 1 ? $[C.key] = I[0] : $[C.key] = I);
    }), M && h($);
  }, [m, r, x.dropZones, h]);
  const T = (v) => m.measures.includes(v) ? "measure" : m.timeDimensions.includes(v) ? "timeDimension" : "dimension", D = (v) => {
    if (!c?.cubes) return null;
    const [M] = v.split("."), $ = c.cubes.find((I) => I.name === M);
    if (!$) return null;
    const C = $.measures?.find((I) => I.name === v);
    if (C) return { ...C, fieldType: "measure" };
    const L = $.dimensions?.find((I) => I.name === v);
    return L ? { ...L, fieldType: L.type === "time" ? "timeDimension" : "dimension" } : null;
  }, k = (v) => {
    const M = T(v), $ = v.split("."), C = $[0] || v, L = $[1] || v, I = D(v), E = a.find((K) => K.field === v);
    return I ? {
      title: I.title || L,
      shortTitle: I.shortTitle || I.title || L,
      cubeName: C,
      type: I.fieldType,
      measureType: I.fieldType === "measure" ? I.type : void 0
    } : E ? {
      title: L,
      shortTitle: L,
      cubeName: C,
      type: E.isTimeDimension ? "timeDimension" : "dimension"
    } : {
      title: L,
      shortTitle: L,
      cubeName: C,
      type: M
    };
  }, A = (v, M, $, C) => {
    v.dataTransfer.setData("text/plain", JSON.stringify({ field: M, fromAxis: $, fromIndex: C })), u({ field: M, fromAxis: $, fromIndex: C });
  }, _ = (v) => {
    v.preventDefault();
  }, O = () => {
    u(null);
  }, R = (v, M) => {
    v.preventDefault();
    const $ = JSON.parse(v.dataTransfer.getData("text/plain")), { field: C, fromAxis: L } = $, I = { ...r };
    if (L !== "available" && L !== M) {
      const P = I[L];
      if (Array.isArray(P)) {
        const Ne = P.filter((ye) => ye !== C);
        Ne.length === 0 ? delete I[L] : I[L] = Ne;
      } else P === C && delete I[L];
    }
    const E = I[M], K = x.dropZones.find((P) => P.key === M);
    if (K?.maxItems === 1 ? I[M] = C : Array.isArray(E) ? E.includes(C) || (I[M] = [...E, C]) : I[M] = [C], M === "yAxis" && K?.enableDualAxis) {
      const Ne = (Array.isArray(I.yAxis) ? I.yAxis : [C]).indexOf(C);
      I.yAxisAssignment?.[C] || (I.yAxisAssignment = {
        ...I.yAxisAssignment,
        [C]: Ne === 1 ? "right" : "left"
      });
    }
    u(null), h(I);
  }, y = (v, M) => {
    const $ = { ...r }, C = $[M];
    if (Array.isArray(C)) {
      const L = C.filter((I) => I !== v);
      L.length === 0 ? delete $[M] : $[M] = L;
    } else C === v && delete $[M];
    if (M === "yAxis" && $.yAxisAssignment?.[v]) {
      const { [v]: L, ...I } = $.yAxisAssignment;
      $.yAxisAssignment = Object.keys(I).length > 0 ? I : void 0;
    }
    h($);
  }, i = (v, M, $) => {
    const C = { ...r }, L = C[$];
    if (Array.isArray(L) && L.length > 1 && v !== M) {
      const I = [...L], [E] = I.splice(v, 1);
      I.splice(M, 0, E), C[$] = I, u(null), h(C);
    }
  }, g = F(
    (v, M) => {
      h({
        ...r,
        yAxisAssignment: {
          ...r.yAxisAssignment,
          [v]: M
        }
      });
    },
    [r, h]
  ), b = (() => {
    const v = /* @__PURE__ */ new Set();
    return x.dropZones.forEach((M) => {
      S(M.key).forEach(($) => v.add($));
    }), o && o.fromAxis !== "available" && v.add(o.field), {
      dimensions: m.dimensions.filter((M) => !v.has(M)),
      timeDimensions: m.timeDimensions.filter((M) => !v.has(M)),
      measures: m.measures.filter((M) => !v.has(M))
    };
  })(), w = b.dimensions.length > 0 || b.timeDimensions.length > 0 || b.measures.length > 0;
  return /* @__PURE__ */ s("div", { className: "space-y-6", children: [
    /* @__PURE__ */ s("div", { children: [
      /* @__PURE__ */ e(Ot, { className: "mb-2", children: "Chart Type" }),
      /* @__PURE__ */ e(
        rs,
        {
          selectedType: t,
          onTypeChange: d,
          availability: l,
          compact: !0
        }
      )
    ] }),
    !f && x.dropZones.length > 0 && /* @__PURE__ */ s("div", { children: [
      /* @__PURE__ */ e(Ot, { className: "mb-2", children: "Chart Configuration" }),
      /* @__PURE__ */ e("div", { className: "space-y-1", children: x.dropZones.map((v) => /* @__PURE__ */ e(
        fc,
        {
          config: v,
          fields: S(v.key),
          onDrop: R,
          onRemove: y,
          onDragStart: A,
          onDragEnd: O,
          onDragOver: _,
          onReorder: i,
          draggedItem: o,
          getFieldMeta: k,
          yAxisAssignment: r.yAxisAssignment,
          onYAxisAssignmentChange: v.enableDualAxis ? g : void 0
        },
        v.key
      )) })
    ] }),
    !f && w && /* @__PURE__ */ s("div", { children: [
      /* @__PURE__ */ s("div", { className: "mb-2", children: [
        /* @__PURE__ */ e(Ot, { children: "Unassigned Fields" }),
        /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted mt-0.5", children: "Drag fields to chart axes above" })
      ] }),
      /* @__PURE__ */ e("div", { className: "border-2 border-dashed border-dc-border rounded-lg p-2 bg-dc-surface-secondary", children: /* @__PURE__ */ s("div", { className: "space-y-2", children: [
        b.measures.map((v) => {
          const M = k(v), $ = o && o.field === v && o.fromAxis === "available", C = qt(M.measureType || "count") || hc;
          return /* @__PURE__ */ s(
            "div",
            {
              draggable: !0,
              onDragStart: (L) => A(L, v, "available"),
              onDragEnd: O,
              className: `flex items-center gap-2 p-2 bg-dc-surface rounded-lg hover:bg-dc-surface-tertiary transition-colors cursor-move ${$ ? "opacity-50 cursor-grabbing" : ""}`,
              title: v,
              children: [
                /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-measure text-dc-measure-text flex-shrink-0", children: /* @__PURE__ */ e(C, { className: "w-4 h-4" }) }),
                /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                  /* @__PURE__ */ e("div", { className: "text-sm text-dc-text truncate", children: M.shortTitle }),
                  /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: M.cubeName })
                ] })
              ]
            },
            v
          );
        }),
        b.dimensions.map((v) => {
          const M = k(v), $ = o && o.field === v && o.fromAxis === "available";
          return /* @__PURE__ */ s(
            "div",
            {
              draggable: !0,
              onDragStart: (C) => A(C, v, "available"),
              onDragEnd: O,
              className: `flex items-center gap-2 p-2 bg-dc-surface rounded-lg hover:bg-dc-surface-tertiary transition-colors cursor-move ${$ ? "opacity-50 cursor-grabbing" : ""}`,
              title: v,
              children: [
                /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-dimension text-dc-dimension-text flex-shrink-0", children: /* @__PURE__ */ e(pc, { className: "w-4 h-4" }) }),
                /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                  /* @__PURE__ */ e("div", { className: "text-sm text-dc-text truncate", children: M.shortTitle }),
                  /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: M.cubeName })
                ] })
              ]
            },
            v
          );
        }),
        b.timeDimensions.map((v) => {
          const M = k(v), $ = o && o.field === v && o.fromAxis === "available";
          return /* @__PURE__ */ s(
            "div",
            {
              draggable: !0,
              onDragStart: (C) => A(C, v, "available"),
              onDragEnd: O,
              className: `flex items-center gap-2 p-2 bg-dc-surface rounded-lg hover:bg-dc-surface-tertiary transition-colors cursor-move ${$ ? "opacity-50 cursor-grabbing" : ""}`,
              title: v,
              children: [
                /* @__PURE__ */ e("span", { className: "w-6 h-6 flex items-center justify-center rounded bg-dc-time-dimension text-dc-time-dimension-text flex-shrink-0", children: /* @__PURE__ */ e(xc, { className: "w-4 h-4" }) }),
                /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                  /* @__PURE__ */ e("div", { className: "text-sm text-dc-text truncate", children: M.shortTitle }),
                  /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: M.cubeName })
                ] })
              ]
            },
            v
          );
        })
      ] }) })
    ] }),
    !f && m.measures.length === 0 && m.dimensions.length === 0 && m.timeDimensions.length === 0 && /* @__PURE__ */ e("div", { className: "text-center text-dc-text-muted text-sm py-4", children: /* @__PURE__ */ e("p", { children: "Add metrics and breakdowns in the Query tab to configure your chart." }) })
  ] });
}
function gc({
  chartType: t,
  displayConfig: r,
  colorPalette: n,
  onDisplayConfigChange: a
}) {
  const c = Oe(
    () => br(t, Bt),
    [t]
  );
  return c.displayOptions && c.displayOptions.length > 0 || c.displayOptionsConfig && c.displayOptionsConfig.length > 0 ? /* @__PURE__ */ e("div", { className: "space-y-6", children: /* @__PURE__ */ s("div", { children: [
    /* @__PURE__ */ e(Ot, { className: "mb-2", children: "Display Options" }),
    /* @__PURE__ */ s("div", { className: "space-y-2", children: [
      c.displayOptions?.includes("showLegend") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ e(
          "input",
          {
            type: "checkbox",
            checked: r.showLegend ?? !0,
            onChange: (d) => a({
              ...r,
              showLegend: d.target.checked
            }),
            className: "rounded border-dc-border focus:ring-dc-accent",
            style: { color: "var(--dc-primary)" }
          }
        ),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Show Legend" })
      ] }),
      c.displayOptions?.includes("showGrid") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ e(
          "input",
          {
            type: "checkbox",
            checked: r.showGrid ?? !0,
            onChange: (d) => a({
              ...r,
              showGrid: d.target.checked
            }),
            className: "rounded border-dc-border focus:ring-dc-accent",
            style: { color: "var(--dc-primary)" }
          }
        ),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Show Grid" })
      ] }),
      c.displayOptions?.includes("showTooltip") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ e(
          "input",
          {
            type: "checkbox",
            checked: r.showTooltip ?? !0,
            onChange: (d) => a({
              ...r,
              showTooltip: d.target.checked
            }),
            className: "rounded border-dc-border focus:ring-dc-accent",
            style: { color: "var(--dc-primary)" }
          }
        ),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Show Tooltip" })
      ] }),
      c.displayOptions?.includes("stacked") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ e(
          "input",
          {
            type: "checkbox",
            checked: r.stacked ?? !1,
            onChange: (d) => a({
              ...r,
              stacked: d.target.checked
            }),
            className: "rounded border-dc-border focus:ring-dc-accent",
            style: { color: "var(--dc-primary)" }
          }
        ),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Stacked" })
      ] }),
      c.displayOptions?.includes("hideHeader") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ e(
          "input",
          {
            type: "checkbox",
            checked: r.hideHeader ?? !1,
            onChange: (d) => a({
              ...r,
              hideHeader: d.target.checked
            }),
            className: "rounded border-dc-border focus:ring-dc-accent",
            style: { color: "var(--dc-primary)" }
          }
        ),
        /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Hide Header" })
      ] }),
      c.displayOptionsConfig?.map((d) => /* @__PURE__ */ s("div", { className: `space-y-1 ${d.type === "axisFormat" ? "mt-6 pt-2" : ""}`, children: [
        d.type === "boolean" && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "checkbox",
              checked: r[d.key] ?? d.defaultValue ?? !1,
              onChange: (h) => a({
                ...r,
                [d.key]: h.target.checked
              }),
              className: "rounded border-dc-border focus:ring-dc-accent",
              style: { color: "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: d.label })
        ] }),
        d.type === "string" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
          /* @__PURE__ */ s("label", { className: "text-sm text-dc-text-secondary", children: [
            d.label,
            d.key === "content" && /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted ml-1", children: "(only headers, lists and links)" })
          ] }),
          d.key === "content" ? /* @__PURE__ */ e(
            "textarea",
            {
              value: r[d.key] ?? d.defaultValue ?? "",
              onChange: (h) => a({
                ...r,
                [d.key]: h.target.value
              }),
              placeholder: d.placeholder,
              rows: 8,
              className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent font-mono resize-y bg-dc-surface text-dc-text"
            }
          ) : /* @__PURE__ */ e(
            "input",
            {
              type: "text",
              value: r[d.key] ?? d.defaultValue ?? "",
              onChange: (h) => a({
                ...r,
                [d.key]: h.target.value
              }),
              placeholder: d.placeholder,
              className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text"
            }
          ),
          d.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: d.description })
        ] }),
        d.type === "paletteColor" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
          /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: d.label }),
          /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-2", children: n?.colors.map((h, o) => {
            const u = (r[d.key] ?? d.defaultValue ?? 0) === o;
            return /* @__PURE__ */ e(
              "button",
              {
                type: "button",
                onClick: () => a({
                  ...r,
                  [d.key]: o
                }),
                className: `w-8 h-8 rounded border-2 transition-all duration-200 hover:scale-110 focus:outline-hidden focus:ring-2 focus:ring-dc-accent focus:ring-offset-1 ${u ? "ring-2 ring-offset-1 scale-110" : "hover:border-dc-text-muted"}`,
                style: {
                  backgroundColor: h,
                  borderColor: u ? "var(--dc-primary)" : "var(--dc-border)"
                },
                title: `Color ${o + 1}: ${h}`
              },
              o
            );
          }) || [
            // Fallback if no palette available
            /* @__PURE__ */ e(
              "button",
              {
                type: "button",
                onClick: () => a({
                  ...r,
                  [d.key]: 0
                }),
                className: "w-8 h-8 rounded-sm border-2 ring-2 ring-offset-1",
                style: {
                  backgroundColor: "#8884d8",
                  borderColor: "var(--dc-primary)",
                  boxShadow: "0 0 0 2px var(--dc-primary)"
                },
                title: "Default Color"
              },
              0
            )
          ] }),
          d.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: d.description })
        ] }),
        d.type === "number" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
          /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: d.label }),
          /* @__PURE__ */ e(
            "input",
            {
              type: "number",
              value: r[d.key] ?? d.defaultValue ?? 0,
              onChange: (h) => a({
                ...r,
                [d.key]: h.target.value === "" ? void 0 : Number(h.target.value)
              }),
              placeholder: d.placeholder,
              min: d.min,
              max: d.max,
              step: d.step,
              className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text"
            }
          ),
          d.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: d.description })
        ] }),
        d.type === "select" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
          /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: d.label }),
          /* @__PURE__ */ e(
            "select",
            {
              value: r[d.key] ?? d.defaultValue ?? "",
              onChange: (h) => a({
                ...r,
                [d.key]: h.target.value
              }),
              className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text",
              children: d.options?.map((h) => /* @__PURE__ */ e("option", { value: h.value, children: h.label }, h.value))
            }
          ),
          d.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: d.description })
        ] }),
        d.type === "color" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
          /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: d.label }),
          /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
            /* @__PURE__ */ e(
              "input",
              {
                type: "color",
                value: r[d.key] ?? d.defaultValue ?? "#8884d8",
                onChange: (h) => a({
                  ...r,
                  [d.key]: h.target.value
                }),
                className: "w-12 h-8 border border-dc-border rounded-sm cursor-pointer"
              }
            ),
            /* @__PURE__ */ e(
              "input",
              {
                type: "text",
                value: r[d.key] ?? d.defaultValue ?? "#8884d8",
                onChange: (h) => a({
                  ...r,
                  [d.key]: h.target.value
                }),
                placeholder: d.placeholder || "#8884d8",
                className: "flex-1 px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text"
              }
            )
          ] }),
          d.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: d.description })
        ] }),
        d.type === "axisFormat" && /* @__PURE__ */ e(
          js,
          {
            axisLabel: d.label,
            value: r[d.key] || {},
            onChange: (h) => a({
              ...r,
              [d.key]: Object.keys(h).length > 0 ? h : void 0
            })
          }
        )
      ] }, d.key))
    ] })
  ] }) }) : /* @__PURE__ */ e("div", { className: "text-center text-dc-text-muted text-sm py-4", children: /* @__PURE__ */ e("p", { children: "No display options available for this chart type." }) });
}
const yc = gt(function({
  metrics: r,
  breakdowns: n,
  filters: a,
  schema: c,
  activeTab: l,
  onActiveTabChange: d,
  onAddMetric: h,
  onRemoveMetric: o,
  onReorderMetrics: u,
  onAddBreakdown: m,
  onRemoveBreakdown: x,
  onBreakdownGranularityChange: f,
  onReorderBreakdowns: S,
  onFiltersChange: T,
  onDropFieldToFilter: D,
  // Sorting
  order: k,
  onOrderChange: A,
  // Chart configuration
  chartType: _,
  chartConfig: O,
  displayConfig: R,
  colorPalette: y,
  chartAvailability: i,
  onChartTypeChange: g,
  onChartConfigChange: p,
  onDisplayConfigChange: b
}) {
  return Ce(() => {
    r.length === 0 && (l === "chart" || l === "display") && d("query");
  }, [r.length, l, d]), /* @__PURE__ */ s("div", { className: "h-full flex flex-col bg-dc-surface", children: [
    /* @__PURE__ */ s("div", { className: "flex border-b border-dc-border flex-shrink-0", children: [
      /* @__PURE__ */ e(
        "button",
        {
          onClick: () => d("query"),
          className: `flex-1 px-4 py-3 text-sm font-medium transition-colors ${l === "query" ? "text-dc-primary border-b-2 border-dc-primary" : "text-dc-text-secondary hover:text-dc-text"}`,
          children: "Query"
        }
      ),
      /* @__PURE__ */ e(
        "button",
        {
          onClick: () => r.length > 0 && d("chart"),
          disabled: r.length === 0,
          className: `flex-1 px-4 py-3 text-sm font-medium transition-colors ${l === "chart" ? "text-dc-primary border-b-2 border-dc-primary" : r.length === 0 ? "text-dc-text-muted cursor-not-allowed opacity-50" : "text-dc-text-secondary hover:text-dc-text"}`,
          title: r.length === 0 ? "Add metrics to configure chart" : "Chart configuration",
          children: "Chart"
        }
      ),
      /* @__PURE__ */ e(
        "button",
        {
          onClick: () => r.length > 0 && d("display"),
          disabled: r.length === 0,
          className: `flex-1 px-4 py-3 text-sm font-medium transition-colors ${l === "display" ? "text-dc-primary border-b-2 border-dc-primary" : r.length === 0 ? "text-dc-text-muted cursor-not-allowed opacity-50" : "text-dc-text-secondary hover:text-dc-text"}`,
          title: r.length === 0 ? "Add metrics to configure display" : "Display options",
          children: "Display"
        }
      )
    ] }),
    /* @__PURE__ */ e("div", { className: "flex-1 overflow-auto p-4", children: l === "query" ? /* @__PURE__ */ s("div", { className: "space-y-6", children: [
      /* @__PURE__ */ e(
        Va,
        {
          metrics: r,
          schema: c,
          onAdd: h,
          onRemove: o,
          order: k,
          onOrderChange: A,
          onReorder: u
        }
      ),
      /* @__PURE__ */ e(
        Wa,
        {
          breakdowns: n,
          schema: c,
          onAdd: m,
          onRemove: x,
          onGranularityChange: f,
          order: k,
          onOrderChange: A,
          onReorder: S
        }
      ),
      /* @__PURE__ */ e(
        ic,
        {
          filters: a,
          schema: c,
          onFiltersChange: T,
          onFieldDropped: D
        }
      )
    ] }) : l === "chart" ? (
      /* Chart Tab Content */
      /* @__PURE__ */ e(
        bc,
        {
          chartType: _,
          chartConfig: O,
          metrics: r,
          breakdowns: n,
          schema: c,
          chartAvailability: i,
          onChartTypeChange: g,
          onChartConfigChange: p
        }
      )
    ) : l === "display" ? (
      /* Display Tab Content */
      /* @__PURE__ */ e(
        gc,
        {
          chartType: _,
          displayConfig: R,
          colorPalette: y,
          onDisplayConfigChange: b
        }
      )
    ) : null })
  ] });
});
var Tr = { exports: {} }, fn;
function vc() {
  return fn || (fn = 1, (function(t) {
    var r = (function() {
      var n = String.fromCharCode, a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$", l = {};
      function d(o, u) {
        if (!l[o]) {
          l[o] = {};
          for (var m = 0; m < o.length; m++)
            l[o][o.charAt(m)] = m;
        }
        return l[o][u];
      }
      var h = {
        compressToBase64: function(o) {
          if (o == null) return "";
          var u = h._compress(o, 6, function(m) {
            return a.charAt(m);
          });
          switch (u.length % 4) {
            // To produce valid Base64
            default:
            // When could this happen ?
            case 0:
              return u;
            case 1:
              return u + "===";
            case 2:
              return u + "==";
            case 3:
              return u + "=";
          }
        },
        decompressFromBase64: function(o) {
          return o == null ? "" : o == "" ? null : h._decompress(o.length, 32, function(u) {
            return d(a, o.charAt(u));
          });
        },
        compressToUTF16: function(o) {
          return o == null ? "" : h._compress(o, 15, function(u) {
            return n(u + 32);
          }) + " ";
        },
        decompressFromUTF16: function(o) {
          return o == null ? "" : o == "" ? null : h._decompress(o.length, 16384, function(u) {
            return o.charCodeAt(u) - 32;
          });
        },
        //compress into uint8array (UCS-2 big endian format)
        compressToUint8Array: function(o) {
          for (var u = h.compress(o), m = new Uint8Array(u.length * 2), x = 0, f = u.length; x < f; x++) {
            var S = u.charCodeAt(x);
            m[x * 2] = S >>> 8, m[x * 2 + 1] = S % 256;
          }
          return m;
        },
        //decompress from uint8array (UCS-2 big endian format)
        decompressFromUint8Array: function(o) {
          if (o == null)
            return h.decompress(o);
          for (var u = new Array(o.length / 2), m = 0, x = u.length; m < x; m++)
            u[m] = o[m * 2] * 256 + o[m * 2 + 1];
          var f = [];
          return u.forEach(function(S) {
            f.push(n(S));
          }), h.decompress(f.join(""));
        },
        //compress into a string that is already URI encoded
        compressToEncodedURIComponent: function(o) {
          return o == null ? "" : h._compress(o, 6, function(u) {
            return c.charAt(u);
          });
        },
        //decompress from an output of compressToEncodedURIComponent
        decompressFromEncodedURIComponent: function(o) {
          return o == null ? "" : o == "" ? null : (o = o.replace(/ /g, "+"), h._decompress(o.length, 32, function(u) {
            return d(c, o.charAt(u));
          }));
        },
        compress: function(o) {
          return h._compress(o, 16, function(u) {
            return n(u);
          });
        },
        _compress: function(o, u, m) {
          if (o == null) return "";
          var x, f, S = {}, T = {}, D = "", k = "", A = "", _ = 2, O = 3, R = 2, y = [], i = 0, g = 0, p;
          for (p = 0; p < o.length; p += 1)
            if (D = o.charAt(p), Object.prototype.hasOwnProperty.call(S, D) || (S[D] = O++, T[D] = !0), k = A + D, Object.prototype.hasOwnProperty.call(S, k))
              A = k;
            else {
              if (Object.prototype.hasOwnProperty.call(T, A)) {
                if (A.charCodeAt(0) < 256) {
                  for (x = 0; x < R; x++)
                    i = i << 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++;
                  for (f = A.charCodeAt(0), x = 0; x < 8; x++)
                    i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
                } else {
                  for (f = 1, x = 0; x < R; x++)
                    i = i << 1 | f, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = 0;
                  for (f = A.charCodeAt(0), x = 0; x < 16; x++)
                    i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
                }
                _--, _ == 0 && (_ = Math.pow(2, R), R++), delete T[A];
              } else
                for (f = S[A], x = 0; x < R; x++)
                  i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
              _--, _ == 0 && (_ = Math.pow(2, R), R++), S[k] = O++, A = String(D);
            }
          if (A !== "") {
            if (Object.prototype.hasOwnProperty.call(T, A)) {
              if (A.charCodeAt(0) < 256) {
                for (x = 0; x < R; x++)
                  i = i << 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++;
                for (f = A.charCodeAt(0), x = 0; x < 8; x++)
                  i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
              } else {
                for (f = 1, x = 0; x < R; x++)
                  i = i << 1 | f, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = 0;
                for (f = A.charCodeAt(0), x = 0; x < 16; x++)
                  i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
              }
              _--, _ == 0 && (_ = Math.pow(2, R), R++), delete T[A];
            } else
              for (f = S[A], x = 0; x < R; x++)
                i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
            _--, _ == 0 && (_ = Math.pow(2, R), R++);
          }
          for (f = 2, x = 0; x < R; x++)
            i = i << 1 | f & 1, g == u - 1 ? (g = 0, y.push(m(i)), i = 0) : g++, f = f >> 1;
          for (; ; )
            if (i = i << 1, g == u - 1) {
              y.push(m(i));
              break;
            } else g++;
          return y.join("");
        },
        decompress: function(o) {
          return o == null ? "" : o == "" ? null : h._decompress(o.length, 32768, function(u) {
            return o.charCodeAt(u);
          });
        },
        _decompress: function(o, u, m) {
          var x = [], f = 4, S = 4, T = 3, D = "", k = [], A, _, O, R, y, i, g, p = { val: m(0), position: u, index: 1 };
          for (A = 0; A < 3; A += 1)
            x[A] = A;
          for (O = 0, y = Math.pow(2, 2), i = 1; i != y; )
            R = p.val & p.position, p.position >>= 1, p.position == 0 && (p.position = u, p.val = m(p.index++)), O |= (R > 0 ? 1 : 0) * i, i <<= 1;
          switch (O) {
            case 0:
              for (O = 0, y = Math.pow(2, 8), i = 1; i != y; )
                R = p.val & p.position, p.position >>= 1, p.position == 0 && (p.position = u, p.val = m(p.index++)), O |= (R > 0 ? 1 : 0) * i, i <<= 1;
              g = n(O);
              break;
            case 1:
              for (O = 0, y = Math.pow(2, 16), i = 1; i != y; )
                R = p.val & p.position, p.position >>= 1, p.position == 0 && (p.position = u, p.val = m(p.index++)), O |= (R > 0 ? 1 : 0) * i, i <<= 1;
              g = n(O);
              break;
            case 2:
              return "";
          }
          for (x[3] = g, _ = g, k.push(g); ; ) {
            if (p.index > o)
              return "";
            for (O = 0, y = Math.pow(2, T), i = 1; i != y; )
              R = p.val & p.position, p.position >>= 1, p.position == 0 && (p.position = u, p.val = m(p.index++)), O |= (R > 0 ? 1 : 0) * i, i <<= 1;
            switch (g = O) {
              case 0:
                for (O = 0, y = Math.pow(2, 8), i = 1; i != y; )
                  R = p.val & p.position, p.position >>= 1, p.position == 0 && (p.position = u, p.val = m(p.index++)), O |= (R > 0 ? 1 : 0) * i, i <<= 1;
                x[S++] = n(O), g = S - 1, f--;
                break;
              case 1:
                for (O = 0, y = Math.pow(2, 16), i = 1; i != y; )
                  R = p.val & p.position, p.position >>= 1, p.position == 0 && (p.position = u, p.val = m(p.index++)), O |= (R > 0 ? 1 : 0) * i, i <<= 1;
                x[S++] = n(O), g = S - 1, f--;
                break;
              case 2:
                return k.join("");
            }
            if (f == 0 && (f = Math.pow(2, T), T++), x[g])
              D = x[g];
            else if (g === S)
              D = _ + _.charAt(0);
            else
              return null;
            k.push(D), x[S++] = _ + D.charAt(0), f--, _ = D, f == 0 && (f = Math.pow(2, T), T++);
          }
        }
      };
      return h;
    })();
    t != null ? t.exports = r : typeof angular < "u" && angular != null && angular.module("LZString", []).factory("LZString", function() {
      return r;
    });
  })(Tr)), Tr.exports;
}
var ns = /* @__PURE__ */ vc();
const hn = 1800, pn = "share=";
function xn(t) {
  const r = JSON.stringify(t);
  return ns.compressToEncodedURIComponent(r);
}
function Nc(t) {
  try {
    const r = ns.decompressFromEncodedURIComponent(t);
    if (!r) return null;
    const n = JSON.parse(r);
    return !n.query || typeof n.query != "object" ? null : n;
  } catch {
    return null;
  }
}
function wc(t) {
  const r = xn(t);
  if (r.length <= hn)
    return { encoded: r, queryOnly: !1 };
  const n = { query: t.query }, a = xn(n);
  return a.length <= hn ? { encoded: a, queryOnly: !0 } : { encoded: null, queryOnly: !0 };
}
function kc() {
  if (typeof window > "u") return null;
  const t = window.location.hash;
  return !t || !t.startsWith(`#${pn}`) ? null : t.slice(pn.length + 1);
}
function Cc() {
  if (typeof window > "u") return;
  const t = new URL(window.location.href);
  t.hash = "", window.history.replaceState(null, "", t.toString());
}
async function Dc(t, r, n = "/api/ai/generate") {
  const a = {
    text: r
    // Send only the user's prompt, server handles system prompt
  }, c = {
    "Content-Type": "application/json"
  };
  console.log("🤖 Client: Sending user prompt to AI proxy"), console.log("  URL:", n), console.log("  Headers:", c), console.log("  User prompt length:", r.length);
  const l = await fetch(n, {
    method: "POST",
    headers: c,
    body: JSON.stringify(a)
  });
  if (console.log("📥 Client: Proxy response"), console.log("  Status:", l.status), console.log("  Status Text:", l.statusText), !l.ok) {
    let h = `Failed to generate content: ${l.status} ${l.statusText}`;
    try {
      const o = await l.json();
      if (console.error("❌ Client: Proxy error:", o), l.status === 429 && o.error === "Daily quota exceeded")
        throw new Error(
          `${o.message}

${o.suggestion || "Add your own Gemini API key for unlimited access."}`
        );
      o.error && (h = o.message || o.error, o.suggestion && (h += `

💡 ${o.suggestion}`));
    } catch {
      try {
        const o = await l.text();
        console.error("❌ Client: Proxy text error:", o), h = o || h;
      } catch {
        console.error("❌ Client: Could not parse error response");
      }
    }
    throw new Error(h);
  }
  const d = await l.json();
  return console.log("✅ Client: Successfully generated content"), d;
}
function Tc(t) {
  return (t.query || "").replace(/```json\s*/g, "").replace(/```\s*/g, "").replace(/^\s*```.*\n/gm, "").trim();
}
const bn = z("sparkles"), Sc = z("error");
function Ac({
  userPrompt: t,
  onPromptChange: r,
  isGenerating: n,
  error: a,
  hasGeneratedQuery: c,
  onGenerate: l,
  onAccept: d,
  onCancel: h
}) {
  const o = F(
    (u) => {
      u.key === "Enter" && !u.shiftKey && (u.preventDefault(), l());
    },
    [l]
  );
  return /* @__PURE__ */ s(
    "div",
    {
      className: "border-b border-dc-border",
      style: { background: "linear-gradient(to right, var(--dc-ai-gradient-start), var(--dc-ai-gradient-end))" },
      children: [
        /* @__PURE__ */ s("div", { className: "px-4 py-2 flex items-center justify-between border-b border-dc-border bg-dc-surface-secondary", children: [
          /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ e(bn, { className: "w-4 h-4 text-dc-accent" }),
            /* @__PURE__ */ e("span", { className: "text-sm font-medium text-dc-text", children: "AI Query Generator" }),
            n && /* @__PURE__ */ e("span", { className: "text-xs text-dc-accent animate-pulse", children: "Generating..." })
          ] }),
          /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
            c && /* @__PURE__ */ e(
              "button",
              {
                onClick: d,
                className: "px-3 py-1 text-xs font-medium text-white bg-dc-success hover:opacity-80 rounded transition-colors",
                children: "Accept"
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: h,
                className: "px-3 py-1 text-xs font-medium text-dc-text-secondary hover:text-dc-text bg-dc-surface hover:bg-dc-surface-hover border border-dc-border rounded transition-colors",
                children: c ? "Cancel" : "Close"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ s("div", { className: "p-4", children: [
          /* @__PURE__ */ s("div", { className: "flex gap-3", children: [
            /* @__PURE__ */ s("div", { className: "flex-1", children: [
              /* @__PURE__ */ e(
                "textarea",
                {
                  value: t,
                  onChange: (u) => r(u.target.value),
                  onKeyDown: o,
                  placeholder: "Describe your query in natural language... (e.g., 'Show total sales by month for the last year')",
                  className: "w-full px-3 py-2 text-sm border border-dc-border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-dc-accent focus:border-dc-accent resize-none bg-dc-surface text-dc-text placeholder-dc-text-muted",
                  rows: 2,
                  disabled: n
                }
              ),
              /* @__PURE__ */ e("div", { className: "mt-1 text-xs text-dc-text-muted", children: "Press Enter to generate, Shift+Enter for new line" })
            ] }),
            /* @__PURE__ */ e("div", { className: "flex-shrink-0", children: /* @__PURE__ */ e(
              "button",
              {
                onClick: l,
                disabled: n || !t.trim(),
                className: `px-4 py-2 text-sm font-medium rounded-md transition-colors flex items-center gap-2 ${n || !t.trim() ? "bg-dc-surface-tertiary text-dc-text-disabled cursor-not-allowed" : "bg-dc-accent hover:bg-dc-accent-hover text-white"}`,
                children: n ? /* @__PURE__ */ s(Ie, { children: [
                  /* @__PURE__ */ e("div", { className: "w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" }),
                  /* @__PURE__ */ e("span", { children: "Generating..." })
                ] }) : /* @__PURE__ */ s(Ie, { children: [
                  /* @__PURE__ */ e(bn, { className: "w-4 h-4" }),
                  /* @__PURE__ */ e("span", { children: "Generate" })
                ] })
              }
            ) })
          ] }),
          a && /* @__PURE__ */ s("div", { className: "mt-3 flex items-start gap-2 p-3 bg-dc-error-bg border border-dc-error-border rounded-md", children: [
            /* @__PURE__ */ e(Sc, { className: "w-4 h-4 text-dc-error mt-0.5 flex-shrink-0" }),
            /* @__PURE__ */ e("div", { className: "text-sm text-dc-error", children: a })
          ] }),
          c && !a && /* @__PURE__ */ e("div", { className: "mt-3 p-3 bg-dc-success-bg border border-dc-success-border rounded-md", children: /* @__PURE__ */ s("div", { className: "text-sm text-dc-success", children: [
            "Query generated and loaded! Check the results below, then click",
            " ",
            /* @__PURE__ */ e("strong", { children: "Accept" }),
            " to keep or ",
            /* @__PURE__ */ e("strong", { children: "Cancel" }),
            " to revert."
          ] }) })
        ] })
      ]
    }
  );
}
const ss = "drizzle-cube-analysis-builder-state", _c = 300;
function at() {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
function or(t) {
  let r = "", n = t;
  do
    r = String.fromCharCode(65 + n % 26) + r, n = Math.floor(n / 26) - 1;
  while (n >= 0);
  return r;
}
function Ec(t, r, n, a) {
  const c = {
    measures: t.map((l) => l.field),
    dimensions: r.filter((l) => !l.isTimeDimension).map((l) => l.field),
    timeDimensions: r.filter((l) => l.isTimeDimension).map((l) => ({
      dimension: l.field,
      granularity: l.granularity || "day"
    })),
    filters: n.length > 0 ? n : void 0,
    order: a && Object.keys(a).length > 0 ? a : void 0
  };
  return c.measures?.length === 0 && delete c.measures, c.dimensions?.length === 0 && delete c.dimensions, c.timeDimensions?.length === 0 && delete c.timeDimensions, c;
}
function Yt() {
  return {
    metrics: [],
    breakdowns: [],
    filters: [],
    validationStatus: "idle",
    validationError: null,
    executionStatus: "idle",
    executionResults: null,
    executionError: null,
    totalRowCount: null,
    resultsStale: !1
  };
}
function Rc(t) {
  if (t) return null;
  try {
    const r = localStorage.getItem(ss);
    if (r)
      return JSON.parse(r);
  } catch {
  }
  return null;
}
const Qr = Fr(
  ({
    className: t = "",
    maxHeight: r,
    initialQuery: n,
    initialChartConfig: a,
    initialData: c,
    colorPalette: l,
    disableLocalStorage: d = !1,
    hideSettings: h = !1,
    onQueryChange: o,
    onChartConfigChange: u
  }, m) => {
    const x = d || !!n, { meta: f, cubeApi: S } = jt(), T = Oe(
      () => Rc(d),
      []
      // Only run once on mount
    ), [D, k] = H(() => n ? {
      ...Yt(),
      metrics: (n.measures || []).map((B, te) => ({
        id: at(),
        field: B,
        label: or(te)
      })),
      breakdowns: [
        ...(n.dimensions || []).map((B) => ({
          id: at(),
          field: B,
          isTimeDimension: !1
        })),
        ...(n.timeDimensions || []).map((B) => ({
          id: at(),
          field: B.dimension,
          granularity: B.granularity,
          isTimeDimension: !0
        }))
      ],
      filters: n.filters || []
    } : T ? {
      ...Yt(),
      metrics: T.metrics || [],
      breakdowns: T.breakdowns || [],
      filters: T.filters || []
    } : Yt()), [A, _] = H(() => a?.chartType ? a.chartType : !n && T?.chartType ? T.chartType : "line"), [O, R] = H(() => a?.chartConfig ? a.chartConfig : !n && T?.chartConfig ? T.chartConfig : {}), [y, i] = H(() => a?.displayConfig ? a.displayConfig : !n && T?.displayConfig ? T.displayConfig : { showLegend: !0, showGrid: !0, showTooltip: !0 }), [g, p] = H("default"), b = Oe(() => l || zr(g), [l, g]), [w, v] = H(() => {
      if (n?.order)
        return n.order;
      if (!n && T?.order)
        return T.order;
    }), [M, $] = H("query"), [C, L] = H(() => !n && T?.activeView ? T.activeView : "chart"), [I, E] = H(100), [K, P] = H(
      () => !!a?.chartType
    ), [Ne, ye] = H({ sql: null, analysis: null, loading: !1, error: null }), [Ue, Q] = H(!1), [ue, me] = H("metrics"), [J, Y] = H("idle"), { features: ge } = jt(), [ee, j] = H({
      isOpen: !1,
      userPrompt: "",
      isGenerating: !1,
      error: null,
      hasGeneratedQuery: !1,
      previousState: null
    });
    Ce(() => {
      if (n) return;
      const B = kc();
      if (!B) return;
      const te = Nc(B);
      if (!te || !te.query) return;
      const W = te.query;
      k({
        ...Yt(),
        metrics: (W.measures || []).map((ie, Le) => ({
          id: at(),
          field: ie,
          label: or(Le)
        })),
        breakdowns: [
          ...(W.dimensions || []).map((ie) => ({
            id: at(),
            field: ie,
            isTimeDimension: !1
          })),
          ...(W.timeDimensions || []).map((ie) => ({
            id: at(),
            field: ie.dimension,
            granularity: ie.granularity,
            isTimeDimension: !0
          }))
        ],
        filters: W.filters || []
      }), W.order && v(W.order), te.chartType && (_(te.chartType), P(!0)), te.chartConfig && R(te.chartConfig), te.displayConfig && i(te.displayConfig), te.activeView && L(te.activeView), Cc();
    }, []);
    const re = Oe(
      () => Ec(D.metrics, D.breakdowns, D.filters, w),
      [D.metrics, D.breakdowns, D.filters, w]
    ), xe = Oe(() => JSON.stringify(re), [re]), [$e, Me] = H(null), ze = Te(null), ve = Te(""), Be = Te(!!c && c.length > 0), U = Te(n ? JSON.stringify(n) : ""), fe = Te(""), ae = Te(O), Ae = re.measures && re.measures.length > 0 || re.dimensions && re.dimensions.length > 0 || re.timeDimensions && re.timeDimensions.length > 0;
    Ce(() => {
      if (xe !== ve.current) {
        if (Be.current && xe === U.current) {
          ve.current = xe, Be.current = !1;
          return;
        }
        return ze.current && clearTimeout(ze.current), Ae ? ze.current = setTimeout(() => {
          ve.current = xe, Me(re);
        }, _c) : (ve.current = xe, Me(null)), () => {
          ze.current && clearTimeout(ze.current);
        };
      }
    }, [xe, re, Ae]);
    const ke = Oe(() => $e ? wa($e) : null, [$e]), { resultSet: Fe, isLoading: Ke, error: yt } = Rn(ke, {
      skip: !ke,
      resetResultSetOnChange: !0
    }), it = Oe(() => c && c.length > 0 && !$e && !Fe ? "success" : $e ? Ke && !Fe ? "loading" : Ke && Fe ? "refreshing" : yt ? "error" : Fe ? "success" : "idle" : "idle", [$e, Ke, yt, Fe, c]), pt = Oe(() => {
      if (Fe)
        try {
          return Fe.rawData();
        } catch {
          return null;
        }
      return c && c.length > 0 ? c : null;
    }, [Fe, c]), Dt = Oe(
      () => Ma(D.metrics, D.breakdowns),
      [D.metrics, D.breakdowns]
    ), Mt = F((B) => ["xAxis", "yAxis", "series", "sizeField", "colorField", "dateField", "valueField"].every((W) => {
      const ie = B[W];
      return ie == null ? !0 : Array.isArray(ie) ? ie.length === 0 : typeof ie == "string" ? ie === "" : !1;
    }), []);
    ae.current = O, Ce(() => {
      if (!$e || D.metrics.length === 0 && D.breakdowns.length === 0)
        return;
      const B = JSON.stringify({
        metrics: D.metrics.map((W) => W.field),
        breakdowns: D.breakdowns.map((W) => ({ field: W.field, isTime: W.isTimeDimension }))
      });
      if (B === fe.current)
        return;
      fe.current = B;
      const te = $a(
        D.metrics,
        D.breakdowns,
        A,
        K
      );
      if (te) {
        const { chartConfig: W } = Cr(
          D.metrics,
          D.breakdowns,
          te
        );
        _(te), R(W), P(!1);
      } else if ((D.metrics.length > 0 || D.breakdowns.length > 0) && Mt(ae.current)) {
        const { chartConfig: W } = Cr(
          D.metrics,
          D.breakdowns,
          A
        );
        R(W);
      }
    }, [$e, D.metrics, D.breakdowns, A, K, Mt]), Ce(() => {
      if (x) return;
      const B = setTimeout(() => {
        try {
          const te = {
            metrics: D.metrics,
            breakdowns: D.breakdowns,
            filters: D.filters,
            order: w,
            chartType: A,
            chartConfig: O,
            displayConfig: y,
            activeView: C
          };
          localStorage.setItem(ss, JSON.stringify(te));
        } catch {
        }
      }, 0);
      return () => clearTimeout(B);
    }, [
      D.metrics,
      D.breakdowns,
      D.filters,
      w,
      A,
      O,
      y,
      C,
      x
    ]), Ce(() => {
      o && Ae && o(re);
    }, [re, Ae, o]), Ce(() => {
      u && u({ chartType: A, chartConfig: O, displayConfig: y });
    }, [A, O, y, u]), Ce(() => {
      if (!Ae || !ke) {
        ye({ sql: null, analysis: null, loading: !1, error: null });
        return;
      }
      let B = !1;
      return (async () => {
        ye((W) => ({ ...W, loading: !0, error: null }));
        try {
          const W = await S.dryRun(ke);
          B || ye({
            sql: W.sql,
            analysis: W.analysis,
            loading: !1,
            error: null
          });
        } catch (W) {
          B || ye({
            sql: null,
            analysis: null,
            loading: !1,
            error: W instanceof Error ? W.message : "Failed to fetch debug info"
          });
        }
      })(), () => {
        B = !0;
      };
    }, [ke, S, Ae]);
    const Vt = F(() => {
      me("metrics"), Q(!0);
    }, []), Ht = F((B) => {
      const te = D.metrics.find((W) => W.id === B)?.field;
      k((W) => ({
        ...W,
        metrics: W.metrics.filter((ie) => ie.id !== B),
        resultsStale: !0
      })), te && v((W) => {
        if (!W || !W[te]) return W;
        const ie = { ...W };
        return delete ie[te], Object.keys(ie).length > 0 ? ie : void 0;
      });
    }, [D.metrics]), zt = F(
      (B, te, W, ie) => {
        if (ue === "metrics" && te === "measure")
          k((Le) => {
            const Ge = Le.metrics.findIndex((G) => G.field === B.name);
            if (Ge >= 0)
              return {
                ...Le,
                metrics: Le.metrics.filter((G, ne) => ne !== Ge),
                resultsStale: !0
              };
            const V = {
              id: at(),
              field: B.name,
              label: or(Le.metrics.length)
            };
            return {
              ...Le,
              metrics: [...Le.metrics, V],
              resultsStale: !0
            };
          });
        else if (ue === "breakdown") {
          const Le = te === "timeDimension";
          k((Ge) => {
            const V = Ge.breakdowns.findIndex((ne) => ne.field === B.name);
            if (V >= 0)
              return {
                ...Ge,
                breakdowns: Ge.breakdowns.filter((ne, se) => se !== V),
                resultsStale: !0
              };
            if (Le && Ge.breakdowns.some((se) => se.isTimeDimension))
              return Ge;
            const G = {
              id: at(),
              field: B.name,
              isTimeDimension: Le,
              granularity: Le ? "month" : void 0
            };
            return {
              ...Ge,
              breakdowns: [...Ge.breakdowns, G],
              resultsStale: !0
            };
          });
        }
        ie || Q(!1);
      },
      [ue]
    ), Qt = F(() => {
      me("breakdown"), Q(!0);
    }, []), It = F((B) => {
      const te = D.breakdowns.find((W) => W.id === B)?.field;
      k((W) => ({
        ...W,
        breakdowns: W.breakdowns.filter((ie) => ie.id !== B),
        resultsStale: !0
      })), te && v((W) => {
        if (!W || !W[te]) return W;
        const ie = { ...W };
        return delete ie[te], Object.keys(ie).length > 0 ? ie : void 0;
      });
    }, [D.breakdowns]), Tt = F(
      (B, te) => {
        k((W) => ({
          ...W,
          breakdowns: W.breakdowns.map(
            (ie) => ie.id === B ? { ...ie, granularity: te } : ie
          ),
          resultsStale: !0
        }));
      },
      []
    ), $t = F(
      (B, te) => {
        k((W) => {
          const ie = [...W.metrics], [Le] = ie.splice(B, 1);
          return ie.splice(te, 0, Le), {
            ...W,
            metrics: ie,
            resultsStale: !0
          };
        });
      },
      []
    ), Ft = F(
      (B, te) => {
        k((W) => {
          const ie = [...W.breakdowns], [Le] = ie.splice(B, 1);
          return ie.splice(te, 0, Le), {
            ...W,
            breakdowns: ie,
            resultsStale: !0
          };
        });
      },
      []
    ), ot = F((B) => {
      k((te) => ({
        ...te,
        filters: B,
        resultsStale: !0
      }));
    }, []), St = F((B) => {
      const te = {
        member: B,
        operator: "set",
        values: []
      };
      k((W) => {
        const ie = W.filters || [];
        if (ie.some(
          (V) => "member" in V && V.member === B
        ))
          return W;
        let Ge;
        if (ie.length === 0)
          Ge = [te];
        else if (ie.length === 1 && "type" in ie[0]) {
          const V = ie[0];
          Ge = [{
            ...V,
            filters: [...V.filters, te]
          }];
        } else
          Ge = [{
            type: "and",
            filters: [...ie, te]
          }];
        return {
          ...W,
          filters: Ge,
          resultsStale: !0
        };
      });
    }, []), At = F(
      (B, te) => {
        v((W) => {
          const ie = { ...W || {} };
          return te === null ? delete ie[B] : ie[B] = te, Object.keys(ie).length > 0 ? ie : void 0;
        });
      },
      []
    ), _t = F(() => {
      k(Yt()), v(void 0), P(!1), _("line"), R({}), i({ showLegend: !0, showGrid: !0, showTooltip: !0 }), Me(null), ze.current && (clearTimeout(ze.current), ze.current = null);
    }, []), Et = F(() => {
      j({
        isOpen: !0,
        userPrompt: "",
        isGenerating: !1,
        error: null,
        hasGeneratedQuery: !1,
        previousState: {
          metrics: [...D.metrics],
          breakdowns: [...D.breakdowns],
          filters: [...D.filters],
          chartType: A,
          chartConfig: { ...O },
          displayConfig: { ...y }
        }
      });
    }, [D.metrics, D.breakdowns, D.filters, A, O, y]), dt = F(() => {
      j((B) => ({
        ...B,
        isOpen: !1,
        userPrompt: "",
        error: null,
        hasGeneratedQuery: !1
      }));
    }, []), N = F((B) => {
      j((te) => ({ ...te, userPrompt: B }));
    }, []), q = F(async () => {
      if (ee.userPrompt.trim()) {
        j((B) => ({ ...B, isGenerating: !0, error: null }));
        try {
          const B = await Dc(
            "",
            // API key not needed for server-side AI
            ee.userPrompt,
            ge?.aiEndpoint || "/api/ai"
          ), te = Tc(B), W = JSON.parse(te), ie = "query" in W && W.query ? W.query : W, Le = "chartType" in W ? W.chartType : void 0, Ge = "chartConfig" in W ? W.chartConfig : void 0;
          k((V) => ({
            ...V,
            metrics: (ie.measures || []).map((G, ne) => ({
              id: at(),
              field: G,
              label: or(ne)
            })),
            breakdowns: [
              ...(ie.dimensions || []).map((G) => ({
                id: at(),
                field: G,
                isTimeDimension: !1
              })),
              ...(ie.timeDimensions || []).map((G) => ({
                id: at(),
                field: G.dimension,
                granularity: G.granularity,
                isTimeDimension: !0
              }))
            ],
            filters: ie.filters || []
          })), Le && (_(Le), P(!0)), Ge && R(Ge), L("chart"), j((V) => ({
            ...V,
            isGenerating: !1,
            hasGeneratedQuery: !0
          }));
        } catch (B) {
          j((te) => ({
            ...te,
            isGenerating: !1,
            error: B instanceof Error ? B.message : "Failed to generate query"
          }));
        }
      }
    }, [ee.userPrompt, ge?.aiEndpoint]), Z = F(() => {
      j({
        isOpen: !1,
        userPrompt: "",
        isGenerating: !1,
        error: null,
        hasGeneratedQuery: !1,
        previousState: null
      });
    }, []), we = F(() => {
      ee.previousState && (k((B) => ({
        ...B,
        metrics: ee.previousState.metrics,
        breakdowns: ee.previousState.breakdowns,
        filters: ee.previousState.filters
      })), _(ee.previousState.chartType), R(ee.previousState.chartConfig), i(ee.previousState.displayConfig)), j({
        isOpen: !1,
        userPrompt: "",
        isGenerating: !1,
        error: null,
        hasGeneratedQuery: !1,
        previousState: null
      });
    }, [ee.previousState]), Ve = F((B) => {
      _(B), P(!0);
      const { chartConfig: te } = Cr(
        D.metrics,
        D.breakdowns,
        B
      );
      R(te), L("chart");
    }, [D.metrics, D.breakdowns]), Qe = F((B) => {
      R(B), L("chart");
    }, []), oe = F((B) => {
      i(B), L("chart");
    }, []), le = F(async () => {
      if (!Ae || !ke) return;
      const B = {
        query: ke,
        chartType: A,
        chartConfig: O,
        displayConfig: y,
        activeView: C
      }, { encoded: te, queryOnly: W } = wc(B);
      if (!te)
        return;
      const ie = `${window.location.origin}${window.location.pathname}#share=${te}`;
      try {
        await navigator.clipboard.writeText(ie);
      } catch {
        const Le = document.createElement("textarea");
        Le.value = ie, document.body.appendChild(Le), Le.select(), document.execCommand("copy"), document.body.removeChild(Le);
      }
      Y(W ? "copied-no-chart" : "copied"), setTimeout(() => {
        Y("idle");
      }, 2e3);
    }, [Ae, ke, A, O, y, C]);
    return Lr(
      m,
      () => ({
        getCurrentQuery: () => re,
        getChartConfig: () => ({ chartType: A, chartConfig: O, displayConfig: y }),
        executeQuery: () => {
        },
        clearQuery: _t
      }),
      [re, A, O, y, _t]
    ), /* @__PURE__ */ s(
      "div",
      {
        className: `flex flex-col lg:flex-row bg-dc-surface border-x border-b border-dc-border ${r ? "lg:h-[var(--dc-max-h)] lg:max-h-[var(--dc-max-h)] lg:overflow-hidden" : "lg:h-full"} ${t}`,
        style: r ? { "--dc-max-h": r } : void 0,
        children: [
          /* @__PURE__ */ s("div", { className: "h-[60vh] lg:h-auto lg:flex-1 min-w-0 border-b lg:border-b-0 lg:border-r border-dc-border overflow-auto flex flex-col", children: [
            ee.isOpen && /* @__PURE__ */ e(
              Ac,
              {
                userPrompt: ee.userPrompt,
                onPromptChange: N,
                isGenerating: ee.isGenerating,
                error: ee.error,
                hasGeneratedQuery: ee.hasGeneratedQuery,
                onGenerate: q,
                onAccept: Z,
                onCancel: we
              }
            ),
            /* @__PURE__ */ e("div", { className: "flex-1 overflow-auto", children: /* @__PURE__ */ e(
              La,
              {
                executionStatus: it,
                executionResults: pt,
                executionError: yt?.message || null,
                totalRowCount: null,
                resultsStale: Ke && pt !== null,
                chartType: A,
                chartConfig: O,
                displayConfig: y,
                colorPalette: b,
                currentPaletteName: l ? void 0 : g,
                onColorPaletteChange: l ? void 0 : p,
                query: re,
                schema: f,
                activeView: C,
                onActiveViewChange: L,
                displayLimit: I,
                onDisplayLimitChange: E,
                hasMetrics: D.metrics.length > 0,
                debugQuery: ke,
                debugSql: Ne.sql,
                debugAnalysis: Ne.analysis,
                debugLoading: Ne.loading,
                debugError: Ne.error,
                onShareClick: le,
                canShare: Ae,
                shareButtonState: J,
                onClearClick: _t,
                canClear: D.metrics.length > 0 || D.breakdowns.length > 0 || D.filters.length > 0,
                enableAI: ge?.enableAI !== !1,
                isAIOpen: ee.isOpen,
                onAIToggle: ee.isOpen ? dt : Et
              }
            ) })
          ] }),
          /* @__PURE__ */ e("div", { className: "w-full lg:w-96 flex-shrink-0 lg:h-full overflow-auto lg:overflow-hidden", children: /* @__PURE__ */ e(
            yc,
            {
              metrics: D.metrics,
              breakdowns: D.breakdowns,
              filters: D.filters,
              schema: f,
              activeTab: M,
              onActiveTabChange: $,
              onAddMetric: Vt,
              onRemoveMetric: Ht,
              onReorderMetrics: $t,
              onAddBreakdown: Qt,
              onRemoveBreakdown: It,
              onBreakdownGranularityChange: Tt,
              onReorderBreakdowns: Ft,
              onFiltersChange: ot,
              onDropFieldToFilter: St,
              order: w,
              onOrderChange: At,
              chartType: A,
              chartConfig: O,
              displayConfig: y,
              colorPalette: b,
              chartAvailability: Dt,
              onChartTypeChange: Ve,
              onChartConfigChange: Qe,
              onDisplayConfigChange: oe,
              validationStatus: D.validationStatus,
              validationError: D.validationError
            }
          ) }),
          /* @__PURE__ */ e(
            zn,
            {
              isOpen: Ue,
              onClose: () => Q(!1),
              onSelect: zt,
              mode: ue,
              schema: f,
              selectedFields: [
                ...D.metrics.map((B) => B.field),
                ...D.breakdowns.map((B) => B.field)
              ]
            }
          )
        ]
      }
    );
  }
);
Qr.displayName = "AnalysisBuilder";
const as = Fr(
  (t, r) => {
    const n = Te(null);
    return Lr(r, () => ({
      getCurrentQuery: () => n.current?.getCurrentQuery() || {
        measures: [],
        dimensions: []
      },
      getValidationState: () => ({
        status: "valid"
      }),
      getValidationResult: () => null
    }), []), /* @__PURE__ */ e(
      Qr,
      {
        ref: n,
        className: t.className,
        initialQuery: t.initialQuery,
        disableLocalStorage: t.disableLocalStorage,
        hideSettings: t.hideSettings
      }
    );
  }
);
as.displayName = "QueryBuilder";
const Oc = z("close");
function Mc({
  config: t,
  fields: r,
  onDrop: n,
  onRemove: a,
  onDragStart: c,
  onDragEnd: l,
  onDragOver: d,
  getFieldStyling: h,
  onReorder: o,
  draggedItem: u
}) {
  const { key: m, label: x, description: f, mandatory: S, maxItems: T, emptyText: D, icon: k } = t, [A, _] = H(null), [O, R] = H(!1), [y, i] = H(!1), g = () => {
    let C = r.length;
    return u && u.fromAxis === m && (C = Math.max(0, r.length - 1)), !T || C < T;
  }, p = () => {
    let C = r.length;
    return u && u.fromAxis === m && (C = Math.max(0, r.length - 1)), T && C >= T;
  }, b = g(), w = p();
  lt.useEffect(() => {
    const C = () => {
      _(null), R(!1), i(!1);
    };
    return document.addEventListener("dragend", C), () => {
      document.removeEventListener("dragend", C);
    };
  }, []), lt.useEffect(() => {
    u ? u.fromAxis !== m ? (i(!1), _(null)) : u.fromAxis === m && u.fromIndex !== void 0 && R(!1) : (_(null), R(!1), i(!1));
  }, [u, m]);
  const v = (C, L) => {
    u && u.fromAxis === m && u.fromIndex !== void 0 && (C.preventDefault(), C.stopPropagation(), _(L), i(!0));
  }, M = () => {
    _(null);
  }, $ = (C, L) => {
    if (C.preventDefault(), C.stopPropagation(), _(null), i(!1), u && u.fromAxis === m && u.fromIndex !== void 0 && o) {
      o(u.fromIndex, L, m);
      return;
    }
    try {
      const I = JSON.parse(C.dataTransfer.getData("text/plain"));
      I.fromAxis === m && o && I.fromIndex !== void 0 && o(I.fromIndex, L, m);
    } catch {
    }
  };
  return /* @__PURE__ */ s("div", { className: "mb-2", children: [
    /* @__PURE__ */ s("div", { className: "flex items-center gap-2 mb-1", children: [
      /* @__PURE__ */ s("h4", { className: "text-xs font-semibold text-dc-text-secondary flex items-center", children: [
        k && /* @__PURE__ */ e(k, { className: "w-3 h-3 mr-1 text-dc-text-muted" }),
        x,
        S && /* @__PURE__ */ e("span", { className: "text-dc-error ml-1", children: "*" }),
        T && /* @__PURE__ */ s("span", { className: "text-dc-text-muted ml-1 font-normal", children: [
          "(",
          r.length,
          "/",
          T,
          ")"
        ] })
      ] }),
      f && /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted", children: f })
    ] }),
    /* @__PURE__ */ e(
      "div",
      {
        "data-axis-container": m,
        className: `min-h-[40px] sm:min-h-[32px] border-2 border-dashed rounded-lg p-3 sm:p-1.5 transition-all duration-300 flex items-center ${O && (b || T === 1) || y ? "shadow-lg scale-110 border-solid animate-pulse" : w ? "bg-dc-surface-secondary" : "bg-dc-surface-secondary hover:bg-dc-surface-hover"}`,
        style: {
          borderColor: O && (b || T === 1) || y ? "var(--dc-primary)" : "var(--dc-border)",
          backgroundColor: O && (b || T === 1) || y ? "rgba(var(--dc-primary-rgb), 0.1)" : void 0
        },
        onDragOver: (C) => {
          if (u && u.fromAxis === m && u.fromIndex !== void 0)
            return;
          b || T === 1 ? (R(!0), d(C)) : (C.preventDefault(), C.dataTransfer.dropEffect = "none");
        },
        onDragLeave: (C) => {
          const L = C.currentTarget.getBoundingClientRect(), I = C.clientX < L.left || C.clientX > L.right || C.clientY < L.top || C.clientY > L.bottom, E = C.relatedTarget, K = E && !C.currentTarget.contains(E);
          (I || K || C.currentTarget === C.target) && (R(!1), i(!1));
        },
        onDrop: (C) => {
          if (u && u.fromAxis === m && u.fromIndex !== void 0)
            return;
          b || T === 1 ? n(C, m) : C.preventDefault(), R(!1), i(!1);
        },
        children: r.length === 0 ? /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted text-center w-full", children: w ? "Maximum items reached" : D || "Drop fields here" }) : /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-1", children: r.map((C, L) => {
          const { IconComponent: I, baseClasses: E, hoverClasses: K } = h(C), P = A === L, Ne = u && u.field === C && u.fromAxis === m;
          return /* @__PURE__ */ s(
            "div",
            {
              className: `relative ${P ? "transform scale-105" : ""}`,
              children: [
                P && /* @__PURE__ */ e("div", { className: "absolute -left-1 top-0 bottom-0 w-1 rounded-full z-10", style: { backgroundColor: "var(--dc-primary)" } }),
                /* @__PURE__ */ s(
                  "div",
                  {
                    draggable: !0,
                    onDragStart: (ye) => {
                      c(ye, C, m, L);
                    },
                    onDragEnd: l,
                    onDragOver: (ye) => v(ye, L),
                    onDragLeave: M,
                    onDrop: (ye) => $(ye, L),
                    className: `rounded text-xs cursor-move px-3 py-0.5 sm:px-2 sm:py-1 flex items-center transition-transform h-[28px] sm:h-auto ${E} ${K} ${P ? "bg-opacity-75" : ""} ${Ne ? "opacity-50 cursor-grabbing" : ""}`,
                    children: [
                      /* @__PURE__ */ e(I, { className: "w-3 h-3 mr-1 shrink-0" }),
                      /* @__PURE__ */ e("span", { className: "leading-none", children: C }),
                      /* @__PURE__ */ e(
                        "button",
                        {
                          type: "button",
                          onClick: () => a(C, m),
                          className: "text-dc-text-secondary hover:text-dc-danger ml-1.5 leading-none",
                          title: `Remove from ${x}`,
                          children: /* @__PURE__ */ e(Oc, { className: "w-3 h-3" })
                        }
                      )
                    ]
                  }
                )
              ]
            },
            `${C}-${L}`
          );
        }) })
      }
    ),
    S && r.length === 0 && /* @__PURE__ */ e("div", { className: "text-xs text-dc-error mt-0.5", children: "This field is required" })
  ] });
}
const gn = z("measure"), yn = z("dimension"), vn = z("timeDimension");
function Nn({
  chartType: t,
  chartConfig: r,
  displayConfig: n,
  availableFields: a,
  colorPalette: c,
  onChartConfigChange: l,
  onDisplayConfigChange: d
}) {
  const [h, o] = H(null), u = Oe(
    () => br(t, Bt),
    [t]
  ), m = u.skipQuery === !0, x = (i) => {
    const g = r[i];
    return Array.isArray(g) ? g : typeof g == "string" ? [g] : [];
  };
  Ce(() => {
    if (!a) return;
    const i = [
      ...a.dimensions,
      ...a.timeDimensions,
      ...a.measures
    ];
    let g = !1;
    const p = { ...r };
    u.dropZones.forEach((b) => {
      const w = x(b.key), v = w.filter((M) => i.includes(M));
      v.length !== w.length && (g = !0, v.length === 0 ? delete p[b.key] : b.maxItems === 1 ? p[b.key] = v[0] : p[b.key] = v);
    }), g && l(p);
  }, [a, r, u.dropZones, l]);
  const f = (i) => a ? a.measures.includes(i) ? "measure" : a.timeDimensions.includes(i) ? "timeDimension" : "dimension" : "dimension", S = (i) => {
    switch (f(i)) {
      case "measure":
        return {
          IconComponent: gn,
          baseClasses: "bg-dc-measure text-dc-measure border border-dc-measure",
          hoverClasses: "hover:opacity-80"
        };
      case "timeDimension":
        return {
          IconComponent: vn,
          baseClasses: "bg-dc-time-dimension text-dc-time-dimension border border-dc-time-dimension",
          hoverClasses: "hover:opacity-80"
        };
      default:
        return {
          IconComponent: yn,
          baseClasses: "bg-dc-dimension text-dc-dimension border border-dc-dimension",
          hoverClasses: "hover:opacity-80"
        };
    }
  }, T = (i, g, p, b) => {
    i.dataTransfer.setData("text/plain", JSON.stringify({ field: g, fromAxis: p, fromIndex: b })), o({ field: g, fromAxis: p, fromIndex: b });
  }, D = (i) => {
    i.preventDefault();
  }, k = () => {
    o(null);
  }, A = (i, g) => {
    i.preventDefault();
    const p = JSON.parse(i.dataTransfer.getData("text/plain")), { field: b, fromAxis: w } = p, v = { ...r };
    if (w !== "available" && w !== g) {
      const C = v[w];
      if (Array.isArray(C)) {
        const L = C.filter((I) => I !== b);
        L.length === 0 ? delete v[w] : v[w] = L;
      } else C === b && delete v[w];
    }
    const M = v[g];
    u.dropZones.find((C) => C.key === g)?.maxItems === 1 ? v[g] = b : Array.isArray(M) ? M.includes(b) || (v[g] = [...M, b]) : v[g] = [b], o(null), l(v);
  }, _ = (i, g) => {
    const p = { ...r }, b = p[g];
    if (Array.isArray(b)) {
      const w = b.filter((v) => v !== i);
      w.length === 0 ? delete p[g] : p[g] = w;
    } else b === i && delete p[g];
    l(p);
  }, O = (i, g, p) => {
    const b = { ...r }, w = b[p];
    if (Array.isArray(w) && w.length > 1 && i !== g) {
      const v = [...w], [M] = v.splice(i, 1);
      v.splice(g, 0, M), b[p] = v, o(null), l(b);
    }
  }, y = (() => {
    if (!a) return { dimensions: [], timeDimensions: [], measures: [] };
    const i = /* @__PURE__ */ new Set();
    return u.dropZones.forEach((g) => {
      x(g.key).forEach((p) => i.add(p));
    }), h && h.fromAxis !== "available" && i.add(h.field), {
      dimensions: a.dimensions.filter((g) => !i.has(g)),
      timeDimensions: a.timeDimensions.filter((g) => !i.has(g)),
      measures: a.measures.filter((g) => !i.has(g))
    };
  })();
  return /* @__PURE__ */ s("div", { children: [
    !m && a && /* @__PURE__ */ s("div", { className: "mb-4", children: [
      /* @__PURE__ */ e("h4", { className: "text-xs font-semibold text-dc-text-secondary mb-2", children: "Available Fields" }),
      /* @__PURE__ */ e("div", { className: "border border-dc-border rounded-lg p-2 bg-dc-surface-secondary", children: y.dimensions.length > 0 || y.timeDimensions.length > 0 || y.measures.length > 0 ? /* @__PURE__ */ s("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-2 sm:gap-2 gap-y-4 sm:gap-y-2", children: [
        /* @__PURE__ */ s("div", { className: "pb-2 sm:pb-0", children: [
          /* @__PURE__ */ s("div", { className: "text-xs text-dc-text-secondary mb-2 sm:mb-1 flex items-center", children: [
            /* @__PURE__ */ e(yn, { className: "w-3 h-3 mr-1 text-dc-text-muted" }),
            "Dimensions"
          ] }),
          /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            y.dimensions.map((i) => {
              const g = h && h.field === i && h.fromAxis === "available";
              return /* @__PURE__ */ e(
                "div",
                {
                  draggable: !0,
                  onDragStart: (p) => T(p, i, "available"),
                  onDragEnd: k,
                  className: `bg-dc-dimension text-dc-dimension border border-dc-dimension hover:opacity-80 rounded-sm text-xs cursor-move px-3 py-2 sm:px-2 sm:py-1 truncate ${g ? "opacity-50 cursor-grabbing" : ""}`,
                  title: i,
                  children: i
                },
                i
              );
            }),
            y.dimensions.length === 0 && /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted italic", children: "None" })
          ] })
        ] }),
        /* @__PURE__ */ s("div", { className: "pb-2 sm:pb-0", children: [
          /* @__PURE__ */ s("div", { className: "text-xs text-dc-text-secondary mb-2 sm:mb-1 flex items-center", children: [
            /* @__PURE__ */ e(vn, { className: "w-3 h-3 mr-1 text-dc-text-muted" }),
            "Time Dimensions"
          ] }),
          /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            y.timeDimensions.map((i) => {
              const g = h && h.field === i && h.fromAxis === "available";
              return /* @__PURE__ */ e(
                "div",
                {
                  draggable: !0,
                  onDragStart: (p) => T(p, i, "available"),
                  onDragEnd: k,
                  className: `bg-dc-time-dimension text-dc-time-dimension border border-dc-time-dimension hover:opacity-80 rounded-sm text-xs cursor-move px-3 py-2 sm:px-2 sm:py-1 truncate ${g ? "opacity-50 cursor-grabbing" : ""}`,
                  title: i,
                  children: i
                },
                i
              );
            }),
            y.timeDimensions.length === 0 && /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted italic", children: "None" })
          ] })
        ] }),
        /* @__PURE__ */ s("div", { className: "pb-2 sm:pb-0", children: [
          /* @__PURE__ */ s("div", { className: "text-xs text-dc-text-secondary mb-2 sm:mb-1 flex items-center", children: [
            /* @__PURE__ */ e(gn, { className: "w-3 h-3 mr-1 text-dc-text-muted" }),
            "Measures"
          ] }),
          /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            y.measures.map((i) => {
              const g = h && h.field === i && h.fromAxis === "available";
              return /* @__PURE__ */ e(
                "div",
                {
                  draggable: !0,
                  onDragStart: (p) => T(p, i, "available"),
                  onDragEnd: k,
                  className: `bg-dc-measure text-dc-measure border border-dc-measure hover:opacity-80 rounded-sm text-xs cursor-move px-3 py-2 sm:px-2 sm:py-1 truncate ${g ? "opacity-50 cursor-grabbing" : ""}`,
                  title: i,
                  children: i
                },
                i
              );
            }),
            y.measures.length === 0 && /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted italic", children: "None" })
          ] })
        ] })
      ] }) : /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted text-center py-2", children: "All fields have been assigned" }) })
    ] }),
    !m && /* @__PURE__ */ s("div", { className: "mb-4", children: [
      /* @__PURE__ */ e("h4", { className: "text-xs font-semibold text-dc-text-secondary mb-2", children: "Chart Configuration" }),
      /* @__PURE__ */ e("div", { className: "space-y-1", children: u.dropZones.map((i) => /* @__PURE__ */ e(
        Mc,
        {
          config: i,
          fields: x(i.key),
          onDrop: A,
          onRemove: _,
          onDragStart: T,
          onDragEnd: k,
          onDragOver: D,
          getFieldStyling: S,
          onReorder: O,
          draggedItem: h
        },
        i.key
      )) })
    ] }),
    (u.displayOptions && u.displayOptions.length > 0 || u.displayOptionsConfig && u.displayOptionsConfig.length > 0) && /* @__PURE__ */ s("div", { className: "mb-4", children: [
      /* @__PURE__ */ e("h4", { className: "text-xs font-semibold text-dc-text-secondary mb-2", children: "Display Options" }),
      /* @__PURE__ */ s("div", { className: "space-y-2", children: [
        u.displayOptions?.includes("showLegend") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "checkbox",
              checked: n.showLegend ?? !0,
              onChange: (i) => d({
                ...n,
                showLegend: i.target.checked
              }),
              className: "rounded border-dc-border focus:ring-dc-accent",
              style: { color: "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Show Legend" })
        ] }),
        u.displayOptions?.includes("showGrid") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "checkbox",
              checked: n.showGrid ?? !0,
              onChange: (i) => d({
                ...n,
                showGrid: i.target.checked
              }),
              className: "rounded border-dc-border focus:ring-dc-accent",
              style: { color: "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Show Grid" })
        ] }),
        u.displayOptions?.includes("showTooltip") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "checkbox",
              checked: n.showTooltip ?? !0,
              onChange: (i) => d({
                ...n,
                showTooltip: i.target.checked
              }),
              className: "rounded border-dc-border focus:ring-dc-accent",
              style: { color: "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Show Tooltip" })
        ] }),
        u.displayOptions?.includes("stacked") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "checkbox",
              checked: n.stacked ?? !1,
              onChange: (i) => d({
                ...n,
                stacked: i.target.checked
              }),
              className: "rounded border-dc-border focus:ring-dc-accent",
              style: { color: "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Stacked" })
        ] }),
        u.displayOptions?.includes("hideHeader") && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "checkbox",
              checked: n.hideHeader ?? !1,
              onChange: (i) => d({
                ...n,
                hideHeader: i.target.checked
              }),
              className: "rounded border-dc-border focus:ring-dc-accent",
              style: { color: "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: "Hide Header" })
        ] }),
        u.displayOptionsConfig?.map((i) => /* @__PURE__ */ s("div", { className: "space-y-1", children: [
          i.type === "boolean" && /* @__PURE__ */ s("label", { className: "flex items-center space-x-2", children: [
            /* @__PURE__ */ e(
              "input",
              {
                type: "checkbox",
                checked: n[i.key] ?? i.defaultValue ?? !1,
                onChange: (g) => d({
                  ...n,
                  [i.key]: g.target.checked
                }),
                className: "rounded border-dc-border focus:ring-dc-accent",
                style: { color: "var(--dc-primary)" }
              }
            ),
            /* @__PURE__ */ e("span", { className: "text-sm text-dc-text", children: i.label })
          ] }),
          i.type === "string" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            /* @__PURE__ */ s("label", { className: "text-sm text-dc-text-secondary", children: [
              i.label,
              i.key === "content" && /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted ml-1", children: "(only headers, lists and links)" })
            ] }),
            i.key === "content" ? /* @__PURE__ */ e(
              "textarea",
              {
                value: n[i.key] ?? i.defaultValue ?? "",
                onChange: (g) => d({
                  ...n,
                  [i.key]: g.target.value
                }),
                placeholder: i.placeholder,
                rows: 8,
                className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent font-mono resize-y bg-dc-surface text-dc-text"
              }
            ) : /* @__PURE__ */ e(
              "input",
              {
                type: "text",
                value: n[i.key] ?? i.defaultValue ?? "",
                onChange: (g) => d({
                  ...n,
                  [i.key]: g.target.value
                }),
                placeholder: i.placeholder,
                className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text"
              }
            ),
            i.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: i.description })
          ] }),
          i.type === "paletteColor" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: i.label }),
            /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-2", children: c?.colors.map((g, p) => {
              const b = (n[i.key] ?? i.defaultValue ?? 0) === p;
              return /* @__PURE__ */ e(
                "button",
                {
                  type: "button",
                  onClick: () => d({
                    ...n,
                    [i.key]: p
                  }),
                  className: `w-8 h-8 rounded border-2 transition-all duration-200 hover:scale-110 focus:outline-hidden focus:ring-2 focus:ring-dc-accent focus:ring-offset-1 ${b ? "ring-2 ring-offset-1 scale-110" : "hover:border-dc-text-muted"}`,
                  style: {
                    backgroundColor: g,
                    borderColor: b ? "var(--dc-primary)" : "var(--dc-border)"
                  },
                  title: `Color ${p + 1}: ${g}`
                },
                p
              );
            }) || [
              // Fallback if no palette available
              /* @__PURE__ */ e(
                "button",
                {
                  type: "button",
                  onClick: () => d({
                    ...n,
                    [i.key]: 0
                  }),
                  className: "w-8 h-8 rounded-sm border-2 ring-2 ring-offset-1",
                  style: {
                    backgroundColor: "#8884d8",
                    borderColor: "var(--dc-primary)",
                    boxShadow: "0 0 0 2px var(--dc-primary)"
                  },
                  title: "Default Color"
                },
                0
              )
            ] }),
            i.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: i.description })
          ] }),
          i.type === "number" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: i.label }),
            /* @__PURE__ */ e(
              "input",
              {
                type: "number",
                value: n[i.key] ?? i.defaultValue ?? 0,
                onChange: (g) => d({
                  ...n,
                  [i.key]: g.target.value === "" ? void 0 : Number(g.target.value)
                }),
                placeholder: i.placeholder,
                min: i.min,
                max: i.max,
                step: i.step,
                className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text"
              }
            ),
            i.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: i.description })
          ] }),
          i.type === "select" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: i.label }),
            /* @__PURE__ */ e(
              "select",
              {
                value: n[i.key] ?? i.defaultValue ?? "",
                onChange: (g) => d({
                  ...n,
                  [i.key]: g.target.value
                }),
                className: "w-full px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text",
                children: i.options?.map((g) => /* @__PURE__ */ e("option", { value: g.value, children: g.label }, g.value))
              }
            ),
            i.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: i.description })
          ] }),
          i.type === "color" && /* @__PURE__ */ s("div", { className: "space-y-1", children: [
            /* @__PURE__ */ e("label", { className: "text-sm text-dc-text-secondary", children: i.label }),
            /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
              /* @__PURE__ */ e(
                "input",
                {
                  type: "color",
                  value: n[i.key] ?? i.defaultValue ?? "#8884d8",
                  onChange: (g) => d({
                    ...n,
                    [i.key]: g.target.value
                  }),
                  className: "w-12 h-8 border border-dc-border rounded-sm cursor-pointer"
                }
              ),
              /* @__PURE__ */ e(
                "input",
                {
                  type: "text",
                  value: n[i.key] ?? i.defaultValue ?? "#8884d8",
                  onChange: (g) => d({
                    ...n,
                    [i.key]: g.target.value
                  }),
                  placeholder: i.placeholder || "#8884d8",
                  className: "flex-1 px-2 py-1 text-sm border border-dc-border rounded-sm focus:ring-dc-accent focus:border-dc-accent bg-dc-surface text-dc-text"
                }
              )
            ] }),
            i.description && /* @__PURE__ */ e("p", { className: "text-xs text-dc-text-muted", children: i.description })
          ] })
        ] }, i.key))
      ] })
    ] })
  ] });
}
const Ic = [
  {
    name: "Employee Count by Department",
    query: JSON.stringify({
      measures: ["Employees.count"],
      dimensions: ["Departments.name"],
      order: { "Employees.count": "desc" }
    }, null, 2)
  },
  {
    name: "Employee Hiring Trends",
    query: JSON.stringify({
      measures: ["Employees.count"],
      timeDimensions: [{
        dimension: "Employees.createdAt",
        granularity: "month"
      }],
      order: { "Employees.createdAt": "asc" }
    }, null, 2)
  },
  {
    name: "Department Budget Analysis",
    query: JSON.stringify({
      measures: ["Departments.totalBudget", "Departments.avgBudget"],
      dimensions: ["Departments.name"],
      order: { "Departments.totalBudget": "desc" }
    }, null, 2)
  },
  {
    name: "Daily Productivity Trends",
    query: JSON.stringify({
      measures: ["Productivity.avgLinesOfCode", "Productivity.totalPullRequests"],
      timeDimensions: [{
        dimension: "Productivity.date",
        granularity: "day"
      }],
      order: { "Productivity.date": "asc" }
    }, null, 2)
  },
  {
    name: "Happiness by Department",
    query: JSON.stringify({
      measures: ["Productivity.avgHappinessIndex", "Productivity.workingDaysCount"],
      dimensions: ["Departments.name"],
      order: { "Productivity.avgHappinessIndex": "desc" }
    }, null, 2)
  },
  {
    name: "Employee Salary Overview",
    query: JSON.stringify({
      measures: ["Employees.count", "Employees.avgSalary", "Employees.totalSalary"],
      dimensions: ["Employees.isActive"],
      order: { "Employees.avgSalary": "desc" }
    }, null, 2)
  }
];
function wn({
  isOpen: t,
  onClose: r,
  onSave: n,
  portlet: a,
  title: c,
  submitText: l,
  colorPalette: d
}) {
  const { cubeApi: h } = jt(), [o, u] = H(""), [m, x] = H(""), [f, S] = H("bar"), [T, D] = H([]), [k, A] = H(!1), [_, O] = H(null), [R, y] = H(""), [i, g] = H(null), [p, b] = H({ xAxis: [], yAxis: [], series: [] }), [w, v] = H({ showLegend: !0, showGrid: !0, showTooltip: !0, stacked: !1 }), [M, $] = H(!1), [C, L] = H(null), I = Te(null), K = br(f, Bt).skipQuery === !0, P = (ve) => {
  }, Ne = 5, ye = 4;
  Ce(() => {
    if (t) {
      if (a) {
        u(a.title);
        const ve = (() => {
          try {
            return JSON.stringify(JSON.parse(a.query), null, 2);
          } catch {
            return a.query;
          }
        })();
        x(ve), S(a.chartType), b(a.chartConfig || { xAxis: [], yAxis: [], series: [] }), v(a.displayConfig || {}), D(a.dashboardFilterMapping || []), y(ve), O({ isValid: !0, message: "Loaded query (assumed valid)" }), g(null), K || setTimeout(() => {
          me(ve, !0, !0);
        }, 100);
      } else
        u(""), x(""), S("bar"), b({ xAxis: [], yAxis: [], series: [] }), v({ showLegend: !0, showGrid: !0, showTooltip: !0, stacked: !1 }), D([]), y(""), O(null), g(null);
      A(!1);
    }
  }, [t, a]);
  const Ue = (ve) => {
    if (ve.preventDefault(), K) {
      if (!o.trim())
        return;
    } else {
      if (!o.trim() || !m.trim())
        return;
      if (xe || R === "" && m.trim() !== "") {
        alert("Please validate your query before saving.");
        return;
      }
      try {
        JSON.parse(m);
      } catch {
        alert("Invalid JSON in query. Please check your syntax.");
        return;
      }
    }
    const Be = K ? '{"measures":[]}' : m.trim();
    n(a ? {
      ...a,
      title: o.trim(),
      query: Be,
      chartType: f,
      chartConfig: Object.keys(p).length > 0 ? p : void 0,
      displayConfig: w,
      dashboardFilterMapping: T.length > 0 ? T : void 0,
      w: a.w || Ne,
      h: a.h || ye
    } : {
      title: o.trim(),
      query: Be,
      chartType: f,
      chartConfig: Object.keys(p).length > 0 ? p : void 0,
      displayConfig: w,
      dashboardFilterMapping: T.length > 0 ? T : void 0,
      w: Ne,
      h: ye
    });
  }, Q = (ve) => {
    x(ve), O(null), y(""), g(null), b({ xAxis: [], yAxis: [], series: [] });
  }, ue = (ve) => {
    x(ve), O(null), g(null), a || b({ xAxis: [], yAxis: [], series: [] });
  }, me = async (ve, Be = !1, U = !1) => {
    if (!ve.trim()) {
      Be || O({ isValid: !1, message: "Query cannot be empty" });
      return;
    }
    let fe;
    try {
      fe = JSON.parse(ve);
    } catch {
      Be || O({ isValid: !1, message: "Invalid JSON syntax" });
      return;
    }
    Be || (A(!0), O(null));
    try {
      const ae = await h.dryRun(fe);
      if (!ae.error && ae.queryType) {
        if (g(ae), !Be) {
          const ke = [];
          ae.pivotQuery?.query && (ae.pivotQuery.query.measures?.length > 0 && ke.push(`${ae.pivotQuery.query.measures.length} measure${ae.pivotQuery.query.measures.length > 1 ? "s" : ""}`), ae.pivotQuery.query.dimensions?.length > 0 && ke.push(`${ae.pivotQuery.query.dimensions.length} dimension${ae.pivotQuery.query.dimensions.length > 1 ? "s" : ""}`), ae.pivotQuery.query.filters?.length > 0 && ke.push(`${ae.pivotQuery.query.filters.length} filter${ae.pivotQuery.query.filters.length > 1 ? "s" : ""}`), ae.pivotQuery.query.timeDimensions?.length > 0 && ke.push(`${ae.pivotQuery.query.timeDimensions.length} time dimension${ae.pivotQuery.query.timeDimensions.length > 1 ? "s" : ""}`)), ae.complexity && ke.push(`${ae.complexity} complexity`), ae.sql?.sql && ke.push("SQL generated"), ae.cubesUsed?.length > 0 && ke.push(`Cubes: ${ae.cubesUsed.join(", ")}`);
          const Fe = ke.length > 0 ? `Query validated successfully (${ke.join(", ")})` : "Query validated successfully";
          O({ isValid: !0, message: Fe }), y(ve);
        }
        U || P(ae);
      } else if (!Be) {
        const ke = ae.error || "Query validation failed", Fe = ae.details ? ` - ${Array.isArray(ae.details) ? ae.details.join(", ") : ae.details}` : "";
        O({
          isValid: !1,
          message: ke + Fe
        }), y(ve);
      }
    } catch (ae) {
      Be || (O({
        isValid: !1,
        message: ae instanceof Error ? ae.message : "Network error during validation"
      }), y(ve));
    } finally {
      Be || A(!1);
    }
  }, J = async () => {
    await me(m);
  }, Y = () => {
    const ve = m ? (() => {
      try {
        return JSON.parse(m);
      } catch {
        return {};
      }
    })() : {};
    L(ve), $(!0);
  }, ge = (ve) => {
    if (ve?.preventDefault(), ve?.stopPropagation(), !I.current) return;
    const Be = I.current.getCurrentQuery(), U = I.current.getValidationState(), fe = I.current.getValidationResult(), ae = JSON.stringify(Be, null, 2);
    x(ae), U?.status === "valid" && fe ? (O({
      isValid: !0,
      message: "Query validated in Query Builder"
    }), y(ae), g(fe)) : (O(null), y(""), g(null)), $(!1);
  }, ee = () => {
    $(!1), L(null);
  }, j = () => {
    u(""), x(""), S("bar"), b({ xAxis: [], yAxis: [], series: [] }), v({ showLegend: !0, showGrid: !0, showTooltip: !0, stacked: !1 }), O(null), A(!1), y(""), g(null), $(!1), L(null), r();
  }, re = !!a, xe = m.trim() !== R.trim() && R !== "", $e = _?.isValid && m.trim() === R.trim(), Me = i?.pivotQuery?.query ? {
    dimensions: i.pivotQuery.query.dimensions || [],
    timeDimensions: i.pivotQuery.query.timeDimensions?.map((ve) => ve.dimension) || [],
    measures: i.pivotQuery.query.measures || []
  } : null, ze = M ? /* @__PURE__ */ s(Ie, { children: [
    /* @__PURE__ */ e(
      "button",
      {
        type: "button",
        onClick: ee,
        className: "px-4 py-2 text-sm font-medium text-dc-text-secondary bg-dc-surface border border-dc-border rounded-md hover:bg-dc-surface-hover focus:outline-none focus:ring-2 focus:ring-dc-primary",
        children: "Back to Form"
      }
    ),
    /* @__PURE__ */ e(
      "button",
      {
        type: "button",
        onClick: ge,
        className: "px-4 py-2 text-sm font-medium border border-transparent rounded-md focus:outline-none focus:ring-2 focus:ring-dc-accent",
        style: { backgroundColor: "var(--dc-primary)", color: "#ffffff" },
        title: "Apply query to form",
        onMouseEnter: (ve) => ve.currentTarget.style.backgroundColor = "var(--dc-primary-hover)",
        onMouseLeave: (ve) => ve.currentTarget.style.backgroundColor = "var(--dc-primary)",
        children: "Apply Query"
      }
    )
  ] }) : /* @__PURE__ */ s(Ie, { children: [
    /* @__PURE__ */ e(
      "button",
      {
        type: "button",
        onClick: j,
        className: "px-4 py-2 text-sm font-medium text-dc-text-secondary bg-dc-surface border border-dc-border rounded-md hover:bg-dc-surface-hover focus:outline-none focus:ring-2 focus:ring-dc-primary",
        children: "Cancel"
      }
    ),
    /* @__PURE__ */ e(
      "button",
      {
        type: "submit",
        form: "portlet-form",
        className: "px-4 py-2 text-sm font-medium border border-transparent rounded-md disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-dc-accent",
        style: { backgroundColor: "var(--dc-primary)", color: "#ffffff" },
        disabled: K ? !o.trim() : !o.trim() || !m.trim() || xe || R === "" && m.trim() !== "",
        title: !K && (xe || R === "" && m.trim() !== "") ? "Please validate your query before saving" : "",
        onMouseEnter: (ve) => ve.currentTarget.style.backgroundColor = "var(--dc-primary-hover)",
        onMouseLeave: (ve) => ve.currentTarget.style.backgroundColor = "var(--dc-primary)",
        children: l
      }
    )
  ] });
  return /* @__PURE__ */ e(
    Pr,
    {
      isOpen: t,
      onClose: j,
      title: M ? "Query Builder" : c,
      size: "fullscreen-mobile",
      footer: ze,
      noPadding: M,
      children: M ? /* @__PURE__ */ e(
        as,
        {
          ref: I,
          initialQuery: C,
          disableLocalStorage: !0,
          hideSettings: !0,
          className: "flex-1 w-full"
        }
      ) : /* @__PURE__ */ s("form", { id: "portlet-form", onSubmit: Ue, className: "space-y-4", children: [
        /* @__PURE__ */ s("div", { className: "flex flex-col lg:flex-row gap-4", children: [
          /* @__PURE__ */ s("div", { className: "flex-1 flex flex-col gap-4", children: [
            /* @__PURE__ */ s("div", { children: [
              /* @__PURE__ */ e("label", { className: "block text-sm font-semibold text-dc-text-secondary mb-1", children: "Title" }),
              /* @__PURE__ */ e(
                "input",
                {
                  type: "text",
                  value: o,
                  onChange: (ve) => u(ve.target.value),
                  className: "w-full px-3 py-2 border border-dc-border rounded-md bg-dc-surface text-dc-text focus:outline-none focus:ring-2 focus:ring-dc-primary focus:border-dc-primary",
                  placeholder: "Enter portlet title...",
                  required: !0
                }
              )
            ] }),
            /* @__PURE__ */ s("div", { children: [
              /* @__PURE__ */ e("label", { className: "block text-sm font-semibold text-dc-text-secondary mb-3", children: "Chart Type" }),
              /* @__PURE__ */ e(
                rs,
                {
                  selectedType: f,
                  onTypeChange: S
                }
              )
            ] }),
            !K && /* @__PURE__ */ s("div", { className: "flex-1 flex flex-col", children: [
              /* @__PURE__ */ s("div", { className: "flex justify-between items-center mb-1", children: [
                /* @__PURE__ */ e("label", { className: "block text-sm font-semibold text-dc-text-secondary", children: "Cube.js Query (JSON)" }),
                /* @__PURE__ */ e("div", { className: "flex items-center space-x-2", children: /* @__PURE__ */ e(
                  "button",
                  {
                    type: "button",
                    onClick: Y,
                    className: "text-xs px-2 py-1 text-dc-accent bg-dc-surface hover:bg-dc-accent-bg rounded-sm border border-dc-accent hover:opacity-80 focus:outline-none focus:ring-2 focus:ring-dc-accent",
                    children: "Edit in Query Builder"
                  }
                ) })
              ] }),
              /* @__PURE__ */ e(
                "textarea",
                {
                  value: m,
                  onChange: (ve) => ue(ve.target.value),
                  className: "flex-1 w-full min-h-64 px-3 py-2 border border-dc-border rounded-md bg-dc-surface text-dc-text focus:outline-none focus:ring-2 focus:ring-dc-primary focus:border-dc-primary font-mono text-xs resize-y",
                  placeholder: `{
  "measures": ["People.count"],
  "dimensions": ["People.active"]
}`,
                  required: !0
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ s("div", { className: "flex-1 flex flex-col", children: [
            /* @__PURE__ */ e("label", { className: "block text-sm font-semibold text-dc-text-secondary mb-1", children: K ? "Chart Configuration" : "Chart Axis Configuration" }),
            K ? /* @__PURE__ */ e("div", { className: "rounded-lg bg-dc-surface p-3 border border-dc-border", children: /* @__PURE__ */ e(
              Nn,
              {
                chartType: f,
                chartConfig: p,
                displayConfig: w,
                availableFields: null,
                colorPalette: d,
                onChartConfigChange: b,
                onDisplayConfigChange: v
              }
            ) }) : !i || !$e ? /* @__PURE__ */ e("div", { className: "flex-1 flex items-center justify-center border-2 border-dashed border-dc-border rounded-lg bg-dc-surface-secondary", children: /* @__PURE__ */ s("div", { className: "text-center text-dc-text-muted", children: [
              /* @__PURE__ */ e("svg", { className: "h-8 w-8 mx-auto mb-2", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" }) }),
              /* @__PURE__ */ e("p", { className: "text-sm", children: "Validate query first to configure chart axes" })
            ] }) }) : /* @__PURE__ */ e("div", { className: "rounded-lg bg-dc-surface p-3 border border-dc-border", children: /* @__PURE__ */ e(
              Nn,
              {
                chartType: f,
                chartConfig: p,
                displayConfig: w,
                availableFields: Me,
                colorPalette: d,
                onChartConfigChange: b,
                onDisplayConfigChange: v
              }
            ) })
          ] })
        ] }),
        !K && (xe || R === "" && m.trim() !== "" || _ && m.trim() === R.trim() && _.message !== "Loaded query (assumed valid)") && /* @__PURE__ */ e("div", { className: `rounded-lg p-4 ${_?.isValid && m.trim() === R.trim() ? "bg-dc-success-bg" : _ && !_.isValid ? "bg-dc-error-bg" : xe ? "bg-dc-warning-bg" : "bg-dc-surface-secondary"}`, children: /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ s("div", { className: "flex items-center space-x-3", children: [
            /* @__PURE__ */ e("div", { className: `w-2 h-2 rounded-full ${_?.isValid && m.trim() === R.trim() ? "bg-dc-success" : _ && !_.isValid ? "bg-dc-error" : xe ? "bg-dc-warning" : "bg-dc-muted"}` }),
            /* @__PURE__ */ s("div", { children: [
              /* @__PURE__ */ e("h3", { className: `text-sm font-medium ${_?.isValid && m.trim() === R.trim() ? "text-dc-success" : _ && !_.isValid ? "text-dc-error" : xe ? "text-dc-warning" : "text-dc-text-secondary"}`, children: _?.isValid && m.trim() === R.trim() ? "Query validated successfully" : _ && !_.isValid ? "Query validation failed" : xe ? "Query modified - validation required" : "Query validation required" }),
              _ && /* @__PURE__ */ e("p", { className: `text-xs mt-1 ${_.isValid ? "text-dc-success" : "text-dc-error"}`, children: _.message })
            ] })
          ] }),
          /* @__PURE__ */ e(
            "button",
            {
              type: "button",
              onClick: J,
              disabled: k || !m.trim(),
              className: `px-3 py-1.5 text-sm font-medium rounded-md transition-colors flex items-center space-x-1.5 ${_?.isValid && m.trim() === R.trim() ? "bg-dc-success text-white hover:opacity-80" : _ && !_.isValid ? "bg-dc-error text-white hover:opacity-80" : "bg-dc-primary text-white hover:bg-dc-primary-hover"} disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-dc-primary`,
              children: k ? /* @__PURE__ */ s(Ie, { children: [
                /* @__PURE__ */ s("svg", { className: "animate-spin h-4 w-4", fill: "none", viewBox: "0 0 24 24", children: [
                  /* @__PURE__ */ e("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }),
                  /* @__PURE__ */ e("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })
                ] }),
                /* @__PURE__ */ e("span", { children: "Validating" })
              ] }) : _?.isValid && m.trim() === R.trim() ? /* @__PURE__ */ s(Ie, { children: [
                /* @__PURE__ */ e("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" }) }),
                /* @__PURE__ */ e("span", { children: "Validated" })
              ] }) : /* @__PURE__ */ s(Ie, { children: [
                /* @__PURE__ */ e("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" }) }),
                /* @__PURE__ */ e("span", { children: "Validate" })
              ] })
            }
          )
        ] }) }),
        !re && /* @__PURE__ */ s("div", { children: [
          /* @__PURE__ */ e("label", { className: "block text-sm text-dc-text-muted mb-2", children: "Sample Queries (click to use)" }),
          /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-2 mb-2", children: Ic.map((ve, Be) => /* @__PURE__ */ e(
            "button",
            {
              type: "button",
              onClick: () => Q(ve.query),
              className: "px-2 py-1 text-xs text-dc-text-secondary bg-dc-surface-secondary border border-dc-border rounded-sm cursor-pointer transition-all duration-200 ease-in-out hover:bg-dc-surface-hover hover:border-dc-border m-0.5",
              children: ve.name
            },
            Be
          )) })
        ] })
      ] })
    }
  );
}
function kn({
  isOpen: t,
  onClose: r,
  onSave: n,
  portlet: a,
  initialData: c,
  title: l,
  submitText: d,
  colorPalette: h
}) {
  const o = Te(null), [u, m] = H(""), x = lt.useMemo(() => {
    if (a?.query)
      try {
        return JSON.parse(a.query);
      } catch {
        return;
      }
  }, [a?.query]), f = lt.useMemo(() => {
    if (a)
      return {
        chartType: a.chartType,
        chartConfig: a.chartConfig,
        displayConfig: a.displayConfig
      };
  }, [a]);
  Ce(() => {
    t && m(a?.title || "");
  }, [t, a]);
  const S = F(() => {
    if (!u.trim()) {
      alert("Please enter a title for the portlet.");
      return;
    }
    const k = o.current?.getCurrentQuery(), A = o.current?.getChartConfig();
    if (!k) {
      alert("Please configure a query before saving.");
      return;
    }
    if (!(k.measures && k.measures.length > 0 || k.dimensions && k.dimensions.length > 0 || k.timeDimensions && k.timeDimensions.length > 0)) {
      alert("Please add at least one metric or breakdown to your query.");
      return;
    }
    const O = {
      ...a || {},
      title: u.trim(),
      query: JSON.stringify(k),
      chartType: A?.chartType || "line",
      chartConfig: A?.chartConfig || {},
      displayConfig: A?.displayConfig || {},
      // Preserve existing position or use defaults for new portlets
      w: a?.w || 5,
      h: a?.h || 4
    };
    n(O), r();
  }, [u, a, n, r]), T = F(() => {
    r();
  }, [r]);
  return /* @__PURE__ */ e(
    Pr,
    {
      isOpen: t,
      onClose: r,
      title: l,
      size: "fullscreen-mobile",
      showCloseButton: !0,
      closeOnBackdropClick: !1,
      closeOnEscape: !0,
      noPadding: !0,
      footer: /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e(
          "button",
          {
            type: "button",
            onClick: T,
            className: "px-4 py-2 text-sm font-medium text-dc-text-secondary hover:text-dc-text bg-dc-surface border border-dc-border rounded-md hover:bg-dc-surface-hover transition-colors",
            children: "Cancel"
          }
        ),
        /* @__PURE__ */ e(
          "button",
          {
            type: "button",
            onClick: S,
            className: "px-4 py-2 text-sm font-medium text-white bg-dc-accent hover:bg-dc-accent-hover rounded-md transition-colors",
            children: d
          }
        )
      ] }),
      children: /* @__PURE__ */ s("div", { className: "flex flex-col h-full", children: [
        /* @__PURE__ */ e("div", { className: "shrink-0 px-4 py-3 border-b border-dc-border bg-dc-surface-secondary", children: /* @__PURE__ */ s("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ e("label", { htmlFor: "portlet-title", className: "text-sm font-medium text-dc-text-secondary shrink-0", children: "Title" }),
          /* @__PURE__ */ e(
            "input",
            {
              id: "portlet-title",
              type: "text",
              value: u,
              onChange: (k) => m(k.target.value),
              placeholder: "Enter portlet title...",
              autoComplete: "off",
              className: "flex-1 px-3 py-1.5 text-sm bg-dc-surface border border-dc-border rounded-md text-dc-text placeholder-dc-text-muted focus:outline-none focus:ring-2 focus:ring-dc-accent focus:border-transparent",
              autoFocus: !0
            }
          )
        ] }) }),
        /* @__PURE__ */ e("div", { className: "flex-1 min-h-0", children: /* @__PURE__ */ e(
          Qr,
          {
            ref: o,
            maxHeight: "100%",
            initialQuery: x,
            initialChartConfig: f,
            initialData: c,
            colorPalette: h,
            disableLocalStorage: !0,
            className: "h-full"
          }
        ) })
      ] })
    }
  );
}
function $c({
  isOpen: t,
  onClose: r,
  dashboardFilters: n = [],
  currentMapping: a = [],
  onSave: c,
  portletTitle: l
}) {
  const [d, h] = H(a);
  Ce(() => {
    h(a);
  }, [a, t]);
  const o = (f) => {
    h((S) => S.includes(f) ? S.filter((T) => T !== f) : [...S, f]);
  }, u = () => {
    c(d), r();
  }, m = () => {
    h(a), r();
  }, x = (f) => {
    if (!f.filter) return "";
    if ("member" in f.filter && f.filter.member) {
      const S = f.filter.values || [], T = S.length > 0 ? S.join(", ") : "no value";
      return `${f.filter.member} ${f.filter.operator} ${T}`;
    }
    if ("type" in f.filter && f.filter.type) {
      const S = f.filter.filters?.length || 0;
      return `${f.filter.type.toUpperCase()} group with ${S} filter${S !== 1 ? "s" : ""}`;
    }
    return "Complex filter";
  };
  return t ? /* @__PURE__ */ e("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50", onClick: m, children: /* @__PURE__ */ s(
    "div",
    {
      className: "bg-dc-surface border border-dc-border rounded-lg max-w-2xl w-full mx-4 max-h-[80vh] flex flex-col",
      style: { boxShadow: "var(--dc-shadow-lg)" },
      onClick: (f) => f.stopPropagation(),
      children: [
        /* @__PURE__ */ s("div", { className: "px-6 py-4 border-b border-dc-border bg-dc-surface-secondary rounded-t-lg", children: [
          /* @__PURE__ */ e("h2", { className: "text-lg font-semibold text-dc-text", children: "Configure Dashboard Filters" }),
          /* @__PURE__ */ s("p", { className: "text-sm text-dc-text-secondary mt-1", children: [
            'Choose which dashboard filters apply to "',
            l,
            '"'
          ] })
        ] }),
        /* @__PURE__ */ e("div", { className: "flex-1 overflow-y-auto px-6 py-4", children: n.length === 0 ? /* @__PURE__ */ s("div", { className: "text-center py-8 text-dc-text-muted", children: [
          /* @__PURE__ */ e(
            "svg",
            {
              className: "mx-auto h-12 w-12 mb-3",
              fill: "none",
              viewBox: "0 0 24 24",
              stroke: "currentColor",
              children: /* @__PURE__ */ e(
                "path",
                {
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: 1.5,
                  d: "M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
                }
              )
            }
          ),
          /* @__PURE__ */ e("p", { className: "text-sm font-medium", children: "No dashboard filters available" }),
          /* @__PURE__ */ e("p", { className: "text-xs mt-1", children: "Add filters at the dashboard level first" })
        ] }) : /* @__PURE__ */ s("div", { className: "space-y-3", children: [
          /* @__PURE__ */ s("div", { className: "flex items-center justify-between mb-4 pb-2 border-b border-dc-border", children: [
            /* @__PURE__ */ e("span", { className: "text-sm font-medium text-dc-text", children: "Available Filters" }),
            /* @__PURE__ */ s("span", { className: "text-xs text-dc-text-secondary", children: [
              d.length,
              " of ",
              n.length,
              " selected"
            ] })
          ] }),
          n.map((f) => {
            const S = d.includes(f.id);
            return /* @__PURE__ */ s(
              "label",
              {
                className: `flex items-start p-3 rounded-md border cursor-pointer transition-colors ${S ? "border-dc-primary bg-dc-surface-secondary" : "border-dc-border hover:bg-dc-surface-hover"}`,
                children: [
                  /* @__PURE__ */ e(
                    "input",
                    {
                      type: "checkbox",
                      checked: S,
                      onChange: () => o(f.id),
                      className: "mt-0.5 mr-3 h-4 w-4 rounded border-dc-border focus:ring-2 focus:ring-dc-primary",
                      style: {
                        accentColor: "var(--dc-primary)"
                      }
                    }
                  ),
                  /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                    /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
                      /* @__PURE__ */ e("span", { className: "font-medium text-sm text-dc-text truncate", children: f.label }),
                      S && /* @__PURE__ */ e(
                        "span",
                        {
                          className: "px-2 py-0.5 text-xs rounded-full",
                          style: {
                            backgroundColor: "var(--dc-primary)",
                            color: "white"
                          },
                          children: "Applied"
                        }
                      )
                    ] }),
                    /* @__PURE__ */ e("div", { className: "mt-1 text-xs text-dc-text-secondary break-words", children: x(f) })
                  ] })
                ]
              },
              f.id
            );
          })
        ] }) }),
        /* @__PURE__ */ s("div", { className: "px-6 py-4 border-t border-dc-border bg-dc-surface-secondary rounded-b-lg flex justify-end gap-3", children: [
          /* @__PURE__ */ e(
            "button",
            {
              onClick: m,
              className: "px-4 py-2 text-sm font-medium rounded-md border border-dc-border bg-dc-surface hover:bg-dc-surface-hover transition-colors text-dc-text",
              children: "Cancel"
            }
          ),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: u,
              className: "px-4 py-2 text-sm font-medium rounded-md text-white transition-colors",
              style: {
                backgroundColor: "var(--dc-primary)"
              },
              children: "Apply Filters"
            }
          )
        ] })
      ]
    }
  ) }) : null;
}
const Fc = z("chevronDown"), Sr = z("close"), Lc = ({
  fieldName: t,
  operator: r,
  values: n,
  onValuesChange: a,
  schema: c
}) => {
  const l = Zt[r], [d, h] = H(!1), [o, u] = H(""), [m, x] = H(!1), f = Te(null), S = Te(""), T = On(o, 300), D = Oe(() => c ? c.cubes.some(
    (I) => I.dimensions.some((E) => E.name === t)
  ) : !1, [c, t]), k = Oe(() => c ? c.cubes.some(
    (I) => I.dimensions.some((E) => E.name === t && E.type === "time")
  ) : !1, [c, t]), A = Oe(
    () => ["equals", "notEquals", "in", "notIn"].includes(r) && D && !k,
    [r, D, k]
  ), _ = A, {
    values: O,
    loading: R,
    error: y,
    searchValues: i
  } = Mn(t, A);
  Ce(() => {
    const I = (E) => {
      f.current && !f.current.contains(E.target) && h(!1);
    };
    return document.addEventListener("mousedown", I), () => document.removeEventListener("mousedown", I);
  }, []), Ce(() => {
    d && A && i && (i("", !0), x(!0), S.current = "");
  }, [d, A, i]), Ce(() => {
    m && A && i && T !== S.current && (S.current = T, i(T));
  }, [T, m, A, i]);
  const g = F(() => {
    const I = !d;
    h(I), I || (u(""), S.current = "");
  }, [d]), p = F((I) => {
    const E = I.target.value;
    u(E);
  }, []), b = F((I) => {
    l.supportsMultipleValues ? n.includes(I) || a([...n, I]) : (a([I]), h(!1)), u("");
  }, [l.supportsMultipleValues, n, a]), w = F((I) => {
    a(n.filter((E) => E !== I));
  }, [n, a]), v = F((I) => {
    const E = I.target.value;
    if (l.valueType === "number") {
      const K = parseFloat(E);
      isNaN(K) ? (E === "" || E === "-") && a([]) : a([K]);
    } else
      a(E ? [E] : []);
  }, [l.valueType, a]), M = F((I) => {
    const E = I.target.value;
    if (r === "inDateRange") {
      const K = n.length >= 2 ? n : ["", ""];
      a([E, K[1]]);
    } else
      a(E ? [E] : []);
  }, [r, n, a]), $ = F((I) => {
    const E = I.target.value, K = n.length >= 2 ? n : ["", ""];
    a([K[0], E]);
  }, [n, a]), C = F((I) => {
    const E = parseFloat(I.target.value), K = n.length >= 2 ? n : ["", ""], P = [isNaN(E) ? I.target.value === "" ? "" : K[0] : E, K[1]];
    a(P.filter((Ne) => Ne !== ""));
  }, [n, a]), L = F((I) => {
    const E = parseFloat(I.target.value), K = n.length >= 2 ? n : ["", ""], P = [K[0], isNaN(E) ? I.target.value === "" ? "" : K[1] : E];
    a(P.filter((Ne) => Ne !== ""));
  }, [n, a]);
  return l.requiresValues ? r === "inDateRange" ? /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
    /* @__PURE__ */ e(
      "input",
      {
        type: "date",
        value: n[0] || "",
        onChange: M,
        className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
      }
    ),
    /* @__PURE__ */ e("span", { className: "text-sm text-dc-text-muted", children: "to" }),
    /* @__PURE__ */ e(
      "input",
      {
        type: "date",
        value: n[1] || "",
        onChange: $,
        className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
      }
    )
  ] }) : r === "between" || r === "notBetween" ? /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
    /* @__PURE__ */ e(
      "input",
      {
        type: "number",
        value: n[0] !== void 0 && n[0] !== null ? n[0] : "",
        onChange: C,
        placeholder: "Min",
        className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
      }
    ),
    /* @__PURE__ */ e("span", { className: "text-sm text-dc-text-muted", children: "to" }),
    /* @__PURE__ */ e(
      "input",
      {
        type: "number",
        value: n[1] !== void 0 && n[1] !== null ? n[1] : "",
        onChange: L,
        placeholder: "Max",
        className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
      }
    )
  ] }) : l.valueType === "date" ? /* @__PURE__ */ e(
    "input",
    {
      type: "date",
      value: n[0] || "",
      onChange: M,
      className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
    }
  ) : l.valueType === "number" ? /* @__PURE__ */ e(
    "input",
    {
      type: "number",
      value: n[0] !== void 0 && n[0] !== null ? n[0] : "",
      onChange: v,
      placeholder: "Enter number",
      className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
    }
  ) : k && ["equals", "notEquals", "in", "notIn"].includes(r) ? l.supportsMultipleValues ? /* @__PURE__ */ s("div", { className: "space-y-2 min-w-0 max-w-full", children: [
    n.length > 0 && /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-1 max-w-full", children: n.map((I, E) => /* @__PURE__ */ s(
      "div",
      {
        className: "inline-flex items-center bg-dc-time-dimension text-dc-time-dimension text-xs px-2 py-1 rounded-sm border border-dc-time-dimension",
        children: [
          /* @__PURE__ */ e("span", { className: "mr-1", children: String(I) }),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => w(I),
              className: "text-dc-accent hover:text-dc-accent focus:outline-hidden",
              children: /* @__PURE__ */ e(Sr, { className: "w-3 h-3" })
            }
          )
        ]
      },
      E
    )) }),
    /* @__PURE__ */ e(
      "input",
      {
        type: "date",
        onChange: (I) => {
          I.target.value && !n.includes(I.target.value) && (a([...n, I.target.value]), I.target.value = "");
        },
        className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent",
        placeholder: "Add date..."
      }
    )
  ] }) : /* @__PURE__ */ e(
    "input",
    {
      type: "date",
      value: n[0] || "",
      onChange: M,
      className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
    }
  ) : _ ? /* @__PURE__ */ s("div", { className: "relative min-w-0 max-w-full", ref: f, children: [
    l.supportsMultipleValues && n.length > 0 && /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-1 mb-2 max-w-full", children: n.map((I, E) => /* @__PURE__ */ s(
      "div",
      {
        className: "inline-flex items-center bg-dc-time-dimension text-dc-time-dimension text-xs px-2 py-1 rounded-sm border border-dc-time-dimension",
        children: [
          /* @__PURE__ */ e("span", { className: "mr-1", children: String(I) }),
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => w(I),
              className: "text-dc-accent hover:text-dc-accent focus:outline-hidden",
              children: /* @__PURE__ */ e(Sr, { className: "w-3 h-3" })
            }
          )
        ]
      },
      E
    )) }),
    !l.supportsMultipleValues && n.length > 0 && /* @__PURE__ */ e("div", { className: "mb-2", children: /* @__PURE__ */ s("div", { className: "inline-flex items-center bg-dc-time-dimension text-dc-time-dimension text-xs px-2 py-1 rounded-sm border border-dc-time-dimension", children: [
      /* @__PURE__ */ e("span", { className: "mr-1", children: String(n[0]) }),
      /* @__PURE__ */ e(
        "button",
        {
          onClick: () => a([]),
          className: "text-dc-accent hover:text-dc-accent focus:outline-hidden",
          children: /* @__PURE__ */ e(Sr, { className: "w-3 h-3" })
        }
      )
    ] }) }),
    /* @__PURE__ */ s(
      "button",
      {
        onClick: g,
        className: "w-full text-left text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent flex items-center justify-between min-w-0",
        children: [
          /* @__PURE__ */ e("span", { className: "text-dc-text-muted truncate", children: R && !m ? "Loading values..." : "Select value..." }),
          /* @__PURE__ */ e(Fc, { className: "w-4 h-4 text-dc-text-muted" })
        ]
      }
    ),
    d && /* @__PURE__ */ s("div", { className: "absolute z-30 left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-60 overflow-y-auto", children: [
      /* @__PURE__ */ e("div", { className: "p-2 border-b border-dc-border", children: /* @__PURE__ */ e(
        "input",
        {
          type: "text",
          value: o,
          onChange: p,
          placeholder: "Search values...",
          className: "w-full text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent",
          autoFocus: !0
        }
      ) }),
      /* @__PURE__ */ e("div", { className: "max-h-48 overflow-y-auto", children: R ? /* @__PURE__ */ e("div", { className: "p-2 text-sm text-dc-text-muted", children: o ? "Searching..." : "Loading values..." }) : y ? /* @__PURE__ */ s("div", { className: "p-2 text-sm text-dc-error", children: [
        "Error loading values: ",
        y
      ] }) : O.length === 0 ? /* @__PURE__ */ e("div", { className: "p-2 text-sm text-dc-text-muted", children: o ? "No matching values" : "No values available" }) : O.map((I, E) => {
        const K = n.includes(I);
        return /* @__PURE__ */ s(
          "button",
          {
            onClick: () => b(I),
            className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover ${K ? "bg-dc-accent-bg text-dc-accent" : "text-dc-text-secondary"}`,
            children: [
              String(I),
              K && /* @__PURE__ */ e("span", { className: "float-right text-dc-accent", children: "✓" })
            ]
          },
          `${I}-${E}`
        );
      }) })
    ] })
  ] }) : /* @__PURE__ */ e(
    "input",
    {
      type: "text",
      value: n[0] !== void 0 && n[0] !== null ? n[0] : "",
      onChange: v,
      placeholder: `Enter ${l.valueType} value`,
      className: "text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
    }
  ) : /* @__PURE__ */ e("div", { className: "text-sm text-dc-text-muted italic", children: "No value required" });
};
function Xt(t) {
  return "member" in t && "operator" in t && "values" in t;
}
function er(t) {
  return "type" in t && "filters" in t;
}
function jc(t) {
  return er(t) && t.type === "and";
}
function Pc(t) {
  return er(t) && t.type === "or";
}
function Ar(t, r) {
  const n = [];
  if (t.cubes.forEach((l) => {
    n.push(...l.measures), n.push(...l.dimensions);
  }), !r)
    return n.sort((l, d) => l.name.localeCompare(d.name));
  const a = /* @__PURE__ */ new Set();
  return r.measures && r.measures.forEach((l) => a.add(l)), r.dimensions && r.dimensions.forEach((l) => a.add(l)), r.timeDimensions && r.timeDimensions.forEach((l) => a.add(l.dimension)), n.filter((l) => a.has(l.name)).sort((l, d) => l.name.localeCompare(d.name));
}
function Ur(t) {
  const r = [];
  return t.cubes.forEach((n) => {
    r.push(...n.measures), r.push(...n.dimensions);
  }), r.sort((n, a) => n.name.localeCompare(a.name));
}
function Bc(t, r) {
  const n = Ur(t);
  if (!r)
    return {
      queryFields: [],
      allFields: n
    };
  const a = /* @__PURE__ */ new Set();
  return r.measures && r.measures.forEach((l) => a.add(l)), r.dimensions && r.dimensions.forEach((l) => a.add(l)), r.timeDimensions && r.timeDimensions.forEach((l) => a.add(l.dimension)), {
    queryFields: n.filter((l) => a.has(l.name)),
    allFields: n
  };
}
function Cn(t) {
  const r = [];
  for (const [n, a] of Object.entries(Zt))
    a.fieldTypes.includes(t) && r.push({
      operator: n,
      label: a.label
    });
  return r;
}
function qc(t, r) {
  for (const n of r.cubes) {
    const a = n.measures.find((l) => l.name === t);
    if (a) return a.type;
    const c = n.dimensions.find((l) => l.name === t);
    if (c) return c.type;
  }
  return "string";
}
function Vc(t) {
  let r = 0;
  const n = (a) => {
    Xt(a) ? r++ : er(a) && a.filters.forEach(n);
  };
  return t.forEach(n), r;
}
function hr(t, r = "equals", n = []) {
  return {
    member: t,
    operator: r,
    values: n
  };
}
function ct(t = []) {
  return {
    type: "and",
    filters: t
  };
}
function ht(t = []) {
  return {
    type: "or",
    filters: t
  };
}
function kt(t, r) {
  const n = {
    today: "today",
    yesterday: "yesterday",
    this_week: "this week",
    this_month: "this month",
    this_quarter: "this quarter",
    this_year: "this year",
    last_7_days: "last 7 days",
    last_30_days: "last 30 days",
    last_week: "last week",
    last_month: "last month",
    last_quarter: "last quarter",
    last_year: "last year",
    last_12_months: "last 12 months"
  };
  if (t.startsWith("last_n_") && r !== void 0 && r > 0) {
    const a = t.replace("last_n_", ""), c = a.slice(0, -1);
    return r === 1 ? `last ${c}` : `last ${r} ${a}`;
  }
  return n[t] || t;
}
function Ct(t) {
  return t.startsWith("last_n_");
}
function $r(t) {
  return t.toISOString().split("T")[0];
}
function cs(t, r = "w-4 h-4") {
  const n = qt(t);
  return /* @__PURE__ */ e(n, { className: r });
}
const Hc = z("close"), zc = z("filter"), _r = z("chevronDown"), Qc = z("search"), Uc = z("dimension"), Gc = z("timeDimension"), Gr = ({
  filter: t,
  index: r,
  onFilterChange: n,
  onFilterRemove: a,
  schema: c,
  query: l,
  hideFieldSelector: d = !1,
  hideOperatorSelector: h = !1,
  hideRemoveButton: o = !1
}) => {
  const [u, m] = H(!1), [x, f] = H(!1), [S, T] = H(!1), [D, k] = H(""), A = Te(null), _ = Te(null), [O, R] = H("this_month"), [y, i] = H({
    startDate: $r(/* @__PURE__ */ new Date()),
    endDate: $r(/* @__PURE__ */ new Date())
  }), [g, p] = H(1);
  Ce(() => {
    const j = (re) => {
      A.current && !A.current.contains(re.target) && (m(!1), f(!1));
    };
    return document.addEventListener("mousedown", j), () => document.removeEventListener("mousedown", j);
  }, []);
  const b = () => {
    f(!1);
    const j = !u;
    m(j), k(""), j && setTimeout(() => _.current?.focus(), 50);
  }, w = () => {
    m(!1), f(!x);
  }, v = c ? Ur(c) : [], { queryFields: M } = c ? Bc(c, l) : { queryFields: [] }, $ = v.find((j) => j.name === t.member), C = $ ? $.type : "string", L = Cn(C), I = C === "time" && t.operator === "inDateRange";
  if (Ce(() => {
    if (!(!I || !t.dateRange))
      if (Array.isArray(t.dateRange))
        R("custom"), i({
          startDate: t.dateRange[0] || "",
          endDate: t.dateRange[1] || t.dateRange[0] || ""
        });
      else {
        const j = t.dateRange.match(/^last (\d+) (days|weeks|months|quarters|years)$/);
        if (j) {
          const [, re, xe] = j;
          R(`last_n_${xe === "days" ? "days" : xe === "weeks" ? "weeks" : xe === "months" ? "months" : xe === "quarters" ? "quarters" : "years"}`), p(parseInt(re) || 1);
        } else {
          let re = !1;
          for (const xe of bt)
            if (xe.value !== "custom" && !Ct(xe.value) && kt(xe.value) === t.dateRange) {
              R(xe.value), re = !0;
              break;
            }
          re || R("custom");
        }
      }
  }, [t.dateRange, I]), !c)
    return /* @__PURE__ */ e("div", { className: "text-sm text-dc-text-muted", children: "Schema not loaded" });
  const E = (j) => {
    if (!D) return j;
    const re = D.toLowerCase();
    return j.filter(
      (xe) => xe.name.toLowerCase().includes(re) || xe.title.toLowerCase().includes(re) || xe.shortTitle.toLowerCase().includes(re)
    );
  }, K = E(M), P = E(v), Ne = (j) => j.type === "time" ? /* @__PURE__ */ e(Gc, { className: "w-3 h-3 text-dc-accent" }) : ["count", "sum", "avg", "min", "max", "countDistinct", "countDistinctApprox", "runningTotal", "calculated", "number"].includes(j.type) ? cs(j.type, "w-3 h-3 text-dc-warning") : /* @__PURE__ */ e(Uc, { className: "w-3 h-3 text-dc-success" }), ye = (j) => j.type === "time" ? /* @__PURE__ */ e("span", { className: "text-xs bg-dc-time-dimension text-dc-time-dimension px-1.5 py-0.5 rounded-sm", children: "T" }) : ["count", "sum", "avg", "min", "max", "countDistinct", "number"].includes(j.type) ? /* @__PURE__ */ e("span", { className: "text-xs bg-dc-measure text-dc-measure px-1.5 py-0.5 rounded-sm", children: "M" }) : /* @__PURE__ */ e("span", { className: "text-xs bg-dc-dimension text-dc-dimension px-1.5 py-0.5 rounded-sm", children: "D" }), Ue = (j) => {
    const re = qc(j, c), $e = Cn(re)[0]?.operator || "equals";
    n(r, {
      member: j,
      operator: $e,
      values: [],
      dateRange: void 0
      // Reset dateRange when field changes
    }), m(!1);
  }, Q = (j) => {
    n(r, {
      ...t,
      operator: j,
      values: [],
      // Reset values when operator changes
      dateRange: void 0
      // Reset dateRange when operator changes
    }), f(!1);
  }, ue = (j) => {
    n(r, {
      ...t,
      values: j
    });
  }, me = (j) => {
    n(r, {
      ...t,
      dateRange: j
    });
  }, J = (j) => {
    if (T(!1), j === "custom") {
      if (y.startDate && y.endDate) {
        const re = y.startDate === y.endDate ? y.startDate : [y.startDate, y.endDate];
        me(re);
      }
    } else if (Ct(j)) {
      const re = kt(j, g);
      me(re);
    } else {
      const re = kt(j);
      me(re);
    }
    R(j);
  }, Y = (j, re) => {
    const xe = { ...y, [j]: re };
    if (i(xe), O === "custom" && xe.startDate) {
      const $e = !xe.endDate || xe.startDate === xe.endDate ? xe.startDate : [xe.startDate, xe.endDate];
      me($e);
    }
  }, ge = (j) => {
    if (p(j), Ct(O)) {
      const re = kt(O, j);
      me(re);
    }
  }, ee = bt.find((j) => j.value === O)?.label || "Custom";
  return /* @__PURE__ */ e("div", { ref: A, className: "bg-dc-surface border border-dc-border rounded-lg p-3", children: /* @__PURE__ */ s("div", { className: "flex flex-col sm:flex-row sm:items-center gap-3 min-w-0 max-w-full", children: [
    !d && /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
      /* @__PURE__ */ e(zc, { className: "w-4 h-4 text-dc-text-muted shrink-0" }),
      /* @__PURE__ */ s("div", { className: "relative flex-1 min-w-0", children: [
        /* @__PURE__ */ s(
          "button",
          {
            onClick: b,
            className: "w-full flex items-center justify-between text-left text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent min-w-0",
            children: [
              /* @__PURE__ */ e("span", { className: "truncate", children: $ ? /* @__PURE__ */ e("span", { className: "font-medium", children: $.name }) : /* @__PURE__ */ e("span", { className: "text-dc-text-muted", children: "Select field..." }) }),
              /* @__PURE__ */ e(_r, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-1 transition-transform ${u ? "transform rotate-180" : ""}` })
            ]
          }
        ),
        u && /* @__PURE__ */ s("div", { className: "absolute z-20 left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-80 overflow-hidden", children: [
          /* @__PURE__ */ e("div", { className: "p-2 border-b border-dc-border", children: /* @__PURE__ */ s("div", { className: "relative", children: [
            /* @__PURE__ */ e(Qc, { className: "w-4 h-4 absolute left-2 top-1/2 transform -translate-y-1/2 text-dc-text-muted" }),
            /* @__PURE__ */ e(
              "input",
              {
                ref: _,
                type: "text",
                placeholder: "Search fields...",
                value: D,
                onChange: (j) => k(j.target.value),
                className: "w-full pl-8 pr-3 py-1.5 text-sm border border-dc-border rounded-sm bg-dc-surface text-dc-text focus:ring-1 focus:ring-dc-accent focus:border-dc-accent"
              }
            )
          ] }) }),
          /* @__PURE__ */ s("div", { className: "max-h-60 overflow-y-auto", children: [
            K.length > 0 && /* @__PURE__ */ s("div", { children: [
              /* @__PURE__ */ s("div", { className: "px-3 py-1.5 text-xs font-medium text-dc-text-muted bg-dc-surface-secondary border-b border-dc-border", children: [
                "Fields in Query (",
                K.length,
                ")"
              ] }),
              K.map((j) => /* @__PURE__ */ e(
                "button",
                {
                  onClick: () => Ue(j.name),
                  className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-none focus:bg-dc-surface-hover ${j.name === t.member ? "bg-dc-accent-bg text-dc-accent" : "text-dc-text-secondary"}`,
                  children: /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
                    Ne(j),
                    /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                      /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ e("span", { className: "font-medium truncate", children: j.name }),
                        ye(j)
                      ] }),
                      j.title !== j.name && /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: j.title })
                    ] })
                  ] })
                },
                `query-${j.name}`
              ))
            ] }),
            /* @__PURE__ */ s("div", { children: [
              K.length > 0 && /* @__PURE__ */ s("div", { className: "px-3 py-1.5 text-xs font-medium text-dc-text-muted bg-dc-surface-secondary border-b border-dc-border", children: [
                "All Available Fields (",
                P.length,
                ")"
              ] }),
              P.map((j) => /* @__PURE__ */ e(
                "button",
                {
                  onClick: () => Ue(j.name),
                  className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-none focus:bg-dc-surface-hover ${j.name === t.member ? "bg-dc-accent-bg text-dc-accent" : "text-dc-text-secondary"}`,
                  children: /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
                    Ne(j),
                    /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                      /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ e("span", { className: "font-medium truncate", children: j.name }),
                        ye(j)
                      ] }),
                      j.title !== j.name && /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: j.title })
                    ] })
                  ] })
                },
                `all-${j.name}`
              ))
            ] }),
            P.length === 0 && /* @__PURE__ */ s("div", { className: "px-3 py-4 text-sm text-dc-text-muted text-center", children: [
              'No fields found matching "',
              D,
              '"'
            ] })
          ] })
        ] })
      ] })
    ] }),
    $ && /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-1 sm:flex-initial min-w-0", children: [
      !h && /* @__PURE__ */ s("div", { className: "relative shrink-0", children: [
        /* @__PURE__ */ s(
          "button",
          {
            onClick: w,
            className: "w-full sm:w-32 flex items-center justify-between text-left text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent",
            children: [
              /* @__PURE__ */ e("span", { className: "truncate", children: L.find((j) => j.operator === t.operator)?.label || t.operator }),
              /* @__PURE__ */ e(_r, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-1 transition-transform ${x ? "transform rotate-180" : ""}` })
            ]
          }
        ),
        x && /* @__PURE__ */ e("div", { className: "absolute z-20 left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-60 overflow-y-auto", children: L.map((j) => /* @__PURE__ */ e(
          "button",
          {
            onClick: () => Q(j.operator),
            className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-none focus:bg-dc-surface-hover ${j.operator === t.operator ? "bg-dc-accent-bg text-dc-accent" : "text-dc-text-secondary"}`,
            children: j.label
          },
          j.operator
        )) })
      ] }),
      /* @__PURE__ */ e("div", { className: "flex-1 min-w-0", children: I ? (
        /* Date Range Selector for time dimensions with inDateRange */
        /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ s("div", { className: "relative shrink-0", children: [
            /* @__PURE__ */ s(
              "button",
              {
                onClick: () => {
                  f(!1), T(!S);
                },
                className: "w-full sm:w-40 flex items-center justify-between text-left text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent",
                children: [
                  /* @__PURE__ */ e("span", { className: "truncate", children: ee }),
                  /* @__PURE__ */ e(_r, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-1 transition-transform ${S ? "transform rotate-180" : ""}` })
                ]
              }
            ),
            S && /* @__PURE__ */ e("div", { className: "absolute z-20 left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-60 overflow-y-auto", children: bt.map((j) => /* @__PURE__ */ e(
              "button",
              {
                onClick: () => J(j.value),
                className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-none focus:bg-dc-surface-hover ${j.value === O ? "bg-dc-accent-bg text-dc-accent" : "text-dc-text-secondary"}`,
                children: j.label
              },
              j.value
            )) })
          ] }),
          O === "custom" ? /* @__PURE__ */ s(Ie, { children: [
            /* @__PURE__ */ e(
              "input",
              {
                type: "date",
                value: y.startDate,
                onChange: (j) => Y("startDate", j.target.value),
                placeholder: "Start date",
                className: "flex-1 min-w-0 text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
              }
            ),
            /* @__PURE__ */ e(
              "input",
              {
                type: "date",
                value: y.endDate,
                onChange: (j) => Y("endDate", j.target.value),
                placeholder: "End date",
                className: "flex-1 min-w-0 text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
              }
            )
          ] }) : Ct(O) ? /* @__PURE__ */ s(Ie, { children: [
            /* @__PURE__ */ e(
              "input",
              {
                type: "number",
                min: "1",
                max: "1000",
                value: g,
                onChange: (j) => ge(Math.max(1, parseInt(j.target.value) || 1)),
                placeholder: "Number",
                className: "flex-1 min-w-0 text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
              }
            ),
            /* @__PURE__ */ e("div", { className: "shrink-0 text-sm text-dc-text-secondary", children: O.replace("last_n_", "").replace("_", " ") })
          ] }) : null
        ] })
      ) : (
        /* Regular FilterValueSelector for non-dateRange filters */
        /* @__PURE__ */ e(
          Lc,
          {
            fieldName: t.member,
            operator: t.operator,
            values: t.values,
            onValuesChange: ue,
            schema: c
          }
        )
      ) })
    ] }),
    !o && /* @__PURE__ */ e("div", { className: "flex justify-end sm:justify-start", children: /* @__PURE__ */ e(
      "button",
      {
        onClick: () => a(r),
        className: "text-dc-text-muted hover:text-dc-error focus:outline-none shrink-0",
        title: "Remove filter",
        children: /* @__PURE__ */ e(Hc, { className: "w-4 h-4" })
      }
    ) })
  ] }) });
}, Wc = z("close"), Jc = z("add"), ls = ({
  group: t,
  index: r,
  onGroupChange: n,
  onGroupChangeWithUnwrap: a,
  onGroupRemove: c,
  schema: l,
  query: d,
  depth: h = 0
}) => {
  const [o, u] = H(!1), m = t.type === "and", x = m ? "AND" : "OR", f = t.filters, S = h > 0 ? `ml-${Math.min(h * 4, 16)}` : "", T = "border-dc-border", D = "bg-dc-bg-secondary", k = "text-dc-text-secondary", A = () => {
    if (m) {
      const b = ht(f);
      n(r, b);
    } else {
      const b = ct(f);
      n(r, b);
    }
  }, _ = () => {
    if (!l) return;
    const w = Ar(l, d)[0]?.name || "", v = hr(w, "equals", []), M = [...f, v];
    m ? n(r, ct(M)) : n(r, ht(M)), u(!1);
  }, O = () => {
    if (!l) return;
    const w = Ar(l, d)[0]?.name || "", v = ct([hr(w, "equals", [])]), M = [...f, v];
    m ? n(r, ct(M)) : n(r, ht(M)), u(!1);
  }, R = () => {
    if (!l) return;
    const w = Ar(l, d)[0]?.name || "", v = ht([hr(w, "equals", [])]), M = [...f, v];
    m ? n(r, ct(M)) : n(r, ht(M)), u(!1);
  }, y = (b, w) => {
    const v = [...f];
    v[b] = w, m ? n(r, ct(v)) : n(r, ht(v));
  }, i = (b) => {
    const w = f.filter((M, $) => $ !== b);
    if (w.length === 0) {
      c(r);
      return;
    }
    if (w.length === 1) {
      const M = t.type === "and" ? ct(w) : ht(w);
      a ? a(r, M) : n(r, M);
      return;
    }
    const v = t.type === "and" ? ct(w) : ht(w);
    n(r, v);
  }, g = (b, w) => {
    const v = [...f];
    v[b] = w, m ? n(r, ct(v)) : n(r, ht(v));
  }, p = (b) => {
    i(b);
  };
  return /* @__PURE__ */ s("div", { className: `${S} ${T} border-2 ${D} rounded-lg py-3 pr-3 pl-2 space-y-3`, children: [
    /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ e(
          "button",
          {
            onClick: A,
            className: `px-3 py-1 rounded-sm text-sm font-semibold ${k} border border-current hover:bg-dc-surface hover:bg-opacity-20 focus:outline-hidden focus:ring-2 focus:ring-current focus:ring-opacity-50`,
            children: x
          }
        ),
        /* @__PURE__ */ s("span", { className: "text-sm text-dc-text-secondary", children: [
          f.length,
          " condition",
          f.length !== 1 ? "s" : ""
        ] })
      ] }),
      /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ s("div", { className: "relative", children: [
          /* @__PURE__ */ e(
            "button",
            {
              onClick: () => u(!o),
              className: "text-dc-text-muted hover:text-dc-text-secondary focus:outline-hidden",
              title: "Add condition",
              children: /* @__PURE__ */ e(Jc, { className: "w-4 h-4" })
            }
          ),
          o && /* @__PURE__ */ s("div", { className: "absolute right-0 mt-1 w-48 bg-dc-surface border border-dc-border rounded-md shadow-lg z-30", children: [
            /* @__PURE__ */ e(
              "button",
              {
                onClick: _,
                className: "w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover",
                children: "Add Filter"
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: O,
                className: "w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover",
                children: "Add AND Group"
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: R,
                className: "w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover",
                children: "Add OR Group"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ e(
          "button",
          {
            onClick: () => c(r),
            className: "text-dc-text-muted hover:text-dc-error focus:outline-hidden",
            title: "Remove group",
            children: /* @__PURE__ */ e(Wc, { className: "w-4 h-4" })
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ s("div", { className: "space-y-3", children: [
      f.map((b, w) => Xt(b) ? /* @__PURE__ */ e(
        Gr,
        {
          filter: b,
          index: w,
          onFilterChange: y,
          onFilterRemove: i,
          schema: l,
          query: d
        },
        w
      ) : er(b) ? /* @__PURE__ */ e(
        ls,
        {
          group: b,
          index: w,
          onGroupChange: g,
          onGroupRemove: p,
          schema: l,
          query: d,
          depth: h + 1
        },
        w
      ) : null),
      f.length === 0 && /* @__PURE__ */ s("div", { className: "text-center py-4 text-dc-text-muted text-sm", children: [
        "No conditions in this group.",
        /* @__PURE__ */ e(
          "button",
          {
            onClick: _,
            className: "ml-2 text-dc-accent hover:text-dc-accent focus:outline-hidden underline",
            children: "Add a filter"
          }
        )
      ] })
    ] })
  ] });
}, Yc = z("add"), Kc = z("filter"), Xc = ({
  filters: t,
  schema: r,
  query: n,
  onFiltersChange: a,
  hideFieldSelector: c = !1
}) => {
  const l = Vc(t), d = r ? Ur(r) : [], h = d.length > 0, o = () => {
    if (!h) return;
    const D = d[0]?.name || "", k = hr(D, "equals", []);
    if (t.length === 0)
      a([k]);
    else if (t.length === 1 && Xt(t[0])) {
      const A = ct([t[0], k]);
      a([A]);
    } else if (t.length === 1 && jc(t[0])) {
      const A = t[0], _ = ct([...A.filters, k]);
      a([_]);
    } else if (t.length === 1 && Pc(t[0])) {
      const A = t[0], _ = ht([...A.filters, k]);
      a([_]);
    } else
      a([...t, k]);
  }, u = (D, k) => {
    const A = [...t];
    A[D] = k, a(A);
  }, m = (D) => {
    const k = t.filter((A, _) => _ !== D);
    a(k);
  }, x = (D, k) => {
    const A = [...t];
    A[D] = k, a(A);
  }, f = (D, k) => {
    const A = [...t];
    k.filters.length === 1 && Xt(k.filters[0]) ? A[D] = k.filters[0] : A[D] = k, a(A);
  }, S = () => {
    a([]);
  }, T = () => {
    a([]);
  };
  return /* @__PURE__ */ s("div", { className: "space-y-4 bg-dc-surface-secondary rounded-lg p-4", children: [
    !c && /* @__PURE__ */ s("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center", children: [
        /* @__PURE__ */ e(Kc, { className: "w-4 h-4 text-dc-text-muted mr-2" }),
        /* @__PURE__ */ s("h4", { className: "text-sm font-semibold text-dc-text-secondary", children: [
          "Filters (",
          l,
          ")"
        ] })
      ] }),
      /* @__PURE__ */ s("div", { className: "flex items-center space-x-2", children: [
        t.length > 0 && /* @__PURE__ */ e(
          "button",
          {
            onClick: T,
            className: "text-xs text-dc-text-muted hover:text-dc-error focus:outline-hidden underline",
            children: "Clear all"
          }
        ),
        /* @__PURE__ */ s(
          "button",
          {
            onClick: o,
            disabled: !h,
            className: `flex items-center space-x-1 px-2 py-1 text-xs font-medium rounded focus:outline-hidden focus:ring-2 ${h ? "text-dc-accent bg-dc-accent-bg border border-dc-accent hover:bg-dc-accent-bg focus:ring-dc-accent" : "text-dc-text-muted bg-dc-surface-secondary border border-dc-border cursor-not-allowed"}`,
            children: [
              /* @__PURE__ */ e(Yc, { className: "w-3 h-3" }),
              /* @__PURE__ */ e("span", { children: "Add Filter" })
            ]
          }
        )
      ] })
    ] }),
    t.length > 0 && /* @__PURE__ */ e("div", { className: "space-y-3", children: t.map((D, k) => Xt(D) ? /* @__PURE__ */ e(
      Gr,
      {
        filter: D,
        index: k,
        onFilterChange: u,
        onFilterRemove: m,
        schema: r,
        query: n,
        hideFieldSelector: c,
        hideRemoveButton: c
      },
      k
    ) : er(D) ? /* @__PURE__ */ e(
      ls,
      {
        group: D,
        index: k,
        onGroupChange: x,
        onGroupChangeWithUnwrap: f,
        onGroupRemove: S,
        schema: r,
        query: n,
        depth: 0
      },
      k
    ) : null) })
  ] });
}, Zc = z("close"), el = z("timeDimension"), Dn = z("chevronDown"), is = ({
  timeDimension: t,
  availableTimeDimensions: r,
  currentDateRange: n,
  onDateRangeChange: a,
  onTimeDimensionChange: c,
  onRemove: l,
  hideFieldSelector: d = !1,
  hideRemoveButton: h = !1
}) => {
  const o = () => {
    if (!n) return "this_month";
    if (Array.isArray(n))
      return "custom";
    const $ = n.match(/^last (\d+) (days|weeks|months|quarters|years)$/);
    if ($) {
      const [, , C] = $;
      return `last_n_${C === "days" ? "days" : C === "weeks" ? "weeks" : C === "months" ? "months" : C === "quarters" ? "quarters" : "years"}`;
    }
    for (const C of bt)
      if (C.value !== "custom" && !Ct(C.value) && kt(C.value) === n)
        return C.value;
    return "custom";
  }, u = () => {
    if (Array.isArray(n) && n.length >= 1)
      return {
        startDate: n[0] || "",
        endDate: n[1] || n[0] || ""
      };
    const $ = $r(/* @__PURE__ */ new Date());
    return { startDate: $, endDate: $ };
  }, m = () => {
    if (!n || Array.isArray(n)) return 1;
    const $ = n.match(/^last (\d+) (days|weeks|months|quarters|years)$/);
    return $ && parseInt($[1]) || 1;
  }, [x, f] = H(o()), [S, T] = H(u()), [D, k] = H(m()), [A, _] = H(!1), [O, R] = H(!1), y = Te(null);
  Ce(() => {
    const $ = (C) => {
      y.current && !y.current.contains(C.target) && (_(!1), R(!1));
    };
    return document.addEventListener("mousedown", $), () => document.removeEventListener("mousedown", $);
  }, []);
  const i = () => {
    _(!1), R(!O);
  }, g = () => {
    R(!1), _(!A);
  }, p = ($) => {
    if (f($), _(!1), $ === "custom") {
      if (S.startDate && S.endDate) {
        const C = S.startDate === S.endDate ? S.startDate : [S.startDate, S.endDate];
        a(t, C);
      }
    } else if (Ct($)) {
      const C = kt($, D);
      a(t, C);
    } else {
      const C = kt($);
      a(t, C);
    }
  }, b = ($, C) => {
    const L = { ...S, [$]: C };
    if (T(L), x === "custom" && L.startDate) {
      const I = !L.endDate || L.startDate === L.endDate ? L.startDate : [L.startDate, L.endDate];
      a(t, I);
    }
  }, w = ($) => {
    if (k($), Ct(x)) {
      const C = kt(x, $);
      a(t, C);
    }
  }, v = ($) => {
    R(!1), c(t, $);
  }, M = bt.find(($) => $.value === x)?.label || "Custom";
  return /* @__PURE__ */ e("div", { ref: y, className: "bg-dc-surface border border-dc-border rounded-lg p-3", children: /* @__PURE__ */ s("div", { className: "flex flex-col sm:flex-row sm:items-center gap-3 min-w-0", children: [
    !d && /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
      /* @__PURE__ */ e(el, { className: "w-4 h-4 text-dc-text-muted shrink-0" }),
      /* @__PURE__ */ s("div", { className: "relative flex-1 min-w-0", children: [
        /* @__PURE__ */ s(
          "button",
          {
            onClick: i,
            className: "w-full flex items-center justify-between text-left text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent min-w-0",
            children: [
              /* @__PURE__ */ e("span", { className: "truncate", children: t }),
              /* @__PURE__ */ e(Dn, { className: `w-4 h-4 text-dc-text-muted shrink-0 transition-transform ${O ? "transform rotate-180" : ""}` })
            ]
          }
        ),
        O && /* @__PURE__ */ e("div", { className: "absolute z-20 left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-60 overflow-y-auto", children: r.map(($) => /* @__PURE__ */ e(
          "button",
          {
            onClick: () => v($),
            className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover ${$ === t ? "bg-dc-accent-bg dark:bg-dc-accent-bg text-dc-accent dark:text-dc-accent" : "text-dc-text-secondary"}`,
            children: $
          },
          $
        )) })
      ] })
    ] }),
    /* @__PURE__ */ e("div", { className: "flex items-center gap-2 flex-1 sm:flex-initial min-w-0", children: /* @__PURE__ */ s("div", { className: "relative shrink-0", children: [
      /* @__PURE__ */ s(
        "button",
        {
          onClick: g,
          className: "w-full sm:w-40 flex items-center justify-between text-left text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent",
          children: [
            /* @__PURE__ */ e("span", { className: "truncate", children: M }),
            /* @__PURE__ */ e(Dn, { className: `w-4 h-4 text-dc-text-muted shrink-0 ml-1 transition-transform ${A ? "transform rotate-180" : ""}` })
          ]
        }
      ),
      A && /* @__PURE__ */ e("div", { className: "absolute z-20 left-0 right-0 mt-1 bg-dc-surface border border-dc-border rounded-md shadow-lg max-h-60 overflow-y-auto", children: bt.map(($) => /* @__PURE__ */ e(
        "button",
        {
          onClick: () => p($.value),
          className: `w-full text-left px-3 py-2 text-sm hover:bg-dc-surface-hover focus:outline-hidden focus:bg-dc-surface-hover ${$.value === x ? "bg-dc-accent-bg dark:bg-dc-accent-bg text-dc-accent dark:text-dc-accent" : "text-dc-text-secondary"}`,
          children: $.label
        },
        $.value
      )) })
    ] }) }),
    /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
      x === "custom" ? /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ e(
          "input",
          {
            type: "date",
            value: S.startDate,
            onChange: ($) => b("startDate", $.target.value),
            placeholder: "dd/mm/yyyy",
            className: "w-full text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
          }
        ) }),
        /* @__PURE__ */ e("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ e(
          "input",
          {
            type: "date",
            value: S.endDate,
            onChange: ($) => b("endDate", $.target.value),
            placeholder: "dd/mm/yyyy",
            className: "w-full text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
          }
        ) })
      ] }) : Ct(x) ? /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ e(
          "input",
          {
            type: "number",
            min: "1",
            max: "1000",
            value: D,
            onChange: ($) => w(Math.max(1, parseInt($.target.value) || 1)),
            placeholder: "Number",
            className: "w-full text-sm border border-dc-border rounded-sm px-2 py-1 bg-dc-surface text-dc-text hover:bg-dc-surface-hover focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
          }
        ) }),
        /* @__PURE__ */ e("div", { className: "shrink-0 text-sm text-dc-text-secondary", children: x.replace("last_n_", "").replace("_", " ") })
      ] }) : (
        // Empty placeholder to maintain layout consistency
        /* @__PURE__ */ e("div", { className: "flex-1" })
      ),
      !h && /* @__PURE__ */ e(
        "button",
        {
          onClick: () => l(t),
          className: "text-dc-text-muted hover:text-dc-error focus:outline-hidden shrink-0 p-1",
          title: "Remove date range",
          children: /* @__PURE__ */ e(Zc, { className: "w-4 h-4" })
        }
      )
    ] })
  ] }) });
}, tl = ys(
  () => import("./index-B7NSVb33.js").then((t) => ({ default: t.CubeRelationshipDiagram }))
), rl = ({
  schema: t,
  schemaStatus: r,
  schemaError: n,
  selectedFields: a,
  onFieldSelect: c,
  onFieldDeselect: l,
  onRetrySchema: d,
  onOpenSettings: h,
  onViewTypeChange: o,
  isExpanded: u = !1
}) => {
  const m = z("chevronDown"), x = z("chevronRight"), f = z("warning"), S = z("refresh"), T = z("settings"), D = z("measure"), k = z("dimension"), A = z("timeDimension"), _ = z("segment"), O = z("menu"), { features: R } = jt(), y = R?.showSchemaDiagram === !0, [i, g] = H(/* @__PURE__ */ new Set()), [p, b] = H(/* @__PURE__ */ new Set()), [w, v] = H(""), [M, $] = H("tree"), [C, L] = H(null), [I, E] = H(null);
  if (lt.useEffect(() => {
    u && y && $("diagram");
  }, [u, y]), lt.useEffect(() => {
    if (!t)
      return;
    if (w.trim().length > 0) {
      C === null && (L(new Set(i)), E(new Set(p)));
      const Y = /* @__PURE__ */ new Set(), ge = /* @__PURE__ */ new Set();
      t.cubes.forEach((re) => {
        let xe = !1;
        re.measures.filter(
          (U) => U.name.toLowerCase().includes(w.toLowerCase()) || U.title.toLowerCase().includes(w.toLowerCase())
        ).length > 0 && (xe = !0, ge.add(`${re.name}-measures`)), re.dimensions.filter((U) => U.type !== "time").filter(
          (U) => U.name.toLowerCase().includes(w.toLowerCase()) || U.title.toLowerCase().includes(w.toLowerCase())
        ).length > 0 && (xe = !0, ge.add(`${re.name}-dimensions`)), re.dimensions.filter((U) => U.type === "time").filter(
          (U) => U.name.toLowerCase().includes(w.toLowerCase()) || U.title.toLowerCase().includes(w.toLowerCase())
        ).length > 0 && (xe = !0, ge.add(`${re.name}-timeDimensions`)), xe && Y.add(re.name);
      });
      const ee = /* @__PURE__ */ new Set([...C || [], ...Y]), j = /* @__PURE__ */ new Set([...I || [], ...ge]);
      g(ee), b(j);
    } else
      C !== null && I !== null && (g(C), b(I), L(null), E(null));
  }, [t, w, C, I]), r === "loading")
    return /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center text-dc-text-muted", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
      /* @__PURE__ */ e("div", { className: "animate-spin rounded-full h-8 w-8 border-b-2 mx-auto mb-3", style: { borderBottomColor: "var(--dc-primary)" } }),
      /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "Loading Schema..." }),
      /* @__PURE__ */ e("div", { className: "text-xs", children: "Fetching cube metadata" })
    ] }) });
  if (r === "error") {
    const J = n?.toLowerCase().includes("cors") || n?.toLowerCase().includes("fetch");
    return /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center", children: /* @__PURE__ */ s("div", { className: "text-center max-w-sm p-6", children: [
      /* @__PURE__ */ e(f, { className: "w-12 h-12 mx-auto text-dc-error mb-4" }),
      /* @__PURE__ */ e("div", { className: "text-sm font-semibold text-dc-text mb-2", children: "Failed to Load Schema" }),
      /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-secondary mb-4", children: J ? /* @__PURE__ */ e(Ie, { children: "CORS error detected. The API endpoint may be incorrect or not accessible." }) : /* @__PURE__ */ e(Ie, { children: n || "Unable to connect to the Cube.js API" }) }),
      /* @__PURE__ */ s("div", { className: "space-y-2", children: [
        d && /* @__PURE__ */ s(
          "button",
          {
            onClick: d,
            className: "w-full flex items-center justify-center space-x-2 px-3 py-2 text-sm font-medium text-dc-accent bg-dc-accent-bg border border-dc-accent rounded-md hover:bg-dc-accent-bg focus:outline-hidden focus:ring-2 focus:ring-dc-accent",
            children: [
              /* @__PURE__ */ e(S, { className: "w-4 h-4" }),
              /* @__PURE__ */ e("span", { children: "Retry" })
            ]
          }
        ),
        h && /* @__PURE__ */ s(
          "button",
          {
            onClick: h,
            className: "w-full flex items-center justify-center space-x-2 px-3 py-2 text-sm font-medium text-dc-text-secondary bg-dc-surface border border-dc-border rounded-md hover:bg-dc-surface-hover focus:outline-hidden focus:ring-2 focus:ring-dc-accent",
            children: [
              /* @__PURE__ */ e(T, { className: "w-4 h-4" }),
              /* @__PURE__ */ e("span", { children: "Check API Settings" })
            ]
          }
        )
      ] }),
      J && /* @__PURE__ */ e("div", { className: "mt-4 p-3 bg-dc-warning-bg border border-dc-warning rounded-md", children: /* @__PURE__ */ s("div", { className: "text-xs text-dc-warning", children: [
        /* @__PURE__ */ e("div", { className: "font-medium mb-1", children: "Common solutions:" }),
        /* @__PURE__ */ s("ul", { className: "list-disc list-inside space-y-1", children: [
          /* @__PURE__ */ e("li", { children: "Verify the Base API URL is correct" }),
          /* @__PURE__ */ e("li", { children: "Ensure the server supports CORS" }),
          /* @__PURE__ */ e("li", { children: "Check if authentication is required" })
        ] })
      ] }) })
    ] }) });
  }
  if (!t)
    return /* @__PURE__ */ e("div", { className: "h-full flex items-center justify-center text-dc-text-muted", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
      /* @__PURE__ */ e("div", { className: "text-sm font-semibold mb-1", children: "No Schema" }),
      /* @__PURE__ */ e("div", { className: "text-xs", children: "Schema not loaded" })
    ] }) });
  const K = (J) => {
    const Y = new Set(i);
    if (Y.has(J) ? Y.delete(J) : Y.add(J), g(Y), C !== null) {
      const ge = new Set(C);
      ge.has(J) ? ge.delete(J) : ge.add(J), L(ge);
    }
  }, P = (J) => {
    const Y = new Set(p);
    if (Y.has(J) ? Y.delete(J) : Y.add(J), b(Y), I !== null) {
      const ge = new Set(I);
      ge.has(J) ? ge.delete(J) : ge.add(J), E(ge);
    }
  }, Ne = (J, Y) => {
    (() => {
      switch (Y) {
        case "measures":
          return a.measures.includes(J.name);
        case "dimensions":
          return a.dimensions.includes(J.name);
        case "timeDimensions":
          return a.timeDimensions.includes(J.name);
        default:
          return !1;
      }
    })() ? l(J.name, Y) : c(J.name, Y);
  }, ye = (J) => w ? J.filter(
    (Y) => Y.name.toLowerCase().includes(w.toLowerCase()) || Y.title.toLowerCase().includes(w.toLowerCase())
  ) : J, Ue = (J) => {
    if (!w.trim()) return !0;
    const Y = J.measures.some(
      (ee) => ee.name.toLowerCase().includes(w.toLowerCase()) || ee.title.toLowerCase().includes(w.toLowerCase())
    ), ge = J.dimensions.some(
      (ee) => ee.name.toLowerCase().includes(w.toLowerCase()) || ee.title.toLowerCase().includes(w.toLowerCase())
    );
    return Y || ge;
  }, Q = ({ field: J, fieldType: Y, icon: ge }) => {
    const ee = (() => {
      switch (Y) {
        case "measures":
          return a.measures.includes(J.name);
        case "dimensions":
          return a.dimensions.includes(J.name);
        case "timeDimensions":
          return a.timeDimensions.includes(J.name);
        default:
          return !1;
      }
    })(), j = () => {
      if (!ee) return "hover:bg-dc-surface-hover text-dc-text-secondary";
      switch (Y) {
        case "measures":
          return "bg-dc-warning-bg text-dc-warning border border-dc-warning";
        case "dimensions":
          return "bg-dc-success-bg text-dc-success border border-dc-success";
        case "timeDimensions":
          return "bg-dc-accent-bg text-dc-accent border border-dc-accent";
        default:
          return "bg-dc-accent-bg text-dc-accent border border-dc-accent";
      }
    }, re = () => {
      if (!ee) return "text-dc-text-muted";
      switch (Y) {
        case "measures":
          return "text-dc-warning";
        case "dimensions":
          return "text-dc-success";
        case "timeDimensions":
          return "text-dc-accent";
        default:
          return "text-dc-accent";
      }
    }, xe = () => {
      switch (Y) {
        case "measures":
          return "text-dc-warning";
        case "dimensions":
          return "text-dc-success";
        case "timeDimensions":
          return "text-dc-accent";
        default:
          return "text-dc-accent";
      }
    };
    return /* @__PURE__ */ s(
      "div",
      {
        className: `flex items-center px-2 py-1.5 text-xs cursor-pointer rounded-md transition-colors ${j()}`,
        onClick: () => Ne(J, Y),
        title: J.description || J.title,
        children: [
          /* @__PURE__ */ e("div", { className: `mr-1.5 ${re()}`, children: lt.cloneElement(ge, { className: "w-4 h-4" }) }),
          /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ e("div", { className: "font-medium truncate text-xs", children: J.shortTitle }),
            /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted truncate", children: J.name })
          ] }),
          ee && /* @__PURE__ */ e("div", { className: `ml-1.5 ${xe()}`, children: /* @__PURE__ */ e("svg", { className: "w-4 h-4", fill: "currentColor", viewBox: "0 0 20 20", children: /* @__PURE__ */ e("path", { fillRule: "evenodd", d: "M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z", clipRule: "evenodd" }) }) })
        ]
      }
    );
  }, ue = ({ title: J, count: Y, sectionKey: ge, icon: ee }) => {
    const j = p.has(ge), re = () => ge.includes("-dimensions") && !ge.includes("-timeDimensions") ? "dimensions" : ge.includes("-timeDimensions") ? "timeDimensions" : "measures";
    return /* @__PURE__ */ s(
      "div",
      {
        className: `flex items-center px-2 py-1 text-sm font-semibold cursor-pointer hover:bg-dc-surface-hover rounded-md ${(() => {
          switch (re()) {
            case "dimensions":
              return "text-dc-success";
            case "timeDimensions":
              return "text-dc-accent";
            case "measures":
              return "text-dc-warning";
            default:
              return "text-dc-text-secondary";
          }
        })()}`,
        onClick: () => P(ge),
        children: [
          /* @__PURE__ */ e("div", { className: "mr-1.5", children: j ? /* @__PURE__ */ e(m, { className: "w-3 h-3" }) : /* @__PURE__ */ e(x, { className: "w-3 h-3" }) }),
          /* @__PURE__ */ e("div", { className: "mr-1.5", children: ee }),
          /* @__PURE__ */ e("span", { className: "flex-1", children: J }),
          /* @__PURE__ */ e("span", { className: "text-xs text-dc-text-muted bg-dc-surface-secondary px-1.5 py-0.5 rounded-full", children: Y })
        ]
      }
    );
  }, me = () => /* @__PURE__ */ e("div", { className: "flex items-center justify-center py-8 text-center", children: /* @__PURE__ */ s("div", { className: "max-w-sm", children: [
    /* @__PURE__ */ e("div", { className: "text-dc-text-muted mb-2", children: /* @__PURE__ */ e("svg", { className: "w-12 h-12 mx-auto", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" }) }) }),
    /* @__PURE__ */ e("div", { className: "text-sm font-medium text-dc-text mb-1", children: "No matches found" }),
    /* @__PURE__ */ s("div", { className: "text-xs text-dc-text-muted mb-3", children: [
      'No fields match your search term "',
      w,
      '"'
    ] }),
    /* @__PURE__ */ e(
      "button",
      {
        onClick: () => v(""),
        className: "inline-flex items-center px-3 py-1.5 text-xs font-medium text-dc-accent bg-dc-accent-bg border border-dc-accent rounded-md hover:bg-dc-accent-bg focus:outline-hidden focus:ring-2 focus:ring-dc-accent",
        children: "Clear search"
      }
    )
  ] }) });
  return /* @__PURE__ */ s("div", { className: "flex-1 flex flex-col bg-dc-surface border border-dc-border rounded-lg min-h-0", children: [
    /* @__PURE__ */ e("div", { className: "border-b border-dc-border", children: /* @__PURE__ */ s("div", { className: "p-3 pb-0", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center justify-between mb-3", children: [
        /* @__PURE__ */ e("div", { children: /* @__PURE__ */ e("h3", { className: "text-base font-semibold text-dc-text", children: M === "diagram" ? "Schema Diagram" : "Schema Explorer" }) }),
        /* @__PURE__ */ e("div", { className: "flex items-center space-x-2", children: h && /* @__PURE__ */ e(
          "button",
          {
            onClick: h,
            className: "p-1 text-dc-text-muted hover:text-dc-text-secondary transition-colors",
            title: "Open settings",
            children: /* @__PURE__ */ e(T, { className: "w-4 h-4" })
          }
        ) })
      ] }),
      /* @__PURE__ */ s("div", { className: "flex items-center gap-3 mb-3", children: [
        y ? /* @__PURE__ */ s("div", { className: "flex space-x-1 bg-dc-surface-secondary p-1 rounded-md", children: [
          /* @__PURE__ */ s(
            "button",
            {
              onClick: () => {
                $("tree"), o?.("tree");
              },
              className: `
                    flex items-center px-3 py-1.5 rounded text-xs font-medium transition-colors
                    ${M === "tree" ? "bg-dc-surface text-dc-text shadow-xs" : "text-dc-text-secondary hover:text-dc-text"}
                  `,
              children: [
                /* @__PURE__ */ e(O, { className: "w-3 h-3 mr-1.5" }),
                "Fields"
              ]
            }
          ),
          /* @__PURE__ */ s(
            "button",
            {
              onClick: () => {
                $("diagram"), o?.("diagram");
              },
              className: `
                    flex items-center px-3 py-1.5 rounded text-xs font-medium transition-colors
                    ${M === "diagram" ? "bg-dc-surface text-dc-text shadow-xs" : "text-dc-text-secondary hover:text-dc-text"}
                  `,
              children: [
                /* @__PURE__ */ e(_, { className: "w-3 h-3 mr-1.5" }),
                "Schema"
              ]
            }
          )
        ] }) : null,
        /* @__PURE__ */ s("div", { className: "flex-1 relative min-w-0", children: [
          /* @__PURE__ */ e(
            "input",
            {
              type: "text",
              placeholder: "Search fields...",
              value: w,
              onChange: (J) => v(J.target.value),
              className: "w-full px-2 py-1.5 border border-dc-border rounded-md text-sm bg-dc-surface text-dc-text focus:ring-2 focus:ring-dc-accent focus:border-dc-accent"
            }
          ),
          /* @__PURE__ */ e("div", { className: "absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none", children: /* @__PURE__ */ e("svg", { className: "h-4 w-4 text-dc-text-muted", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" }) }) })
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ e("div", { className: "flex-1 min-h-0 overflow-hidden", children: M === "diagram" && y ? (
      /* Diagram View - schema relationship diagram (only when enabled) */
      /* @__PURE__ */ e("div", { className: "h-full", children: /* @__PURE__ */ e(gs, { fallback: /* @__PURE__ */ e("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ e("div", { className: "animate-pulse text-dc-text-muted", children: "Loading diagram..." }) }), children: /* @__PURE__ */ e(
        tl,
        {
          className: "h-full",
          onCubeClick: (J) => {
            u || (g((Y) => /* @__PURE__ */ new Set([...Y, J])), $("tree"));
          },
          onFieldClick: (J, Y, ge) => {
            let ee;
            ge === "measure" ? ee = "measures" : ee = t?.cubes.find((Me) => Me.name === J)?.dimensions.find(
              (Me) => Me.name === `${J}.${Y}` || Me.name === Y
            )?.type === "time" ? "timeDimensions" : "dimensions";
            const j = `${J}.${Y}`;
            a[ee].includes(j) ? l(j, ee) : c(j, ee);
          },
          highlightedCubes: [
            ...a.measures.map((J) => J.split(".")[0]),
            ...a.dimensions.map((J) => J.split(".")[0]),
            ...a.timeDimensions.map((J) => J.split(".")[0])
          ].filter((J, Y, ge) => ge.indexOf(J) === Y),
          highlightedFields: [
            ...a.measures,
            ...a.dimensions,
            ...a.timeDimensions
          ],
          searchTerm: w
        }
      ) }) })
    ) : (
      /* Tree View - existing field list */
      /* @__PURE__ */ e("div", { className: "h-full p-3 space-y-2 overflow-y-auto", children: (() => {
        const J = t.cubes.filter(Ue);
        return w.trim() && J.length === 0 ? /* @__PURE__ */ e(me, {}) : J.map((Y) => {
          const ge = i.has(Y.name), ee = Y.dimensions.filter((re) => re.type === "time"), j = Y.dimensions.filter((re) => re.type !== "time");
          return /* @__PURE__ */ s("div", { className: "border border-dc-border rounded-lg", children: [
            /* @__PURE__ */ s(
              "div",
              {
                className: "flex items-center px-3 py-2 cursor-pointer hover:bg-dc-surface-hover rounded-t-lg",
                onClick: () => K(Y.name),
                children: [
                  /* @__PURE__ */ e("div", { className: "mr-2", children: ge ? /* @__PURE__ */ e(m, { className: "w-4 h-4 text-dc-text-secondary" }) : /* @__PURE__ */ e(x, { className: "w-4 h-4 text-dc-text-secondary" }) }),
                  /* @__PURE__ */ s("div", { className: "flex-1", children: [
                    /* @__PURE__ */ e("div", { className: "font-medium text-sm text-dc-text", children: Y.title }),
                    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-muted", children: Y.description })
                  ] })
                ]
              }
            ),
            ge && /* @__PURE__ */ s("div", { className: "border-t border-dc-border p-2 space-y-1", children: [
              j.length > 0 && ye(j).length > 0 && /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e(
                  ue,
                  {
                    title: "Dimensions",
                    count: ye(j).length,
                    sectionKey: `${Y.name}-dimensions`,
                    icon: /* @__PURE__ */ e(k, { className: "w-4 h-4 text-dc-success" })
                  }
                ),
                p.has(`${Y.name}-dimensions`) && /* @__PURE__ */ e("div", { className: "ml-5 space-y-1 mt-1", children: ye(j).map((re) => /* @__PURE__ */ e(
                  Q,
                  {
                    field: re,
                    fieldType: "dimensions",
                    icon: /* @__PURE__ */ e(k, { className: "w-4 h-4" })
                  },
                  re.name
                )) })
              ] }),
              ee.length > 0 && ye(ee).length > 0 && /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e(
                  ue,
                  {
                    title: "Time Dimensions",
                    count: ye(ee).length,
                    sectionKey: `${Y.name}-timeDimensions`,
                    icon: /* @__PURE__ */ e(A, { className: "w-4 h-4 text-dc-accent" })
                  }
                ),
                p.has(`${Y.name}-timeDimensions`) && /* @__PURE__ */ e("div", { className: "ml-5 space-y-1 mt-1", children: ye(ee).map((re) => /* @__PURE__ */ e(
                  Q,
                  {
                    field: re,
                    fieldType: "timeDimensions",
                    icon: /* @__PURE__ */ e(A, { className: "w-4 h-4" })
                  },
                  re.name
                )) })
              ] }),
              Y.measures.length > 0 && ye(Y.measures).length > 0 && /* @__PURE__ */ s("div", { children: [
                /* @__PURE__ */ e(
                  ue,
                  {
                    title: "Measures",
                    count: ye(Y.measures).length,
                    sectionKey: `${Y.name}-measures`,
                    icon: /* @__PURE__ */ e(D, { className: "w-4 h-4 text-dc-warning" })
                  }
                ),
                p.has(`${Y.name}-measures`) && /* @__PURE__ */ e("div", { className: "ml-5 space-y-1 mt-1", children: ye(Y.measures).map((re) => /* @__PURE__ */ e(
                  Q,
                  {
                    field: re,
                    fieldType: "measures",
                    icon: cs(re.type, "w-4 h-4")
                  },
                  re.name
                )) })
              ] })
            ] })
          ] }, Y.name);
        });
      })() })
    ) })
  ] });
}, nl = gt(rl), sl = z("close"), al = z("eye"), cl = z("eyeOff"), ll = ({
  filter: t,
  schema: r,
  dashboardConfig: n,
  isOpen: a,
  onSave: c,
  onClose: l,
  onDelete: d,
  convertToMetaResponse: h
}) => {
  const [o, u] = H(t.label), [m, x] = H(t.filter), [f, S] = H(!1);
  Ce(() => {
    a && (u(t.label), x(t.filter));
  }, [t, a]);
  const T = Oe(() => Xs(n), [n]), D = Oe(() => {
    if (!r) return null;
    if (f)
      return h(r);
    const p = r.cubes.map((w) => {
      const v = w.name, M = w.measures.filter((C) => {
        const L = C.name.includes(".") ? C.name : `${v}.${C.name}`;
        return T.measures.has(L);
      }), $ = w.dimensions.filter((C) => {
        const L = C.name.includes(".") ? C.name : `${v}.${C.name}`;
        return T.dimensions.has(L) || T.timeDimensions.has(L);
      });
      return M.length > 0 || $.length > 0 ? {
        ...w,
        measures: M,
        dimensions: $
      } : null;
    }).filter((w) => w !== null), b = {
      ...r,
      cubes: p
    };
    return h(b);
  }, [r, T, f, h]), k = Oe(() => "member" in m && m.member ? m.member : null, [m]), A = F((p) => {
    u(p);
  }, []), _ = F((p) => {
    x(p[0] || m);
  }, [m]), O = F((p) => {
    "member" in m && x({
      ...m,
      member: p,
      values: []
      // Reset values when changing field
    });
  }, [m]), R = F((p, b) => {
    "member" in m && x({
      ...m,
      values: Array.isArray(b) ? b : [b]
    });
  }, [m]), y = F(() => o.trim() ? !t.isUniversalTime && "member" in m && !m.member ? { isValid: !1, message: "Please select a field for the filter" } : { isValid: !0 } : { isValid: !1, message: "Filter label is required" }, [o, m, t.isUniversalTime]), i = F(async () => {
    const p = y();
    if (!p.isValid) {
      alert(p.message);
      return;
    }
    const b = {
      id: t.id,
      label: o,
      filter: m,
      // Preserve isUniversalTime flag if present
      ...t.isUniversalTime && { isUniversalTime: !0 }
    };
    try {
      await c(b), l();
    } catch (w) {
      console.error("Failed to save filter:", w), alert("Failed to save filter. Please try again.");
    }
  }, [t.id, t.isUniversalTime, o, m, y, c, l]), g = F(() => {
    u(t.label), x(t.filter), l();
  }, [t, l]);
  return /* @__PURE__ */ e(
    "div",
    {
      className: "fixed inset-0 z-50 backdrop-blur-md flex items-center justify-center p-2",
      style: { backgroundColor: "var(--dc-overlay)" },
      children: /* @__PURE__ */ s(
        "div",
        {
          className: "rounded-lg max-w-7xl w-full h-[95vh] overflow-hidden flex flex-col bg-dc-surface border border-dc-border",
          style: { boxShadow: "var(--dc-shadow-2xl)" },
          children: [
            /* @__PURE__ */ s("div", { className: "px-6 py-4 border-b border-dc-border flex items-center justify-between", children: [
              /* @__PURE__ */ s("div", { className: "flex-1", children: [
                /* @__PURE__ */ e("label", { className: "block text-sm font-medium mb-2 text-dc-text", children: "Filter Label" }),
                /* @__PURE__ */ e(
                  "input",
                  {
                    type: "text",
                    value: o,
                    onChange: (p) => A(p.target.value),
                    className: "w-full px-3 py-2 border border-dc-border rounded-md text-sm bg-dc-surface-secondary text-dc-text",
                    placeholder: "Enter filter label"
                  }
                )
              ] }),
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: g,
                  className: "ml-4 p-2 hover:bg-dc-surface-hover rounded-md transition-colors text-dc-text-secondary",
                  children: /* @__PURE__ */ e(sl, { className: "w-5 h-5" })
                }
              )
            ] }),
            /* @__PURE__ */ s("div", { className: "flex-1 flex", children: [
              !t.isUniversalTime && /* @__PURE__ */ e("div", { className: "w-80 border-r border-dc-border bg-dc-surface overflow-auto", children: /* @__PURE__ */ s("div", { className: "p-4", children: [
                /* @__PURE__ */ s("div", { className: "flex items-center justify-between mb-3", children: [
                  /* @__PURE__ */ e("h3", { className: "text-sm font-semibold text-dc-text", children: "Available Fields" }),
                  /* @__PURE__ */ e(
                    "button",
                    {
                      onClick: () => S(!f),
                      className: "flex items-center gap-1 text-xs px-2 py-1 rounded hover:bg-dc-surface-hover text-dc-text-muted",
                      title: f ? "Show dashboard fields only" : "Show all fields",
                      children: f ? /* @__PURE__ */ s(Ie, { children: [
                        /* @__PURE__ */ e(cl, { className: "w-3.5 h-3.5" }),
                        /* @__PURE__ */ e("span", { children: "Dashboard" })
                      ] }) : /* @__PURE__ */ s(Ie, { children: [
                        /* @__PURE__ */ e(al, { className: "w-3.5 h-3.5" }),
                        /* @__PURE__ */ e("span", { children: "All" })
                      ] })
                    }
                  )
                ] }),
                !f && /* @__PURE__ */ e("div", { className: "text-xs text-dc-info mb-3 p-2 bg-dc-info-bg rounded border border-dc-info-border", children: "Showing only fields used in this dashboard" }),
                D && D.cubes.length > 0 ? /* @__PURE__ */ e(
                  nl,
                  {
                    schema: D,
                    schemaStatus: "success",
                    schemaError: null,
                    selectedFields: {
                      measures: k ? [k] : [],
                      dimensions: k ? [k] : [],
                      timeDimensions: k ? [k] : []
                    },
                    onFieldSelect: (p) => O(p),
                    onFieldDeselect: () => {
                    }
                  }
                ) : /* @__PURE__ */ e("div", { className: "text-center py-8 text-dc-text-muted text-sm", children: f ? /* @__PURE__ */ s("div", { children: [
                  /* @__PURE__ */ e("p", { className: "mb-2", children: "No schema available" }),
                  /* @__PURE__ */ e("p", { className: "text-xs", children: "Check your API connection" })
                ] }) : /* @__PURE__ */ s("div", { children: [
                  /* @__PURE__ */ e("p", { className: "mb-2", children: "No fields used in dashboard" }),
                  /* @__PURE__ */ e("p", { className: "text-xs", children: "Add portlets to the dashboard first, or toggle to show all fields" })
                ] }) })
              ] }) }),
              /* @__PURE__ */ e("div", { className: "flex-1 overflow-auto px-6 py-4 bg-dc-surface-secondary", children: t.isUniversalTime ? (
                /* Universal time filter - show DateRangeSelector */
                /* @__PURE__ */ s("div", { children: [
                  /* @__PURE__ */ s("div", { className: "mb-4 p-3 rounded-md bg-dc-info-bg border border-dc-info-border", children: [
                    /* @__PURE__ */ e("div", { className: "text-sm font-medium text-dc-info mb-1", children: "Universal Time Filter" }),
                    /* @__PURE__ */ e("div", { className: "text-xs text-dc-text-secondary", children: "This filter applies to all time dimensions in portlets it's mapped to. Select a date range below to filter data across all time-based charts." })
                  ] }),
                  /* @__PURE__ */ e("div", { className: "mt-4", children: /* @__PURE__ */ e(
                    is,
                    {
                      timeDimension: "__universal_time__",
                      availableTimeDimensions: ["__universal_time__"],
                      currentDateRange: (() => {
                        const p = m;
                        if (p.dateRange) return p.dateRange;
                        if (p.values)
                          return Array.isArray(p.values) && p.values.length === 1 && typeof p.values[0] == "string" ? p.values[0] : p.values;
                      })(),
                      onDateRangeChange: R,
                      onTimeDimensionChange: () => {
                      },
                      onRemove: () => {
                      },
                      hideFieldSelector: !0,
                      hideRemoveButton: !0
                    }
                  ) })
                ] })
              ) : (
                /* Regular filter - show FilterBuilder */
                /* @__PURE__ */ e(
                  Xc,
                  {
                    filters: [m],
                    schema: h(r),
                    query: {},
                    onFiltersChange: _
                  }
                )
              ) })
            ] }),
            /* @__PURE__ */ s("div", { className: "px-6 py-4 border-t border-dc-border flex items-center justify-between bg-dc-surface", children: [
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: d,
                  className: "px-4 py-2 text-sm font-medium text-dc-danger hover:bg-dc-danger-bg rounded-md transition-colors",
                  children: "Delete Filter"
                }
              ),
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: i,
                  className: "px-4 py-2 text-sm font-medium rounded-md transition-colors bg-dc-primary hover:bg-dc-primary-hover text-dc-primary-content",
                  children: "Done"
                }
              )
            ] })
          ]
        }
      )
    }
  );
}, il = z("filter"), ol = z("timeDimension"), dl = ({
  dashboardFilters: t,
  schema: r,
  onFilterChange: n,
  onDateRangeChange: a,
  convertToMetaResponse: c,
  isTimeDimensionField: l
}) => {
  const d = F((h) => {
    const { id: o, label: u, filter: m, isUniversalTime: x } = h;
    if (!("member" in m))
      return null;
    const f = m, S = l(f.member);
    if (x || S && f.operator === "inDateRange") {
      let T = f.dateRange;
      return !T && f.values && (Array.isArray(f.values) && f.values.length === 1 && typeof f.values[0] == "string" ? T = f.values[0] : T = f.values), /* @__PURE__ */ s("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ s("div", { className: "flex items-center gap-1.5 px-1", children: [
          x && /* @__PURE__ */ e(ol, { className: "w-3.5 h-3.5 shrink-0", style: { color: "var(--dc-primary)" } }),
          /* @__PURE__ */ e(
            "label",
            {
              className: "text-xs font-semibold uppercase tracking-wide truncate",
              style: { color: "var(--dc-text-secondary)" },
              title: x ? `${u} (applies to all time dimensions)` : u,
              children: u
            }
          )
        ] }),
        /* @__PURE__ */ e(
          is,
          {
            timeDimension: x ? "__universal_time__" : f.member,
            availableTimeDimensions: x ? ["__universal_time__"] : [f.member],
            currentDateRange: T,
            onDateRangeChange: (D, k) => a(o, k),
            onTimeDimensionChange: () => {
            },
            onRemove: () => {
            },
            hideFieldSelector: !0,
            hideRemoveButton: !0
          }
        )
      ] }, o);
    }
    return /* @__PURE__ */ s("div", { className: "flex flex-col gap-1.5", children: [
      /* @__PURE__ */ e(
        "label",
        {
          className: "text-xs font-semibold uppercase tracking-wide truncate px-1",
          style: { color: "var(--dc-text-secondary)" },
          title: u,
          children: u
        }
      ),
      /* @__PURE__ */ e(
        Gr,
        {
          filter: f,
          index: 0,
          onFilterChange: (T, D) => {
            n(o, {
              ...h,
              filter: D
            });
          },
          onFilterRemove: () => {
          },
          schema: c(r),
          query: {},
          hideFieldSelector: !0,
          hideOperatorSelector: !0,
          hideRemoveButton: !0
        }
      )
    ] }, o);
  }, [r, c, l, n, a]);
  return t.length === 0 ? null : /* @__PURE__ */ s("div", { className: "px-4 py-3", children: [
    /* @__PURE__ */ s("div", { className: "flex items-center gap-2 mb-3", children: [
      /* @__PURE__ */ e(il, { className: "w-4 h-4 shrink-0", style: { color: "var(--dc-primary)" } }),
      /* @__PURE__ */ e("h3", { className: "text-sm font-semibold", style: { color: "var(--dc-text)" }, children: "Filters" }),
      t.length > 0 && /* @__PURE__ */ e(
        "span",
        {
          className: "px-1.5 py-0.5 rounded-full text-xs font-medium",
          style: {
            backgroundColor: "var(--dc-primary)",
            color: "white"
          },
          children: t.length
        }
      )
    ] }),
    /* @__PURE__ */ e("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4", children: t.map(d) })
  ] });
}, Er = z("filter"), dr = z("add"), ul = z("close"), ml = z("edit"), fl = z("chevronDown"), Tn = z("timeDimension"), hl = ({
  dashboardFilters: t,
  onAddFilter: r,
  onAddTimeFilter: n,
  onEditFilter: a,
  onRemoveFilter: c,
  selectedFilterId: l,
  onFilterSelect: d
}) => {
  const [h, o] = lt.useState(!1), u = (m) => {
    const { id: x, label: f, isUniversalTime: S } = m, T = l === x;
    return /* @__PURE__ */ s(
      "div",
      {
        className: "inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md border text-xs transition-all cursor-pointer hover:shadow-md",
        style: {
          backgroundColor: T ? "var(--dc-primary)" : "var(--dc-surface)",
          borderColor: T ? "var(--dc-primary)" : "var(--dc-border)",
          borderWidth: T ? "2px" : "1px",
          color: T ? "white" : "var(--dc-text)",
          boxShadow: T ? "0 0 0 3px rgba(var(--dc-primary-rgb), 0.1)" : "none"
        },
        onClick: () => {
          d && d(x);
        },
        children: [
          /* @__PURE__ */ e(
            S ? Tn : Er,
            {
              className: "w-3.5 h-3.5 shrink-0",
              style: { color: T ? "white" : "var(--dc-primary)" }
            }
          ),
          /* @__PURE__ */ e("span", { className: "font-medium truncate", children: f }),
          !T && /* @__PURE__ */ s("div", { className: "flex items-center gap-0.5 ml-1", onClick: (k) => k.stopPropagation(), children: [
            /* @__PURE__ */ e(
              "button",
              {
                onClick: () => a(x),
                className: "p-0.5 hover:bg-dc-hover rounded transition-colors",
                title: "Edit filter",
                children: /* @__PURE__ */ e(ml, { className: "w-3 h-3" })
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: () => c(x),
                className: "p-0.5 hover:bg-dc-danger-bg hover:text-dc-danger rounded transition-colors",
                title: "Remove filter",
                children: /* @__PURE__ */ e(ul, { className: "w-3 h-3" })
              }
            )
          ] })
        ]
      },
      x
    );
  };
  return /* @__PURE__ */ s(Ie, { children: [
    /* @__PURE__ */ s("div", { className: "md:hidden", children: [
      /* @__PURE__ */ s(
        "div",
        {
          className: "px-4 py-2 flex items-center justify-between cursor-pointer",
          onClick: () => o(!h),
          children: [
            /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ e(Er, { className: "w-4 h-4 shrink-0", style: { color: "var(--dc-primary)" } }),
              /* @__PURE__ */ e("h3", { className: "text-sm font-semibold", style: { color: "var(--dc-text)" }, children: "Filters" }),
              t.length > 0 && /* @__PURE__ */ e(
                "span",
                {
                  className: "px-1.5 py-0.5 rounded-full text-xs font-medium",
                  style: {
                    backgroundColor: "var(--dc-primary)",
                    color: "white"
                  },
                  children: t.length
                }
              ),
              /* @__PURE__ */ e(
                fl,
                {
                  className: `w-4 h-4 transition-transform ${h ? "" : "rotate-180"}`,
                  style: { color: "var(--dc-text-secondary)" }
                }
              )
            ] }),
            /* @__PURE__ */ s("div", { className: "flex items-center gap-1", children: [
              !t.some((m) => m.isUniversalTime) && /* @__PURE__ */ s(
                "button",
                {
                  onClick: (m) => {
                    m.stopPropagation(), n();
                  },
                  className: "inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-colors hover:opacity-80",
                  style: {
                    backgroundColor: "var(--dc-surface)",
                    color: "var(--dc-primary)",
                    border: "1px solid var(--dc-border)"
                  },
                  title: "Add date range filter (applies to all time dimensions)",
                  children: [
                    /* @__PURE__ */ e(dr, { className: "w-3.5 h-3.5" }),
                    /* @__PURE__ */ e(Tn, { className: "w-3.5 h-3.5" })
                  ]
                }
              ),
              /* @__PURE__ */ e(
                "button",
                {
                  onClick: (m) => {
                    m.stopPropagation(), r();
                  },
                  className: "inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-colors hover:opacity-80",
                  style: {
                    backgroundColor: "var(--dc-primary)",
                    color: "white"
                  },
                  children: /* @__PURE__ */ e(dr, { className: "w-3.5 h-3.5" })
                }
              )
            ] })
          ]
        }
      ),
      t.length > 0 && !h && /* @__PURE__ */ e("div", { className: "px-4 pb-2 flex flex-col gap-2", children: t.map(u) }),
      t.length === 0 && !h && /* @__PURE__ */ e("div", { className: "px-4 pb-2", children: /* @__PURE__ */ e(
        "div",
        {
          className: "text-xs p-2 rounded-md text-center",
          style: {
            backgroundColor: "var(--dc-surface-secondary)",
            color: "var(--dc-text-secondary)"
          },
          children: 'No filters configured. Click "Add" to create one.'
        }
      ) })
    ] }),
    /* @__PURE__ */ s("div", { className: "hidden md:flex md:items-center md:gap-3 px-4 py-2", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center gap-2 shrink-0", children: [
        /* @__PURE__ */ e(Er, { className: "w-4 h-4 shrink-0", style: { color: "var(--dc-primary)" } }),
        /* @__PURE__ */ e("h3", { className: "text-sm font-semibold whitespace-nowrap", style: { color: "var(--dc-text)" }, children: "Filters" }),
        t.length > 0 && /* @__PURE__ */ e(
          "span",
          {
            className: "px-1.5 py-0.5 rounded-full text-xs font-medium",
            style: {
              backgroundColor: "var(--dc-primary)",
              color: "white"
            },
            children: t.length
          }
        )
      ] }),
      t.length > 0 ? /* @__PURE__ */ e("div", { className: "flex flex-wrap gap-2 flex-1 min-w-0", children: t.map(u) }) : /* @__PURE__ */ e("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ e(
        "div",
        {
          className: "text-xs px-3 py-1 rounded-md inline-block",
          style: {
            backgroundColor: "var(--dc-surface-secondary)",
            color: "var(--dc-text-secondary)"
          },
          children: 'No filters configured. Click "Add" to create one.'
        }
      ) }),
      /* @__PURE__ */ s("div", { className: "flex items-center gap-1 shrink-0", children: [
        !t.some((m) => m.isUniversalTime) && /* @__PURE__ */ s(
          "button",
          {
            onClick: n,
            className: "inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-colors hover:opacity-80",
            style: {
              backgroundColor: "var(--dc-surface)",
              color: "var(--dc-primary)",
              border: "1px solid var(--dc-border)"
            },
            title: "Add date range filter (applies to all time dimensions)",
            children: [
              /* @__PURE__ */ e(dr, { className: "w-3.5 h-3.5" }),
              /* @__PURE__ */ e("span", { children: "Date Range" })
            ]
          }
        ),
        /* @__PURE__ */ s(
          "button",
          {
            onClick: r,
            className: "inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-colors hover:opacity-80",
            style: {
              backgroundColor: "var(--dc-primary)",
              color: "white"
            },
            children: [
              /* @__PURE__ */ e(dr, { className: "w-3.5 h-3.5" }),
              /* @__PURE__ */ e("span", { children: "Filter" })
            ]
          }
        )
      ] })
    ] })
  ] });
}, pl = ({
  dashboardFilters: t,
  editable: r,
  schema: n,
  dashboardConfig: a,
  onDashboardFiltersChange: c,
  onSaveFilters: l,
  selectedFilterId: d,
  onFilterSelect: h,
  isEditMode: o = !1
}) => {
  const [u, m] = H(null), [x, f] = H(!1), S = F((p) => p ? {
    cubes: p.cubes.map((b) => ({
      name: b.name,
      title: b.title || b.name,
      description: b.description || "",
      measures: b.measures.map((w) => ({
        name: w.name,
        title: w.title,
        type: w.type,
        description: "",
        shortTitle: w.shortTitle
      })),
      dimensions: b.dimensions.map((w) => ({
        name: w.name,
        title: w.title,
        type: w.type,
        description: "",
        shortTitle: w.shortTitle
      })),
      segments: b.segments?.map((w) => ({
        name: w.name,
        title: w.title,
        type: w.type,
        description: "",
        shortTitle: w.shortTitle
      })) || []
    }))
  } : null, []), T = F(() => `df_${Date.now()}_${Math.random().toString(36).substring(7)}`, []), D = F(() => {
    const p = {
      id: T(),
      label: `Filter ${t.length + 1}`,
      filter: {
        member: "",
        operator: "equals",
        values: []
      }
    };
    m(p), f(!0);
  }, [t.length, T]), k = F(() => {
    const p = {
      id: T(),
      label: "Date Range Filter",
      isUniversalTime: !0,
      filter: {
        member: "__universal_time__",
        // Placeholder, not used in merge logic
        operator: "inDateRange",
        values: ["last 30 days"]
      }
    }, b = [...t, p];
    c(b);
  }, [T, t, c]), A = F((p) => {
    const b = t.find((w) => w.id === p);
    b && (m(b), f(!0));
  }, [t]), _ = F((p) => {
    const b = t.filter((w) => w.id !== p);
    c(b), u?.id === p && (m(null), f(!1));
  }, [t, u, c]), O = F(async (p) => {
    const b = t.findIndex((v) => v.id === p.id);
    let w;
    if (b >= 0 ? w = t.map(
      (v) => v.id === p.id ? p : v
    ) : w = [...t, p], c(w), l)
      try {
        await l(w);
      } catch (v) {
        throw console.error("Failed to save filters:", v), v;
      }
  }, [t, c, l]), R = F(() => {
    m(null), f(!1);
  }, []), y = F((p, b) => {
    const w = t.map((v) => {
      if (v.id === p) {
        const M = v.filter;
        if ("member" in M)
          return {
            ...v,
            filter: {
              ...M,
              dateRange: b,
              values: Array.isArray(b) ? b : [b]
            }
          };
      }
      return v;
    });
    c(w);
  }, [t, c]), i = F((p, b) => {
    const w = t.map(
      (v) => v.id === p ? b : v
    );
    c(w);
  }, [t, c]), g = F((p) => n ? n.cubes.some(
    (b) => b.dimensions.some((w) => w.name === p && w.type === "time")
  ) : !1, [n]);
  return !r || !o && t.length === 0 ? null : /* @__PURE__ */ s(
    "div",
    {
      className: "mb-4 border rounded-lg",
      style: {
        borderColor: "var(--dc-border)",
        backgroundColor: "var(--dc-surface)",
        boxShadow: "var(--dc-shadow-sm)"
      },
      children: [
        o ? /* @__PURE__ */ e(
          hl,
          {
            dashboardFilters: t,
            onAddFilter: D,
            onAddTimeFilter: k,
            onEditFilter: A,
            onRemoveFilter: _,
            selectedFilterId: d,
            onFilterSelect: h
          }
        ) : (
          /* View Mode - Read-only interactive filters */
          /* @__PURE__ */ e(
            dl,
            {
              dashboardFilters: t,
              schema: n,
              onFilterChange: i,
              onDateRangeChange: y,
              convertToMetaResponse: S,
              isTimeDimensionField: g
            }
          )
        ),
        r && x && u && /* @__PURE__ */ e(
          ll,
          {
            filter: u,
            schema: n,
            dashboardConfig: a,
            isOpen: x,
            onSave: O,
            onClose: R,
            onDelete: () => _(u.id),
            convertToMetaResponse: S
          }
        )
      ]
    }
  );
};
function xl({
  scaleFactor: t,
  designWidth: r,
  children: n
}) {
  const [a, c] = H(0), l = Te(null);
  Ce(() => {
    if (!l.current) return;
    const h = new ResizeObserver((o) => {
      c(o[0]?.contentRect.height ?? 0);
    });
    return h.observe(l.current), c(l.current.offsetHeight || 0), () => h.disconnect();
  }, []);
  const d = a * t;
  return /* @__PURE__ */ e(
    "div",
    {
      className: "scaled-grid-container",
      style: {
        height: d > 0 ? d : "auto",
        overflow: "hidden",
        width: "100%"
      },
      children: /* @__PURE__ */ e(
        "div",
        {
          ref: l,
          className: "scaled-grid-inner",
          style: {
            transform: `scale(${t})`,
            transformOrigin: "top left",
            width: r
          },
          children: n
        }
      )
    }
  );
}
const bl = z("refresh");
function gl(t) {
  if (!t) return null;
  let r = t.parentElement;
  for (; r; ) {
    const n = window.getComputedStyle(r), a = n.overflowY, c = n.overflowX, l = a === "auto" || a === "scroll" || c === "auto" || c === "scroll", d = r.scrollHeight > r.clientHeight || r.scrollWidth > r.clientWidth;
    if (l && d)
      return r;
    if (r === document.body) break;
    r = r.parentElement;
  }
  return null;
}
function yl({
  config: t,
  colorPalette: r,
  dashboardFilters: n,
  onPortletRefresh: a
}) {
  const c = Te({}), [l, d] = H(null), h = Te(null), o = F((x) => {
    h.current = x, x && d(gl(x));
  }, []), u = Oe(() => [...t.portlets].sort((x, f) => x.y !== f.y ? x.y - f.y : x.x - f.x), [t.portlets]), m = (x) => {
    c.current[x]?.refresh(), a?.(x);
  };
  return /* @__PURE__ */ e(In, { value: l, children: /* @__PURE__ */ e("div", { ref: o, className: "mobile-stacked-layout space-y-4 px-2", children: u.map((x) => {
    const f = Math.max(300, x.h * 80), S = x.displayConfig?.hideHeader ? 0 : 40, T = f - S - 24;
    return /* @__PURE__ */ s(
      "div",
      {
        "data-portlet-id": x.id,
        className: "bg-dc-surface border border-dc-border rounded-lg flex flex-col",
        style: {
          height: f,
          boxShadow: "var(--dc-shadow-sm)"
        },
        children: [
          !x.displayConfig?.hideHeader && /* @__PURE__ */ s("div", { className: "flex items-center justify-between px-3 py-2 border-b border-dc-border shrink-0 bg-dc-surface-secondary rounded-t-lg", children: [
            /* @__PURE__ */ e("h3", { className: "font-semibold text-sm text-dc-text truncate flex-1", children: x.title }),
            /* @__PURE__ */ e("div", { className: "flex items-center gap-1 shrink-0 ml-2", children: /* @__PURE__ */ e(
              "button",
              {
                onClick: () => m(x.id),
                className: "p-1 bg-transparent border-none rounded-sm text-dc-text-secondary cursor-pointer hover:bg-dc-surface-hover transition-colors",
                title: "Refresh portlet data",
                children: /* @__PURE__ */ e(bl, { style: { width: "16px", height: "16px", color: "currentColor" } })
              }
            ) })
          ] }),
          /* @__PURE__ */ e(
            "div",
            {
              className: "px-2 py-3 overflow-visible flex flex-col",
              style: { height: T },
              children: /* @__PURE__ */ e(
                gr,
                {
                  ref: (D) => {
                    c.current[x.id] = D;
                  },
                  query: x.query,
                  chartType: x.chartType,
                  chartConfig: x.chartConfig,
                  displayConfig: x.displayConfig,
                  dashboardFilters: n,
                  dashboardFilterMapping: x.dashboardFilterMapping,
                  eagerLoad: x.eagerLoad ?? t.eagerLoad ?? !1,
                  title: x.title,
                  height: T,
                  colorPalette: r
                }
              )
            }
          )
        ]
      },
      x.id
    );
  }) }) });
}
const vl = z("measure"), Nl = z("refresh"), Sn = z("edit"), wl = z("delete"), An = z("add"), kl = z("copy"), _n = z("filter"), Cl = z("desktop"), Dl = z("segment"), Tl = z("table");
function Sl(t) {
  if (!t) return null;
  let r = t.parentElement;
  for (; r; ) {
    const n = window.getComputedStyle(r), a = n.overflowY, c = n.overflowX, l = a === "auto" || a === "scroll" || c === "auto" || c === "scroll", d = r.scrollHeight > r.clientHeight || r.scrollWidth > r.clientWidth;
    if (l && d)
      return r;
    if (r === document.body) break;
    r = r.parentElement;
  }
  return null;
}
const ur = {
  cols: 12,
  rowHeight: 80,
  minW: 2,
  minH: 2
}, Rr = () => `row-${Date.now()}`, Al = (t) => ({
  cols: t.grid?.cols ?? ur.cols,
  rowHeight: t.grid?.rowHeight ?? ur.rowHeight,
  minW: t.grid?.minW ?? ur.minW,
  minH: t.grid?.minH ?? ur.minH
}), wt = (t, r) => {
  const n = t.length;
  if (n === 0) return [];
  const { cols: a, minW: c } = r, l = c * n;
  if (l > a) {
    const u = Math.floor(a / n), m = a % n;
    return t.map((x, f) => ({
      portletId: x,
      w: u + (f < m ? 1 : 0)
    }));
  }
  const d = a - l, h = Math.floor(d / n), o = d % n;
  return t.map((u, m) => ({
    portletId: u,
    w: c + h + (m < o ? 1 : 0)
  }));
}, os = (t, r) => {
  if (t.length === 0) return [];
  const { cols: n, minW: a } = r, c = t.map((h) => ({
    ...h,
    w: Math.max(a, h.w)
  }));
  let l = c.reduce((h, o) => h + o.w, 0);
  if (l === n) return c;
  if (l < n) {
    let h = n - l, o = 0;
    for (; h > 0; )
      c[o % c.length].w += 1, h -= 1, o += 1;
    return c;
  }
  let d = l - n;
  for (let h = c.length - 1; h >= 0 && d > 0; h -= 1) {
    const o = c[h], u = Math.max(0, o.w - a);
    if (u === 0) continue;
    const m = Math.min(u, d);
    o.w -= m, d -= m;
  }
  return c;
}, Or = (t, r) => {
  if (t.length === 0) return [];
  const n = [...t].sort((c, l) => c.y !== l.y ? c.y - l.y : c.x - l.x), a = /* @__PURE__ */ new Map();
  return n.forEach((c) => {
    const l = a.get(c.y) ?? [];
    l.push(c), a.set(c.y, l);
  }), Array.from(a.entries()).sort(([c], [l]) => c - l).map(([c, l]) => {
    const d = Math.max(
      r.minH,
      ...l.map((o) => o.h)
    ), h = l.map((o) => o.id);
    return {
      id: `row-${c}`,
      h: d,
      columns: wt(h, r)
    };
  });
}, mr = (t, r, n) => {
  const a = new Set(r.map((c) => c.id));
  return t.map((c) => ({
    ...c,
    h: Math.max(n.minH, c.h),
    columns: os(
      c.columns.filter((l) => a.has(l.portletId)),
      n
    )
  })).filter((c) => c.columns.length > 0);
}, En = (t, r) => {
  const n = new Map(r.map((d) => [d.id, d]));
  let a = 0;
  const c = [];
  t.forEach((d) => {
    let h = 0;
    d.columns.forEach((o) => {
      const u = n.get(o.portletId);
      u && (c.push({
        ...u,
        x: h,
        y: a,
        w: o.w,
        h: d.h
      }), h += o.w);
    }), a += d.h;
  });
  const l = new Set(c.map((d) => d.id));
  return r.forEach((d) => {
    l.has(d.id) || c.push(d);
  }), c;
};
function _l({
  config: t,
  editable: r = !1,
  dashboardFilters: n,
  loadingComponent: a,
  onConfigChange: c,
  onPortletRefresh: l,
  onSave: d,
  colorPalette: h,
  schema: o,
  onDashboardFiltersChange: u,
  dashboardModes: m
}) {
  const { features: x } = jt(), {
    containerRef: f,
    containerWidth: S,
    displayMode: T,
    scaleFactor: D,
    isEditable: k,
    designWidth: A
  } = vs(), _ = m && m.length > 0 ? m : ["rows", "grid"], O = _.includes("rows") ? "rows" : _[0] ?? "grid", R = t.layoutMode ?? "grid", y = _.includes(R) ? R : O, i = Oe(() => Al(t), [t]), [g, p] = H(null), b = Te(null), w = Te(null), v = F((V) => {
    if (b.current = V, f(V), V) {
      const G = Sl(V);
      p(G), w.current = G;
    }
  }, [f]), M = T === "desktop" ? S : A, [$, C] = H(null), L = Te(null), I = Te(null), [E, K] = H(!1), P = Te({}), Ne = Te({}), [ye, Ue] = H(!1), [Q, ue] = H([]), [me, J] = H(!1), [Y, ge] = H(null), ee = r && me && k && !Y, j = r && me && k && !Y && _.length > 1;
  Ce(() => {
    (!me || !k) && Y && ge(null);
  }, [me, k, Y]), Ce(() => {
    !k && me && J(!1);
  }, [k, me]);
  const re = ea(w, {
    threshold: 20,
    debounceMs: 150
  }), [xe, $e] = H(!1), [Me, ze] = H(null), [ve, Be] = H(!1), [U, fe] = H(null), [ae, Ae] = H({});
  Ce(() => {
    L.current = $;
  }, [$]);
  const ke = Oe(() => {
    if (y !== "rows") return [];
    const V = $ ?? t.rows ?? Or(t.portlets, i);
    return mr(V, t.portlets, i);
  }, [y, $, t.rows, t.portlets, i]), Fe = F(async (V, G = !0, ne) => {
    if (!c) return;
    const se = ne ?? t.portlets, he = mr(V, se, i), _e = En(he, se), de = {
      ...t,
      layoutMode: "rows",
      rows: he,
      portlets: _e
    };
    if (C(null), c(de), G && d)
      try {
        await d(de);
      } catch (De) {
        console.error("Auto-save failed after row layout change:", De);
      }
  }, [t, i, c, d]);
  Ce(() => {
    const V = setTimeout(() => {
      Ue(!0);
      const G = t.portlets.map((ne) => ({
        i: ne.id,
        x: ne.x,
        y: ne.y,
        w: ne.w,
        h: ne.h
      }));
      ue(G);
    }, 200);
    return () => clearTimeout(V);
  }, [t.portlets]), Ce(() => {
    const V = (G) => {
      G.key === "Escape" && Y && ge(null);
    };
    return window.addEventListener("keydown", V), () => {
      window.removeEventListener("keydown", V);
    };
  }, [Y]);
  const Ke = F((V) => {
    if (!ye || Q.length === 0) return !1;
    for (const G of V) {
      const ne = Q.find((se) => se.i === G.i);
      if (ne && (ne.x !== G.x || ne.y !== G.y || ne.w !== G.w || ne.h !== G.h))
        return !0;
    }
    return !1;
  }, [ye, Q]), yt = F((V) => {
  }, []), it = F(async (V, G, ne, se, he, _e) => {
    if (!r || !me || !d || !ye) return;
    const de = [...V];
    if (!Ke(de))
      return;
    const De = t.portlets.map((Je) => {
      const je = de.find((rt) => rt.i === Je.id);
      return je ? {
        ...Je,
        x: je.x,
        y: je.y,
        w: je.w,
        h: je.h
      } : Je;
    }), Ye = {
      ...t,
      portlets: De,
      layouts: {
        ...t.layouts,
        lg: de
        // Only save the large layout, let RGL handle responsive adjustments
      }
    };
    ue(de), c?.(Ye);
    try {
      await d(Ye);
    } catch (Je) {
      console.error("Auto-save failed after drag:", Je);
    }
  }, [t.portlets, t.layouts, r, me, c, d, ye, Ke]), pt = F(async (V, G, ne, se, he, _e) => {
    if (!r || !me || !c || !ye) return;
    const de = [...V];
    if (!Ke(de))
      return;
    const De = t.portlets.map((Je) => {
      const je = de.find((rt) => rt.i === Je.id);
      return je ? {
        ...Je,
        x: je.x,
        y: je.y,
        w: je.w,
        h: je.h
      } : Je;
    }), Ye = {
      ...t,
      portlets: De,
      layouts: {
        ...t.layouts,
        lg: de
        // Only save the large layout, let RGL handle responsive adjustments
      }
    };
    if (ue(de), c(Ye), d)
      try {
        await d(Ye);
      } catch (Je) {
        console.error("Auto-save failed after resize:", Je);
      }
  }, [t.portlets, t.layouts, r, me, c, d, ye, Ke]), Dt = F(async (V) => {
    if (!c || V === y || !j || !_.includes(V)) return;
    const G = mr(
      t.rows && t.rows.length > 0 ? t.rows : Or(t.portlets, i),
      t.portlets,
      i
    ), ne = En(G, t.portlets), se = {
      ...t,
      layoutMode: V,
      rows: G,
      portlets: ne
    };
    if (C(null), c(se), d)
      try {
        await d(se);
      } catch (he) {
        console.error("Auto-save failed after layout mode switch:", he);
      }
  }, [_, j, t, i, y, c, d]), Mt = F((V, G) => {
    if (!ee) return;
    G.preventDefault();
    const ne = G.clientY, se = ke.map((de) => ({
      ...de,
      columns: de.columns.map((De) => ({ ...De }))
    })), he = (de) => {
      const De = de.clientY - ne, Ye = Math.round(De / i.rowHeight), Je = se.map((je, rt) => rt !== V ? je : {
        ...je,
        h: Math.max(i.minH, je.h + Ye)
      });
      C(Je);
    }, _e = () => {
      document.removeEventListener("mousemove", he), document.removeEventListener("mouseup", _e);
      const de = L.current ?? se;
      Fe(de);
    };
    document.addEventListener("mousemove", he), document.addEventListener("mouseup", _e);
  }, [ee, i, ke, Fe]), Vt = F((V, G, ne) => {
    if (!ee) return;
    ne.preventDefault();
    const se = ne.clientX, he = ke.map((ut) => ({
      ...ut,
      columns: ut.columns.map((Ut) => ({ ...Ut }))
    })), _e = he[V], de = _e?.columns[G], De = _e?.columns[G + 1];
    if (!_e || !de || !De) return;
    const je = (M - (_e.columns.length - 1) * 16) / i.cols, rt = (ut) => {
      const Ut = ut.clientX - se, Gt = Math.round(Ut / je);
      if (Gt === 0) {
        C(he);
        return;
      }
      let st = de.w + Gt, vt = De.w - Gt;
      if (st < i.minW) {
        const pe = i.minW - st;
        st = i.minW, vt -= pe;
      }
      if (vt < i.minW) {
        const pe = i.minW - vt;
        vt = i.minW, st -= pe;
      }
      if (st < i.minW || vt < i.minW) return;
      const X = he.map((pe, Re) => {
        if (Re !== V) return pe;
        const qe = pe.columns.map((We, et) => et === G ? { ...We, w: st } : et === G + 1 ? { ...We, w: vt } : We);
        return {
          ...pe,
          columns: os(qe, i)
        };
      });
      C(X);
    }, nt = () => {
      document.removeEventListener("mousemove", rt), document.removeEventListener("mouseup", nt);
      const ut = L.current ?? he;
      Fe(ut);
    };
    document.addEventListener("mousemove", rt), document.addEventListener("mouseup", nt);
  }, [ee, i, M, ke, Fe]), Ht = F((V, G, ne, se) => {
    ee && (I.current = { rowIndex: V, colIndex: G, portletId: ne }, K(!0), se.dataTransfer.effectAllowed = "move", se.dataTransfer.setData("text/plain", ne));
  }, [ee]), zt = F(() => {
    I.current = null, K(!1);
  }, []), Qt = F((V, G) => {
    const ne = I.current;
    if (!ne) return;
    const se = ke.map((nt) => ({
      ...nt,
      columns: nt.columns.map((ut) => ({ ...ut }))
    })), he = ne.rowIndex, _e = se[he];
    if (!_e) return;
    const [de] = _e.columns.splice(ne.colIndex, 1);
    let De = !1;
    _e.columns.length === 0 && (se.splice(he, 1), De = !0);
    let Ye = V;
    De && he < V && (Ye -= 1);
    const Je = se[Ye];
    if (!Je) return;
    let je = G ?? Je.columns.length;
    !De && he === Ye && G !== null && G > ne.colIndex && (je -= 1), Je.columns.splice(je, 0, de), (he !== Ye || De) && (De || (se[he] = {
      ...se[he],
      columns: wt(
        se[he].columns.map((nt) => nt.portletId),
        i
      )
    }), se[Ye] = {
      ...se[Ye],
      columns: wt(
        se[Ye].columns.map((nt) => nt.portletId),
        i
      )
    }), Fe(se);
  }, [i, ke, Fe]), It = F((V) => {
    const G = I.current;
    if (!G) return;
    const ne = ke.map((de) => ({
      ...de,
      columns: de.columns.map((De) => ({ ...De }))
    })), se = ne[G.rowIndex];
    if (!se) return;
    const [he] = se.columns.splice(G.colIndex, 1);
    se.columns.length === 0 ? ne.splice(G.rowIndex, 1) : se.columns = wt(
      se.columns.map((de) => de.portletId),
      i
    );
    const _e = {
      id: Rr(),
      h: Math.max(i.minH, 5),
      columns: wt([he.portletId], i)
    };
    ne.splice(V, 0, _e), Fe(ne);
  }, [i, ke, Fe]), Tt = F((V) => {
    const G = Ne.current[V];
    G && G.refresh && G.refresh(), l && l(V);
  }, [l]), $t = F(() => {
    ze(null), $e(!0);
  }, []), Ft = F((V) => {
    ze(V), $e(!0);
  }, []), ot = F(async (V) => {
    if (!c) return;
    let G = [...t.portlets], ne = !1, se = null;
    if (Me) {
      const he = G.findIndex((_e) => _e.id === Me.id);
      he !== -1 && (G[he] = V);
    } else {
      ne = !0;
      const he = {
        ...V,
        id: `portlet-${Date.now()}`,
        x: 0,
        y: 0
      };
      se = he.id;
      const _e = G.map((De) => ({ i: De.id, x: De.x, y: De.y, w: De.w, h: De.h }));
      let de = 0;
      _e.forEach((De) => {
        De.y + De.h > de && (de = De.y + De.h);
      }), he.y = de, G.push(he);
    }
    if (y === "rows") {
      const he = ke.length > 0 ? ke.map((de) => ({
        ...de,
        columns: de.columns.map((De) => ({ ...De }))
      })) : mr(
        t.rows ?? Or(t.portlets, i),
        G,
        i
      ), _e = ne && se ? [
        ...he,
        {
          id: Rr(),
          h: Math.max(i.minH, 5),
          columns: wt([se], i)
        }
      ] : he;
      await Fe(_e, !0, G);
    } else {
      const he = {
        ...t,
        portlets: G
      };
      if (c(he), d)
        try {
          await d(he);
        } catch (_e) {
          console.error("Auto-save failed:", _e);
        }
    }
    $e(!1), ze(null), ne && se && setTimeout(() => {
      const he = () => {
        let _e = P.current[se];
        return _e || (_e = document.querySelector(`[data-portlet-id="${se}"]`)), _e ? (_e.scrollIntoView({
          behavior: "smooth",
          block: "center",
          inline: "nearest"
        }), !0) : !1;
      };
      he() || setTimeout(() => {
        he() || setTimeout(() => {
          he();
        }, 300);
      }, 200);
    }, 200);
  }, [t, Me, i, y, c, d, ke, Fe]), St = F(async (V) => {
    if (c && window.confirm("Are you sure you want to delete this portlet?")) {
      const G = t.portlets.filter((ne) => ne.id !== V);
      if (y === "rows") {
        const ne = ke.map((se) => ({
          ...se,
          columns: se.columns.filter((he) => he.portletId !== V)
        })).filter((se) => se.columns.length > 0).map((se) => ({
          ...se,
          columns: wt(
            se.columns.map((he) => he.portletId),
            i
          )
        }));
        await Fe(ne, !0, G);
      } else {
        const ne = {
          ...t,
          portlets: G
        };
        if (c(ne), d)
          try {
            await d(ne);
          } catch (se) {
            console.error("Auto-save failed:", se);
          }
      }
    }
  }, [t, i, y, c, d, ke, Fe]), At = F(async (V) => {
    if (!c) return;
    const G = t.portlets.find((de) => de.id === V);
    if (!G) return;
    const ne = {
      ...G,
      id: `portlet-${Date.now()}`,
      title: `${G.title} Duplicated`,
      x: 0,
      y: 0
    }, se = t.portlets.map((de) => ({ i: de.id, x: de.x, y: de.y, w: de.w, h: de.h }));
    let he = 0;
    se.forEach((de) => {
      de.y + de.h > he && (he = de.y + de.h);
    }), ne.y = he;
    const _e = [...t.portlets, ne];
    if (y === "rows") {
      const De = [
        ...ke.map((Ye) => ({
          ...Ye,
          columns: Ye.columns.map((Je) => ({ ...Je }))
        })),
        {
          id: Rr(),
          h: Math.max(i.minH, 5),
          columns: wt([ne.id], i)
        }
      ];
      await Fe(De, !0, _e);
    } else {
      const de = {
        ...t,
        portlets: _e
      };
      if (c(de), d)
        try {
          await d(de);
        } catch (De) {
          console.error("Auto-save failed:", De);
        }
    }
    setTimeout(() => {
      const de = () => {
        let De = P.current[ne.id];
        return De || (De = document.querySelector(`[data-portlet-id="${ne.id}"]`)), De ? (De.scrollIntoView({
          behavior: "smooth",
          block: "center",
          inline: "nearest"
        }), !0) : !1;
      };
      de() || setTimeout(() => {
        de() || setTimeout(() => {
          de();
        }, 300);
      }, 200);
    }, 200);
  }, [t, i, y, c, d, ke, Fe]), _t = F(async (V) => {
    if (!c) return;
    const G = {
      ...t,
      colorPalette: V
    };
    if (c(G), d)
      try {
        await d(G);
      } catch (ne) {
        console.error("Auto-save failed:", ne);
      }
  }, [t, c, d]), Et = F((V) => {
    fe(V), Be(!0);
  }, []), dt = F(async (V) => {
    if (!c || !U) return;
    const G = t.portlets.map((se) => se.id === U.id ? {
      ...se,
      dashboardFilterMapping: V
    } : se), ne = {
      ...t,
      portlets: G
    };
    if (c(ne), d)
      try {
        await d(ne);
      } catch (se) {
        console.error("Auto-save failed:", se);
      }
  }, [t, U, c, d]), N = F((V, G) => {
    Ae((ne) => ({
      ...ne,
      [V]: G
    }));
  }, []), q = F((V, G) => {
    P.current[V] = G;
  }, []), Z = F((V, G) => {
    Ne.current[V] = G;
  }, []), we = Oe(() => ({
    RefreshIcon: Nl,
    EditIcon: Sn,
    DeleteIcon: wl,
    CopyIcon: kl,
    FilterIcon: _n
  }), []), Ve = F(async (V, G) => {
    if (!c) return;
    const ne = t.portlets.map((he) => {
      if (he.id === V) {
        const _e = he.dashboardFilterMapping || [], de = _e.includes(G);
        return {
          ...he,
          dashboardFilterMapping: de ? _e.filter((De) => De !== G) : [..._e, G]
        };
      }
      return he;
    }), se = {
      ...t,
      portlets: ne
    };
    if (c(se), d)
      try {
        await d(se);
      } catch (he) {
        console.error("Auto-save failed:", he);
      }
  }, [t, c, d]), Qe = F((V) => {
    ge((G) => G === V ? null : V);
  }, []), oe = F(async (V) => {
    if (!c) return;
    const G = t.portlets.map((se) => {
      const he = se.dashboardFilterMapping || [];
      return he.includes(V) ? se : {
        ...se,
        dashboardFilterMapping: [...he, V]
      };
    }), ne = {
      ...t,
      portlets: G
    };
    if (c(ne), d)
      try {
        await d(ne);
      } catch (se) {
        console.error("Auto-save failed:", se);
      }
  }, [t, c, d]), le = Y ? n?.find((V) => V.id === Y) : null, B = F((V, G, ne) => /* @__PURE__ */ e(
    sa,
    {
      portlet: V,
      editable: r,
      isEditMode: me,
      selectedFilterId: Y,
      debugData: ae[V.id],
      dashboardFilters: n,
      configEagerLoad: t.eagerLoad,
      loadingComponent: a,
      colorPalette: h,
      containerProps: G,
      headerProps: ne,
      onToggleFilter: Ve,
      onRefresh: Tt,
      onDuplicate: At,
      onEdit: Ft,
      onDelete: St,
      onOpenFilterConfig: Et,
      onDebugDataReady: N,
      setPortletRef: q,
      setPortletComponentRef: Z,
      icons: we
    }
  ), [
    r,
    me,
    Y,
    ae,
    n,
    t.eagerLoad,
    a,
    h,
    Ve,
    Tt,
    At,
    Ft,
    St,
    Et,
    N,
    q,
    Z,
    we
  ]);
  if (!t.portlets || t.portlets.length === 0)
    return /* @__PURE__ */ s(Ie, { children: [
      /* @__PURE__ */ e("div", { className: "flex justify-center items-center min-h-[50vh]", children: /* @__PURE__ */ s("div", { className: "text-center", children: [
        /* @__PURE__ */ e(vl, { style: { width: "64px", height: "64px", color: "var(--dc-text-muted)", margin: "0 auto 16px auto" } }),
        /* @__PURE__ */ e("h3", { className: "text-lg font-semibold mb-2 text-dc-text", children: "No Portlets" }),
        /* @__PURE__ */ e("p", { className: "text-sm text-dc-text-secondary mb-4", children: "Add your first portlet to start visualizing your data" }),
        r && /* @__PURE__ */ s(
          "button",
          {
            onClick: $t,
            className: "inline-flex items-center px-4 py-2 border border-dc-border bg-dc-surface rounded-md focus:outline-hidden focus:ring-2",
            style: {
              color: "var(--dc-primary)",
              borderColor: "var(--dc-primary)"
            },
            onMouseEnter: (V) => V.currentTarget.style.backgroundColor = "var(--dc-surface-hover)",
            onMouseLeave: (V) => V.currentTarget.style.backgroundColor = "var(--dc-surface)",
            children: [
              /* @__PURE__ */ e(An, { className: "w-5 h-5 mr-2" }),
              "Add Portlet"
            ]
          }
        )
      ] }) }),
      x.useAnalysisBuilder ? /* @__PURE__ */ e(
        kn,
        {
          isOpen: xe,
          onClose: () => {
            $e(!1), ze(null);
          },
          onSave: ot,
          portlet: Me,
          title: Me ? "Edit Portlet" : "Add New Portlet",
          submitText: Me ? "Update Portlet" : "Add Portlet",
          colorPalette: h
        }
      ) : /* @__PURE__ */ e(
        wn,
        {
          isOpen: xe,
          onClose: () => {
            $e(!1), ze(null);
          },
          onSave: ot,
          portlet: Me,
          title: Me ? "Edit Portlet" : "Add New Portlet",
          submitText: Me ? "Update Portlet" : "Add Portlet",
          colorPalette: h
        }
      )
    ] });
  const te = t.portlets.map((V) => ({
    i: V.id,
    x: V.x,
    y: V.y,
    w: V.w,
    h: V.h,
    minW: i.minW,
    minH: i.minH,
    // 2 rows at 80px = 160px minimum
    // Only enable drag/resize in edit mode
    isDraggable: ee,
    isResizable: ee,
    ...ee ? { resizeHandles: ["s", "w", "e", "n", "se", "sw", "ne", "nw"] } : {}
  })), Le = y === "rows" ? /* @__PURE__ */ e(
    aa,
    {
      rows: ke,
      portlets: t.portlets,
      gridSettings: i,
      gridWidth: M,
      canEdit: ee,
      isDragging: E,
      onRowResize: Mt,
      onColumnResize: Vt,
      onPortletDragStart: Ht,
      onPortletDragEnd: zt,
      onRowDrop: Qt,
      onNewRowDrop: It,
      renderPortlet: B
    }
  ) : /* @__PURE__ */ e(
    Bs,
    {
      className: "layout",
      layout: te,
      onLayoutChange: yt,
      onDragStop: it,
      onResizeStop: pt,
      width: M,
      gridConfig: {
        cols: i.cols,
        rowHeight: i.rowHeight,
        margin: [16, 16],
        containerPadding: [0, 0]
      },
      dragConfig: {
        enabled: ee,
        handle: ".portlet-drag-handle"
      },
      resizeConfig: {
        enabled: ee,
        handles: ["s", "w", "e", "n", "se", "sw", "ne", "nw"],
        // Invisible but functional resize handles
        handleComponent: (V, G) => /* @__PURE__ */ e(
          "div",
          {
            ref: G,
            className: `react-resizable-handle react-resizable-handle-${V}`,
            style: { opacity: 0 }
          }
        )
      },
      compactor: qs,
      children: t.portlets.map((V) => /* @__PURE__ */ e("div", { children: B(V) }, V.id))
    }
  );
  return /* @__PURE__ */ e(In, { value: g, children: /* @__PURE__ */ s("div", { ref: v, className: "dashboard-grid-container w-full", style: { maxWidth: "100%", overflow: "hidden" }, children: [
    r && /* @__PURE__ */ s(
      "div",
      {
        className: `mb-4 flex justify-between items-center sticky top-0 z-10 px-4 py-4 bg-dc-surface-tertiary border border-dc-border rounded-lg transition-all duration-200 ${re ? "border-b" : ""}`,
        style: {
          boxShadow: re ? "var(--dc-shadow-md)" : "var(--dc-shadow-sm)"
        },
        children: [
          /* @__PURE__ */ s("div", { className: "flex items-center gap-4", children: [
            /* @__PURE__ */ s(
              "button",
              {
                onClick: () => k && J(!me),
                disabled: !k,
                className: `inline-flex items-center px-4 py-2 text-sm font-medium rounded-md transition-colors focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${k ? me ? "bg-dc-surface-secondary border border-dc-border hover:bg-dc-surface-hover" : "bg-dc-surface border border-dc-border hover:bg-dc-surface-hover" : "opacity-50 cursor-not-allowed bg-dc-surface-secondary border border-dc-border"}`,
                style: {
                  color: k ? "var(--dc-primary)" : "var(--dc-text-muted)",
                  borderColor: k ? me ? "var(--dc-border)" : "var(--dc-primary)" : "var(--dc-border)"
                },
                children: [
                  /* @__PURE__ */ e(Sn, { className: "w-4 h-4 mr-1.5" }),
                  me ? "Finished Editing" : "Edit"
                ]
              }
            ),
            me && _.length > 1 && /* @__PURE__ */ s("div", { className: "inline-flex rounded-md border border-dc-border overflow-hidden whitespace-nowrap", children: [
              /* @__PURE__ */ s(
                "button",
                {
                  onClick: () => Dt("grid"),
                  disabled: !j,
                  className: `inline-flex items-center gap-2 whitespace-nowrap px-3 py-1.5 text-sm font-medium transition-colors ${y === "grid" ? "bg-dc-surface-secondary text-dc-text shadow-inner" : "bg-dc-surface text-dc-text-secondary hover:bg-dc-surface-hover"} ${j ? "" : "cursor-not-allowed opacity-50"}`,
                  children: [
                    /* @__PURE__ */ e(Dl, { className: "w-4 h-4 shrink-0" }),
                    "Grid"
                  ]
                }
              ),
              /* @__PURE__ */ s(
                "button",
                {
                  onClick: () => Dt("rows"),
                  disabled: !j,
                  className: `inline-flex items-center gap-2 whitespace-nowrap px-3 py-1.5 text-sm font-medium transition-colors ${y === "rows" ? "bg-dc-surface-secondary text-dc-text shadow-inner" : "bg-dc-surface text-dc-text-secondary hover:bg-dc-surface-hover"} ${j ? "" : "cursor-not-allowed opacity-50"}`,
                  children: [
                    /* @__PURE__ */ e(Tl, { className: "w-4 h-4 shrink-0" }),
                    "Rows"
                  ]
                }
              )
            ] }),
            !k && /* @__PURE__ */ s("div", { className: "flex items-center gap-2 text-sm text-dc-text-secondary", children: [
              /* @__PURE__ */ e(Cl, { className: "w-4 h-4" }),
              /* @__PURE__ */ e("span", { children: "Desktop view required for editing" })
            ] }),
            me && k && /* @__PURE__ */ e("p", { className: "hidden md:block text-sm text-dc-text-secondary", children: "Drag • Resize • Auto-save" })
          ] }),
          /* @__PURE__ */ s("div", { className: "flex items-center gap-3", children: [
            me && /* @__PURE__ */ e(
              Yn,
              {
                currentPalette: t.colorPalette,
                onPaletteChange: _t,
                className: "shrink-0"
              }
            ),
            /* @__PURE__ */ s(
              "button",
              {
                onClick: $t,
                disabled: !me,
                className: `inline-flex items-center px-4 py-2 text-sm font-medium border rounded-md focus:outline-hidden focus:ring-2 focus:ring-offset-2 ${me ? "border-dc-border bg-dc-surface hover:bg-dc-surface-hover" : "border-dc-border bg-dc-surface-secondary cursor-not-allowed"}`,
                style: {
                  color: me ? "var(--dc-primary)" : "var(--dc-text-muted)",
                  borderColor: me ? "var(--dc-primary)" : "var(--dc-border)"
                },
                children: [
                  /* @__PURE__ */ e(An, { className: "w-5 h-5 mr-2" }),
                  "Add Portlet"
                ]
              }
            )
          ] })
        ]
      }
    ),
    /* @__PURE__ */ e(
      pl,
      {
        dashboardFilters: n || [],
        editable: r,
        schema: o || null,
        dashboardConfig: t,
        onDashboardFiltersChange: u || (() => {
        }),
        onSaveFilters: d ? async (V) => {
          const G = {
            ...t,
            filters: V
          };
          await d(G);
        } : void 0,
        selectedFilterId: Y,
        onFilterSelect: Qe,
        isEditMode: me
      }
    ),
    Y && le && /* @__PURE__ */ e(
      "div",
      {
        className: "mb-4 px-4 py-3 rounded-md border-2 transition-all",
        style: {
          backgroundColor: "var(--dc-primary)",
          borderColor: "var(--dc-primary)",
          color: "white"
        },
        children: /* @__PURE__ */ s("div", { className: "flex items-center justify-between flex-wrap gap-2", children: [
          /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-wrap", children: [
            /* @__PURE__ */ e(_n, { className: "w-5 h-5 shrink-0" }),
            /* @__PURE__ */ s("span", { className: "font-medium", children: [
              "Filter Selection Mode - Click portlets to toggle '",
              le.label,
              "'"
            ] }),
            /* @__PURE__ */ e("span", { className: "text-sm opacity-90 hidden sm:inline", children: "• Press ESC to exit" })
          ] }),
          /* @__PURE__ */ s("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ e(
              "button",
              {
                onClick: () => oe(Y),
                className: "px-3 py-1 rounded-md transition-colors text-sm font-medium",
                style: {
                  backgroundColor: "rgba(255, 255, 255, 0.2)",
                  color: "white"
                },
                onMouseEnter: (V) => V.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.3)",
                onMouseLeave: (V) => V.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.2)",
                children: "Select All"
              }
            ),
            /* @__PURE__ */ e(
              "button",
              {
                onClick: () => ge(null),
                className: "px-3 py-1 rounded-md transition-colors text-sm font-medium",
                style: {
                  backgroundColor: "rgba(255, 255, 255, 0.2)",
                  color: "white"
                },
                onMouseEnter: (V) => V.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.3)",
                onMouseLeave: (V) => V.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.2)",
                children: "Exit"
              }
            )
          ] })
        ] })
      }
    ),
    T === "mobile" ? /* @__PURE__ */ e(
      yl,
      {
        config: t,
        colorPalette: h,
        dashboardFilters: n,
        onPortletRefresh: Tt
      }
    ) : T === "scaled" ? /* @__PURE__ */ e(xl, { scaleFactor: D, designWidth: A, children: Le }) : Le,
    x.useAnalysisBuilder ? /* @__PURE__ */ e(
      kn,
      {
        isOpen: xe,
        onClose: () => {
          $e(!1), ze(null);
        },
        onSave: ot,
        portlet: Me,
        title: Me ? "Edit Portlet" : "Add New Portlet",
        submitText: Me ? "Update Portlet" : "Add Portlet",
        colorPalette: h
      }
    ) : /* @__PURE__ */ e(
      wn,
      {
        isOpen: xe,
        onClose: () => {
          $e(!1), ze(null);
        },
        onSave: ot,
        portlet: Me,
        title: Me ? "Edit Portlet" : "Add New Portlet",
        submitText: Me ? "Update Portlet" : "Add Portlet",
        colorPalette: h
      }
    ),
    /* @__PURE__ */ e(
      $c,
      {
        isOpen: ve,
        onClose: () => {
          Be(!1), fe(null);
        },
        dashboardFilters: n || [],
        currentMapping: U?.dashboardFilterMapping || [],
        onSave: dt,
        portletTitle: U?.title || ""
      }
    )
  ] }) });
}
function Ll({
  config: t,
  editable: r = !1,
  dashboardFilters: n,
  loadingComponent: a,
  onConfigChange: c,
  onSave: l,
  onDirtyStateChange: d
}) {
  const { meta: h, dashboardModes: o } = jt(), u = Te(t), m = Te(!1), x = Oe(() => {
    const k = t.filters || [], A = n || [];
    if (A.length === 0)
      return k;
    if (k.length === 0)
      return A;
    const _ = k.map((y) => {
      const i = A.find((g) => g.id === y.id);
      return i ? {
        ...y,
        // Preserve id, label, isUniversalTime from config
        filter: i.filter
        // Use filter values from prop override
      } : y;
    }), O = new Set(k.map((y) => y.id)), R = A.filter((y) => !O.has(y.id));
    return [..._, ...R];
  }, [t.filters, n]), f = F(async (k) => {
    if (m.current) {
      d && d(!0);
      try {
        l && await l(k), u.current = k, d && d(!1);
      } catch (A) {
        throw console.error("Save failed:", A), A;
      }
    }
  }, [l, d]), S = F((k) => {
    c && c(k);
    const A = JSON.stringify(k), _ = JSON.stringify(u.current);
    A !== _ && (m.current = !0, d && d(!0));
  }, [c, d]), T = F((k) => {
    if (!n || n.length === 0) {
      const A = {
        ...t,
        filters: k
      };
      S(A);
    } else
      console.warn("Dashboard filters are controlled via props - config changes ignored");
  }, [t, n, S]), D = Oe(() => {
    const k = t.colorPalette;
    return zr(k);
  }, [t.colorPalette]);
  return /* @__PURE__ */ e("div", { className: "w-full", children: /* @__PURE__ */ e(
    _l,
    {
      config: t,
      editable: r,
      dashboardFilters: x,
      loadingComponent: a,
      onConfigChange: S,
      onSave: f,
      colorPalette: D,
      schema: h,
      dashboardModes: o,
      onDashboardFiltersChange: T
    }
  ) });
}
function jl({
  portlet: t,
  editable: r = !1,
  onEdit: n,
  onDelete: a,
  onRefresh: c
}) {
  const [l, d] = H(null), h = F((o) => {
    d(o);
  }, []);
  return /* @__PURE__ */ s("div", { className: "bg-dc-surface border border-dc-border rounded-lg flex flex-col h-full", style: { boxShadow: "var(--dc-shadow-sm)" }, children: [
    /* @__PURE__ */ s("div", { className: "flex items-center justify-between border-b border-dc-border shrink-0 bg-dc-surface-secondary rounded-t-lg px-3 py-2 md:px-6 md:py-3", children: [
      /* @__PURE__ */ s("div", { className: "flex items-center gap-2 flex-1 min-w-0", children: [
        /* @__PURE__ */ e("h3", { className: "font-semibold text-sm truncate text-dc-text", children: t.title }),
        l && /* @__PURE__ */ e(
          Pn,
          {
            chartConfig: l.chartConfig,
            displayConfig: l.displayConfig,
            queryObject: l.queryObject,
            data: l.data,
            chartType: l.chartType
          }
        )
      ] }),
      /* @__PURE__ */ e("div", { className: "flex items-center gap-2 ml-4", children: r && /* @__PURE__ */ s(Ie, { children: [
        /* @__PURE__ */ e(
          "button",
          {
            onClick: () => c?.(t.id),
            className: "p-1.5 hover:bg-dc-surface-hover rounded-sm text-dc-text-secondary",
            title: "Refresh",
            children: /* @__PURE__ */ e("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" }) })
          }
        ),
        /* @__PURE__ */ e(
          "button",
          {
            onClick: () => n?.(t),
            className: "p-1.5 hover:bg-dc-surface-hover rounded-sm text-dc-text-secondary",
            title: "Edit",
            children: /* @__PURE__ */ e("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" }) })
          }
        ),
        /* @__PURE__ */ e(
          "button",
          {
            onClick: () => a?.(t.id),
            className: "p-1.5 rounded-sm text-dc-danger",
            style: { backgroundColor: "transparent" },
            onMouseEnter: (o) => o.currentTarget.style.backgroundColor = "var(--dc-danger-bg)",
            onMouseLeave: (o) => o.currentTarget.style.backgroundColor = "transparent",
            title: "Delete",
            children: /* @__PURE__ */ e("svg", { className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: /* @__PURE__ */ e("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" }) })
          }
        )
      ] }) })
    ] }),
    /* @__PURE__ */ e("div", { className: "px-2 py-3 md:px-4 md:pt-6 md:pb-4 flex-1 min-h-0", children: /* @__PURE__ */ e(
      gr,
      {
        query: t.query,
        chartType: t.chartType,
        chartConfig: t.chartConfig,
        displayConfig: t.displayConfig,
        title: t.title,
        height: "100%",
        onDebugDataReady: h
      }
    ) })
  ] });
}
function Pl({
  isOpen: t,
  onClose: r,
  onSave: n,
  title: a,
  submitText: c,
  initialName: l = "",
  initialDescription: d = ""
}) {
  const [h, o] = H(""), [u, m] = H(""), [x, f] = H(!1);
  Ce(() => {
    t && (o(l), m(d));
  }, [t, l, d]);
  const S = async (k) => {
    if (k.preventDefault(), !!h.trim()) {
      f(!0);
      try {
        await n({
          name: h.trim(),
          description: u.trim() || void 0
        }), T();
      } catch {
      } finally {
        f(!1);
      }
    }
  }, T = () => {
    o(""), m(""), f(!1), r();
  }, D = /* @__PURE__ */ s(Ie, { children: [
    /* @__PURE__ */ e(
      "button",
      {
        type: "button",
        onClick: T,
        disabled: x,
        className: "px-4 py-2 text-sm font-medium text-dc-text-secondary bg-dc-surface border border-dc-border rounded-md hover:bg-dc-surface-hover disabled:opacity-50",
        children: "Cancel"
      }
    ),
    /* @__PURE__ */ e(
      "button",
      {
        type: "submit",
        form: "dashboard-form",
        disabled: x || !h.trim(),
        className: "px-4 py-2 text-sm font-medium text-white bg-dc-primary border border-transparent rounded-md hover:bg-dc-primary-hover disabled:opacity-50 disabled:cursor-not-allowed",
        children: x ? "Saving..." : c
      }
    )
  ] });
  return /* @__PURE__ */ e(
    Pr,
    {
      isOpen: t,
      onClose: T,
      title: a,
      size: "fullscreen-mobile",
      footer: D,
      children: /* @__PURE__ */ s("form", { id: "dashboard-form", onSubmit: S, className: "space-y-4 w-full", children: [
        /* @__PURE__ */ s("div", { children: [
          /* @__PURE__ */ e("label", { htmlFor: "dashboard-name", className: "block text-sm font-medium text-dc-text-secondary mb-1", children: "Dashboard Name" }),
          /* @__PURE__ */ e(
            "input",
            {
              type: "text",
              id: "dashboard-name",
              value: h,
              onChange: (k) => o(k.target.value),
              className: "w-full px-3 py-2 border border-dc-border rounded-md bg-dc-surface text-dc-text focus:outline-none focus:ring-2 focus:ring-dc-primary focus:border-dc-primary",
              placeholder: "Enter dashboard name...",
              required: !0,
              autoFocus: !0
            }
          )
        ] }),
        /* @__PURE__ */ s("div", { children: [
          /* @__PURE__ */ e("label", { htmlFor: "dashboard-description", className: "block text-sm font-medium text-dc-text-secondary mb-1", children: "Description (optional)" }),
          /* @__PURE__ */ e(
            "textarea",
            {
              id: "dashboard-description",
              rows: 3,
              value: u,
              onChange: (k) => m(k.target.value),
              className: "w-full px-3 py-2 border border-dc-border rounded-md bg-dc-surface text-dc-text focus:outline-none focus:ring-2 focus:ring-dc-primary focus:border-dc-primary",
              placeholder: "Enter description..."
            }
          )
        ] })
      ] })
    }
  );
}
export {
  gr as A,
  _l as D,
  qr as H,
  Pr as M,
  jl as P,
  as as Q,
  Ll as a,
  wn as b,
  kn as c,
  Pl as d,
  Qr as e,
  ra as h,
  ea as u
};
//# sourceMappingURL=components-K3xrnHN-.js.map