import { jsxs as f, jsx as a, Fragment as H } from "react/jsx-runtime";
import { aj as k, m as G, ay as U, at as $, cG as J, d1 as T, a2 as _, z as L, bz as K, v as X, d2 as Y, ba as M, d3 as Z, d4 as Q, y, b1 as ee, bw as te, d5 as F, d as j, e as ae, d6 as oe, d7 as B, bZ as ie, bi as ne, bj as re, b$ as O, d8 as b, d9 as se, ao as R, bn as le, bm as ce, cM as de } from "./index-BJZQSU1O.mjs";
import { useState as x, useEffect as C, useCallback as V, memo as ue, useRef as S, useMemo as N } from "react";
import { T as me } from "./Textarea-Gr-nKkZy.mjs";
var pe = k("chart-bubble", "IconChartBubble", [
  ["path", { d: "M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0", key: "svg-0" }],
  ["path", { d: "M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0", key: "svg-1" }],
  [
    "path",
    {
      d: "M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0",
      key: "svg-2"
    }
  ]
]), fe = k("flame", "IconFlame", [
  [
    "path",
    {
      d: "M12 12c2 -2.96 0 -7 -1 -8c0 3.038 -1.773 4.741 -3 6c-1.226 1.26 -2 3.24 -2 5a6 6 0 1 0 12 0c0 -1.532 -1.056 -3.94 -2 -5c-1.786 3 -2.791 3 -4 2z",
      key: "svg-0"
    }
  ]
]), ge = k("stairs", "IconStairs", [
  ["path", { d: "M22 5h-5v5h-5v5h-5v5h-5", key: "svg-0" }]
]), he = k("world", "IconWorld", [
  ["path", { d: "M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0", key: "svg-0" }],
  ["path", { d: "M3.6 9h16.8", key: "svg-1" }],
  ["path", { d: "M3.6 15h16.8", key: "svg-2" }],
  ["path", { d: "M11.5 3a17 17 0 0 0 0 18", key: "svg-3" }],
  ["path", { d: "M12.5 3a17 17 0 0 1 0 18", key: "svg-4" }]
]);
const ye = async (e, i, t, r, n) => $({
  url: `/ai/${e}/custom-viz`,
  method: "POST",
  body: JSON.stringify({
    prompt: i,
    itemsMap: t,
    sampleResults: r,
    currentVizConfig: n
  })
}), ve = (e) => {
  const { showToastApiError: i } = G();
  return U(
    (t) => ye(
      e,
      t.prompt,
      t.itemsMap,
      t.sampleResults,
      t.currentVizConfig
    ),
    {
      mutationKey: ["get_custom_vis_ai", e],
      onError: ({ error: t }) => {
        i({
          title: "Failed to generate custom visualization",
          apiError: t
        });
      }
    }
  );
}, be = ({
  itemsMap: e,
  sampleResults: i,
  editorConfig: t,
  setEditorConfig: r
}) => {
  const { projectUuid: n } = J(), [o, s] = x(""), { mutate: l, data: d, isLoading: u } = ve(n);
  C(() => {
    d && r(d);
  }, [d, r]);
  const h = V(() => {
    u || o && n && l({
      prompt: o,
      itemsMap: e,
      sampleResults: i,
      currentVizConfig: t
    });
  }, [
    l,
    o,
    n,
    u,
    e,
    i,
    t
  ]);
  return /* @__PURE__ */ f(
    T,
    {
      width: "400px",
      position: "bottom",
      withArrow: !0,
      shadow: "md",
      withinPortal: !0,
      children: [
        /* @__PURE__ */ a(T.Target, { children: /* @__PURE__ */ a(
          _,
          {
            compact: !0,
            variant: "default",
            fz: "xs",
            leftIcon: /* @__PURE__ */ a(L, { icon: K }),
            children: "AI"
          }
        ) }),
        /* @__PURE__ */ f(T.Dropdown, { children: [
          /* @__PURE__ */ a(
            me,
            {
              placeholder: "Create a heatmap with detailed tooltips and clear values for fast insights",
              autosize: !0,
              autoFocus: !0,
              minRows: 1,
              maxRows: 20,
              onChange: (p) => {
                s(p.currentTarget.value);
              },
              onKeyDown: (p) => {
                p.key === "Enter" && !p.shiftKey && (p.preventDefault(), h());
              }
            }
          ),
          /* @__PURE__ */ a(
            _,
            {
              mt: "sm",
              size: "xs",
              type: "submit",
              disabled: u,
              onClick: h,
              children: u ? "Generating..." : "Generate"
            }
          )
        ] })
      ]
    }
  );
};
var g = /* @__PURE__ */ ((e) => (e.BAR_CHART = "Bar chart", e.HEATMAP = "Heatmap", e.BUBBLE_PLOTS = "Bubble plots", e.FUNNEL_CHART = "Funnel chart", e.WATERFALL_CHART = "Waterfall chart", e.MAP = "World map", e))(g || {});
const c = "#6e7079", xe = {
  $schema: "https://vega.github.io/schema/vega-lite/v5.json",
  mark: "bar",
  encoding: {
    x: {
      field: "field_x",
      type: "field_type_x",
      axis: {
        labelColor: c,
        tickColor: c
      }
    },
    y: {
      field: "field_y",
      type: "quantitative",
      axis: {
        labelColor: c,
        tickColor: c
      }
    }
  }
}, Ce = {
  $schema: "https://vega.github.io/schema/vega-lite/v5.json",
  mark: "rect",
  encoding: {
    x: {
      field: "field_x",
      type: "field_type_x",
      axis: {
        labelColor: c,
        tickColor: c
      }
    },
    y: {
      field: "field_y",
      type: "quantitative",
      axis: {
        labelColor: c,
        tickColor: c
      }
    },
    color: {
      field: "field_extra",
      type: "quantitative",
      aggregate: "sum"
    }
  }
}, _e = {
  $schema: "https://vega.github.io/schema/vega-lite/v5.json",
  mark: "point",
  encoding: {
    x: {
      field: "field_x",
      type: "field_type_x",
      axis: {
        labelColor: c,
        tickColor: c
      }
    },
    y: {
      field: "field_y",
      type: "quantitative",
      axis: {
        labelColor: c,
        tickColor: c
      }
    },
    size: {
      field: "field_extra",
      type: "quantitative"
    }
  }
}, ke = {
  $schema: "https://vega.github.io/schema/vega-lite/v5.json",
  mark: "funnel",
  config: {
    view: {
      strokeWidth: 0
    }
  },
  transform: [
    {
      calculate: "datum.field_y + ' ' + datum.field_x",
      as: "label"
    },
    {
      window: [{ op: "lag", field: "field_y", as: "previous_value" }],
      frame: [1, 0]
    },
    {
      calculate: "datum.previous_value ? (datum.field_y / datum.previous_value) * 100 : null",
      as: "percent_of_previous"
    },
    {
      calculate: "isValid(datum.percent_of_previous) ? '↓ ' + format(datum.percent_of_previous, '.1f') + '%' : 'N/A'",
      as: "change_label"
    }
  ],
  layer: [
    {
      mark: { type: "bar" },
      encoding: {
        x: {
          field: "field_y",
          type: "quantitative",
          stack: "center",
          axis: null
        },
        y: {
          field: "field_x",
          type: "nominal",
          axis: null,
          sort: null,
          scale: {
            padding: 0.5
          }
        },
        color: {
          field: "field_y",
          scale: {
            scheme: "lightgreyteal"
          }
        }
      }
    },
    {
      mark: { type: "text", color: "black" },
      encoding: {
        y: {
          field: "orders_status",
          type: "nominal",
          axis: null,
          sort: null
        },
        text: { field: "label" }
      }
    },
    {
      mark: { type: "text", color: c },
      encoding: {
        y: {
          field: "orders_status",
          type: "nominal",
          axis: null,
          sort: null
        },
        yOffset: { value: -9 },
        text: {
          condition: {
            test: "datum.change_label !== 'N/A'",
            field: "change_label"
          },
          value: ""
        }
      }
    }
  ]
}, we = {
  $schema: "https://vega.github.io/schema/vega-lite/v2.json",
  mark: "waterfall",
  encoding: {
    x: {
      field: "field_x",
      type: "field_type_x"
    },
    y: {
      field: "field_y",
      type: "quantitative",
      axis: { title: "field_y" }
    },
    y2: {
      field: "field_extra",
      type: "quantitative"
    }
  },
  layer: [
    {
      mark: "bar",
      encoding: {
        color: {
          type: "ordinal",
          _comment: "chose a field to color by",
          _field: "type",
          //placeholder field for type
          scale: {
            domain: ["total", "increase", "decrease"],
            range: ["blue", "green", "red"]
          }
        }
      }
    },
    {
      mark: "text",
      encoding: {
        y: {
          field: "field_y",
          type: "quantitative"
        },
        text: {
          field: "field_y",
          type: "nominal"
        },
        color: {
          value: "black"
        }
      }
    }
  ]
}, Ae = {
  projection: {
    type: "mercator",
    _comment: "change scale and center to zoom into a region",
    scale: 100,
    center: [10, 50]
  },
  mark: "map",
  layer: [
    {
      data: {
        url: "/vega-world-map.json",
        format: {
          type: "topojson",
          feature: "countries"
        }
      },
      mark: {
        fill: "lightgray",
        type: "geoshape",
        stroke: "white"
      }
    },
    {
      mark: "circle",
      encoding: {
        size: {
          type: "quantitative",
          field: "field_y",
          legend: null
          // Hide the legend for size
        },
        tooltip: [
          {
            type: "field_type_x",
            field: "field_x"
          },
          {
            type: "nominal",
            field: "field_y"
          },
          {
            type: "quantitative",
            field: "latitude"
          },
          {
            type: "quantitative",
            field: "longitude"
          }
        ],
        latitude: {
          type: "quantitative",
          field: "latitude"
        },
        longitude: {
          type: "quantitative",
          field: "longitude"
        }
      }
    }
  ]
}, Ie = {
  "Bar chart": xe,
  Heatmap: Ce,
  "Bubble plots": _e,
  "Funnel chart": ke,
  "Waterfall chart": we,
  "World map": Ae
}, Te = (e) => Ie[e], Me = (e, i, t, r) => {
  const n = Te(e);
  let o = JSON.stringify(n, null, 2);
  if (i) {
    const s = X(i) && Y(i) ? "temporal" : "ordinal";
    o = o.replaceAll("field_type_x", s), o = o.replaceAll(
      "field_x",
      M(i)
    );
  }
  return t && (o = o.replaceAll(
    "field_y",
    M(t)
  )), r && (o = o.replaceAll(
    "field_extra",
    M(r)
  )), o;
}, Se = (e) => {
  switch (e) {
    case g.BAR_CHART:
      return F;
    case g.HEATMAP:
      return fe;
    case g.BUBBLE_PLOTS:
      return pe;
    case g.FUNNEL_CHART:
      return te;
    case g.WATERFALL_CHART:
      return ge;
    case g.MAP:
      return he;
  }
  return F;
}, Le = ({
  itemsMap: e,
  isCustomConfig: i,
  setEditorConfig: t
}) => {
  const r = V(
    (n) => {
      if (!i) return null;
      const o = Z(e)[0], [s, l] = Q(e), d = Me(
        n,
        o,
        s,
        l
      );
      t(d);
    },
    [i, e, t]
  );
  return /* @__PURE__ */ f(
    y,
    {
      shadow: "md",
      position: "bottom",
      withArrow: !0,
      closeOnClickOutside: !0,
      closeOnEscape: !0,
      offset: 2,
      width: 183,
      closeOnItemClick: !0,
      children: [
        /* @__PURE__ */ f(y.Dropdown, { children: [
          Object.values(g).map((n) => /* @__PURE__ */ a(
            y.Item,
            {
              onClick: () => r(n),
              leftSection: /* @__PURE__ */ a(L, { icon: Se(n) }),
              children: n
            },
            n
          )),
          /* @__PURE__ */ a(y.Divider, {}),
          /* @__PURE__ */ a(y.Label, { children: 'Selecting a new template will reset the config. Use "ctrl+z" to undo.' })
        ] }),
        /* @__PURE__ */ a(y.Target, { children: /* @__PURE__ */ a(
          _,
          {
            size: "sm",
            variant: "default",
            compact: !0,
            fz: "xs",
            leftIcon: /* @__PURE__ */ a(L, { icon: ee }),
            children: "Insert template"
          }
        ) })
      ]
    }
  );
}, ze = {
  cursorBlinking: "smooth",
  folding: !0,
  lineNumbersMinChars: 1,
  minimap: { enabled: !1 },
  scrollBeyondLastLine: !1,
  wordWrap: "off",
  quickSuggestions: !0,
  contextmenu: !1,
  fixedOverflowWidgets: !0
}, Ee = async () => {
  const e = await import("./vega-lite-schema-svchW7Ro.mjs");
  return [
    {
      uri: "https://lightdash.com/schemas/vega-lite-schema-custom.json",
      fileMatch: ["*"],
      schema: e.default
    }
  ];
}, Fe = (e, i) => {
  e.languages.json.jsonDefaults.setDiagnosticsOptions({
    comments: "warning",
    trailingCommas: "warning",
    enableSchemaRequest: !0,
    schemas: i,
    validate: !0
  }), e.languages.json.jsonDefaults.setModeConfiguration({
    documentFormattingEdits: !1,
    documentRangeFormattingEdits: !1,
    completionItems: !0,
    hovers: !0,
    documentSymbols: !0,
    tokens: !0,
    colors: !0,
    foldingRanges: !0,
    diagnostics: !0
  }), e.editor.defineTheme("lightdash-light", {
    base: "vs",
    inherit: !0,
    rules: [],
    colors: {}
  }), e.editor.defineTheme("lightdash-dark", {
    base: "vs-dark",
    inherit: !0,
    rules: [],
    colors: {}
  });
}, P = (e, i, t) => (console.debug("Loading completion provider with fields", t), e.languages.registerCompletionItemProvider(i, {
  provideCompletionItems: (r, n) => {
    const o = r.getWordUntilPosition(n), s = {
      startLineNumber: n.lineNumber,
      endLineNumber: n.lineNumber,
      startColumn: o.startColumn,
      endColumn: o.endColumn
    };
    return { suggestions: t.map(
      (d) => ({
        label: d,
        kind: e.languages.CompletionItemKind.Class,
        insertText: d,
        range: s
      })
    ) };
  },
  triggerCharacters: ["$"]
})), Ne = ue(() => {
  const { visualizationConfig: e } = j(), i = ae(), t = oe(e), [r, n] = x(!0), o = S(null), s = N(
    () => t ? e.chartConfig : void 0,
    [t, e.chartConfig]
  ), l = S(null), d = S(null), { fields: u } = N(() => ({
    fields: s?.fields
  }), [s]);
  B(() => {
    if (!s || !r) return;
    async function m() {
      o.current = await Ee(), n(!1);
    }
    m();
  }, [r, s]), C(() => () => {
    l.current && (console.debug(
      "Clearning Monaco completion provider on unmount"
    ), l.current.dispose());
  }, []), C(() => {
    d.current && (l.current && (console.debug(
      "Refreshing Monaco completion provider with new fields"
    ), l.current.dispose()), u && (l.current = P(
      d.current,
      "json",
      u
    )));
  }, [u]);
  const [h, p] = x(
    t && e.chartConfig.visSpec || ""
  ), [w] = ie(h, 1e3);
  C(() => {
    r || !s || w && s.setVisSpec(w);
  }, [r, w, s]);
  const [A, q] = x(), D = ne(re.AiCustomViz);
  B(() => {
    const m = "monaco-overflow-container";
    let v = document.getElementById(m);
    if (!v) {
      const I = document.createElement("div");
      I.className = "monaco-editor", v = document.createElement("div"), v.id = m, I.appendChild(v), document.getElementById("root")?.appendChild(I);
    }
    q({
      ...ze,
      overflowWidgetsDomNode: v
    });
  }, [A]);
  const { itemsMap: z } = j();
  if (!t) return null;
  if (!A || r)
    return /* @__PURE__ */ a(O, { color: "gray", size: "xs" });
  const { series: W } = e.chartConfig, E = (h || "")?.length === 0;
  return /* @__PURE__ */ f(H, { children: [
    /* @__PURE__ */ a(b, { children: /* @__PURE__ */ a(b.Section, { children: /* @__PURE__ */ f(b.Group, { children: [
      /* @__PURE__ */ a(b.Heading, { children: /* @__PURE__ */ f(se, { justify: "space-between", gap: "xs", children: [
        /* @__PURE__ */ a(R, { children: "Vega-Lite JSON" }),
        /* @__PURE__ */ a(
          le,
          {
            pos: "relative",
            top: "2px",
            href: "https://docs.lightdash.com/references/custom-charts#custom-charts"
          }
        )
      ] }) }),
      /* @__PURE__ */ f(_.Group, { children: [
        /* @__PURE__ */ a(
          Le,
          {
            itemsMap: z,
            isCustomConfig: t,
            isEditorEmpty: E,
            setEditorConfig: p
          }
        ),
        D && /* @__PURE__ */ a(
          be,
          {
            itemsMap: z,
            sampleResults: W.slice(0, 3),
            setEditorConfig: p,
            editorConfig: h
          }
        )
      ] })
    ] }) }) }),
    /* @__PURE__ */ f(
      ce,
      {
        h: "calc(100vh - 300px)",
        align: "top",
        mt: "4px",
        sx: {
          borderTop: "0.125rem solid #dee2e6"
        },
        children: [
          E ? /* @__PURE__ */ a(
            R,
            {
              pos: "absolute",
              w: "330px",
              color: "ldGray.5",
              sx: {
                pointerEvents: "none",
                zIndex: 100,
                fontFamily: "monospace",
                marginLeft: "35px",
                // Stye to match Monaco text
                fontSize: "12px",
                lineHeight: "19px",
                letterSpacing: "0px"
              },
              children: "Start by entering your Vega-Lite JSON code or choose from our pre-built templates to create your chart."
            }
          ) : null,
          /* @__PURE__ */ a(
            de,
            {
              loading: /* @__PURE__ */ a(O, { color: "gray", size: "xs" }),
              beforeMount: (m) => {
                Fe(m, o.current), d.current = m, l.current && (console.debug(
                  "Clearing Monaco completion provider on beforeMount",
                  l.current
                ), l.current.dispose()), u && (l.current = P(
                  m,
                  "json",
                  u
                ));
              },
              defaultLanguage: "json",
              options: A,
              value: h,
              onChange: (m) => {
                p(m ?? "");
              },
              theme: i.colorScheme === "dark" ? "lightdash-dark" : "lightdash-light"
            }
          )
        ]
      }
    )
  ] });
});
export {
  Ne as ConfigTabs
};
//# sourceMappingURL=CustomVisConfig-DL0j1I1E.mjs.map
