import { jsxs as x, jsx as i } from "react/jsx-runtime";
import { ay as G, at as W, cG as V, dc as H, $ as A, bm as K, z as E, bz as U, ao as L, bo as F, dd as j, d as q, cF as Y, de as Z, df as J, bZ as X, d7 as Q, cK as z, S as ee, E as te, d8 as oe, aK as ne, dg as re, dh as ae, b2 as se, aY as ie, T as le, di as ce, dj as ue } from "./index-BJZQSU1O.mjs";
import { useRef as _, useCallback as f, useState as I, useEffect as N } from "react";
import { T as de } from "./Textarea-Gr-nKkZy.mjs";
const he = 1e4, me = async (n, t, d) => W({
  url: `/ai/${n}/tooltip/generate`,
  method: "POST",
  body: JSON.stringify(t),
  signal: d
}), pe = ({
  projectUuid: n,
  fields: t,
  onSuccess: d
}) => {
  const m = _(null), e = G({
    onSuccess: d,
    mutationFn: ({ prompt: c, currentHtml: l }) => {
      if (!n)
        throw new Error("Project UUID is required");
      m.current?.abort();
      const u = new AbortController();
      m.current = u;
      const h = setTimeout(() => {
        u.abort();
      }, he), b = t.map(
        (s) => ({
          name: s
        })
      );
      return me(
        n,
        {
          prompt: c,
          fieldsContext: b,
          currentHtml: l
        },
        u.signal
      ).finally(() => {
        clearTimeout(h);
      });
    }
  }), a = f(
    (c, l) => {
      !n || !c.trim() || e.mutate({ prompt: c, currentHtml: l });
    },
    [n, e]
  ), p = f(() => {
    e.reset();
  }, [e]);
  return {
    generate: a,
    reset: p,
    generatedResult: e.data ?? null,
    isLoading: e.isLoading,
    error: e.error
  };
}, ge = "_container_1x48z_1", fe = "_inputContainer_1x48z_17", Ce = "_textareaRoot_1x48z_21", be = "_textareaInput_1x48z_25", xe = "_generateButton_1x48z_52", T = {
  container: ge,
  inputContainer: fe,
  textareaRoot: Ce,
  textareaInput: be,
  generateButton: xe
}, Te = ({ fields: n, currentHtml: t, onApply: d }) => {
  const { projectUuid: m } = V(), [e, a] = I(""), p = f(
    (s) => {
      d(s.html), a("");
    },
    [d]
  ), { generate: c, isLoading: l, error: u } = pe({
    projectUuid: m,
    fields: n,
    onSuccess: p
  }), h = f(() => {
    const s = e.trim() || "generate a helpful tooltip";
    c(s, t);
  }, [c, e, t]), b = f(
    (s) => {
      s.key === "Enter" && !s.shiftKey && (s.preventDefault(), h());
    },
    [h]
  );
  return H([["mod+Enter", h]], [], !0), /* @__PURE__ */ x(A, { className: T.container, children: [
    /* @__PURE__ */ x(K, { spacing: "xs", mb: "xs", children: [
      /* @__PURE__ */ i(E, { icon: U, color: "indigo.4" }),
      /* @__PURE__ */ i(L, { size: "xs", c: "ldDark.9", fw: 500, children: t ? "Improve your tooltip code with AI" : "Generate tooltip with AI" })
    ] }),
    /* @__PURE__ */ x(A, { className: T.inputContainer, children: [
      /* @__PURE__ */ i(
        de,
        {
          value: e,
          onChange: (s) => a(s.target.value),
          onKeyDown: b,
          placeholder: "Describe what you want to show in the tooltip...",
          disabled: l,
          classNames: {
            root: T.textareaRoot,
            input: T.textareaInput
          },
          minRows: 2,
          maxRows: 4,
          autosize: !0
        }
      ),
      /* @__PURE__ */ i(
        F,
        {
          size: "sm",
          radius: "xl",
          onClick: h,
          disabled: l || !e.trim() && !!t,
          loading: l,
          className: T.generateButton,
          children: /* @__PURE__ */ i(
            E,
            {
              icon: j,
              color: "ldGray.0",
              size: 16,
              stroke: 2
            }
          )
        }
      )
    ] }),
    u && /* @__PURE__ */ i(L, { size: "xs", c: "red", mt: "xs", children: "Failed to generate. Please try again." })
  ] });
}, we = "_editorWrapper_xvb94_1", _e = "_placeholderText_xvb94_30", M = {
  editorWrapper: we,
  placeholderText: _e
}, Ie = {
  cursorBlinking: "smooth",
  folding: !1,
  minimap: { enabled: !1 },
  scrollBeyondLastLine: !1,
  wordWrap: "off",
  quickSuggestions: !0,
  contextmenu: !1,
  automaticLayout: !0,
  tabSize: 2,
  lineNumbers: "off",
  glyphMargin: !1,
  lineDecorationsWidth: 0,
  lineNumbersMinChars: 0,
  fixedOverflowWidgets: !0
};
let v = null;
const ye = (n, t, d) => {
  v && (console.debug("Clearing Monaco completion provider"), v.dispose()), v = n.languages.registerCompletionItemProvider(t, {
    provideCompletionItems: (m, e) => {
      const a = m.getWordUntilPosition(e), p = {
        startLineNumber: e.lineNumber,
        endLineNumber: e.lineNumber,
        startColumn: a.startColumn,
        endColumn: a.endColumn
      };
      return { suggestions: d.map(
        (l) => {
          const h = m.getValueInRange({
            startLineNumber: e.lineNumber,
            endLineNumber: e.lineNumber,
            startColumn: e.column - 1,
            endColumn: e.column
          }) === "$" ? `{${l}} ` : `\${${l}}`;
          return {
            label: `${l}`,
            kind: n.languages.CompletionItemKind.Class,
            insertText: h,
            range: p
          };
        }
      ) };
    },
    triggerCharacters: ["$"]
  });
}, Ne = 19, ve = 16, Ee = 10, w = (n) => Math.min(n || 1, Ee) * Ne + ve, Me = ({ fields: n }) => {
  const { visualizationConfig: t } = q(), { colorScheme: d } = Y(), m = Z(), e = J(t), [a, p] = I(
    e && t.chartConfig.tooltip || ""
  ), [c] = X(a, 1e3), [l, u] = I(
    w(1)
  ), h = _(null), b = _(null), s = _(
    e ? !!t.chartConfig.tooltip : !1
  ), k = _(
    e && t.chartConfig.tooltip || ""
  ), [g, O] = I(
    e ? !!t.chartConfig.tooltip : !1
  );
  N(() => {
    k.current = a;
  }, [a]), N(() => {
    if (!e) return;
    const { setTooltip: o } = t.chartConfig;
    s.current !== g ? (o(g ? k.current : ""), s.current = g) : g && o(c);
  }, [
    e,
    g,
    c,
    t.chartConfig
  ]);
  const S = (o) => {
    p(o ?? "");
    const r = (o ?? "").split(`
`).length;
    u(w(r));
  }, P = f((o) => {
    p(o);
    const r = o.split(`
`).length;
    u(w(r));
  }, []), [y, D] = I();
  Q(() => {
    const o = "monaco-overflow-container";
    let r = document.getElementById(o);
    if (!r) {
      const C = document.createElement("div");
      C.className = "monaco-editor", r = document.createElement("div"), r.id = o, C.appendChild(r), document.getElementById("root")?.appendChild(C);
    }
    D({
      ...Ie,
      overflowWidgetsDomNode: r
    });
  }, [y]);
  const R = f(
    (o) => {
      ye(o, "html", n);
      const r = z("light"), C = z("dark");
      o.editor.defineTheme("lightdash-light", {
        base: "vs",
        inherit: !0,
        rules: [],
        // No syntax rules needed for HTML editor
        colors: {
          ...r.colors
        }
      }), o.editor.defineTheme("lightdash-dark", {
        base: "vs-dark",
        inherit: !0,
        rules: [],
        // No syntax rules needed for HTML editor
        colors: {
          ...C.colors
        }
      });
    },
    [n]
  ), $ = f((o) => {
    h.current = o;
    const r = o.getModel();
    if (r) {
      const C = r.getLineCount();
      u(w(C)), b.current = r.onDidChangeContent(() => {
        const B = r.getLineCount();
        u(w(B));
      });
    }
  }, []);
  return N(() => () => {
    b.current?.dispose();
  }, []), y ? /* @__PURE__ */ x(ee, { gap: "xs", children: [
    /* @__PURE__ */ x(te, { gap: "xs", align: "center", children: [
      /* @__PURE__ */ i(oe.Label, { children: "Custom" }),
      /* @__PURE__ */ i(
        ne,
        {
          withinPortal: !0,
          maw: 350,
          variant: "xs",
          multiline: !0,
          label: "Use this input to enhance chart tooltips with additional content. You can incorporate HTML code and include dynamic values using the format ${variable_name}.\n                                Click here to read more about this on our docs.",
          children: /* @__PURE__ */ i(
            E,
            {
              onClick: () => {
                window.open(
                  "https://docs.lightdash.com/references/custom-tooltip",
                  "_blank"
                );
              },
              icon: re,
              size: "md",
              display: "inline",
              color: "ldGray.5",
              style: { cursor: "pointer" }
            }
          )
        }
      ),
      /* @__PURE__ */ i(ae, { checked: g, onChange: () => O(!g) })
    ] }),
    /* @__PURE__ */ i(se, { in: g, children: /* @__PURE__ */ x(
      ie,
      {
        className: M.editorWrapper,
        radius: "md",
        withBorder: !0,
        pos: "relative",
        children: [
          a?.length === 0 ? /* @__PURE__ */ i(
            le,
            {
              ml: "sm",
              pos: "absolute",
              w: "400px",
              c: "ldGray.5",
              fz: "xs",
              className: M.placeholderText,
              style: {
                zIndex: ce("overlay")
              },
              children: "- Total orders: ${orders_total_amount}"
            }
          ) : null,
          /* @__PURE__ */ i(
            ue,
            {
              beforeMount: R,
              onMount: $,
              value: a,
              options: y,
              onChange: S,
              language: "html",
              height: `${l}px`,
              width: "100%",
              theme: d === "dark" ? "lightdash-dark" : "lightdash-light",
              wrapperProps: {
                id: "tooltip-editor-wrapper"
              }
            }
          ),
          m && /* @__PURE__ */ i(
            Te,
            {
              fields: n,
              currentHtml: a || void 0,
              onApply: P
            }
          )
        ]
      }
    ) })
  ] }) : null;
};
export {
  Me as TooltipConfig
};
//# sourceMappingURL=TooltipConfig-B56zBuiR.mjs.map
