import { jsxs as x, jsx as i } from "react/jsx-runtime";
import { d as G } from "./index-DgLlxXt5.mjs";
import { useRef as _, useCallback as f, useState as I, useEffect as N } from "react";
import { ay as W, at as V, cG as H, d7 as U, $ as A, bm as K, z as E, bz as F, ao as L, bo as q, d8 as Y, d as Z, cF as j, d9 as J, da as X, bZ as Q, d2 as ee, S as te, E as oe, d3 as ne, aK as re, db as ae, dc as se, b2 as ie, aY as le, T as ce, dd as ue } from "./index-CUr2awEp.mjs";
import { T as de } from "./Textarea-Csue8TSg.mjs";
import { a as z } from "./monaco-BNMCt5QW.mjs";
/* empty css                 */
const me = 1e4, pe = async (n, t, d) => V({
  url: `/ai/${n}/tooltip/generate`,
  method: "POST",
  body: JSON.stringify(t),
  signal: d
}), he = ({
  projectUuid: n,
  fields: t,
  onSuccess: d
}) => {
  const p = _(null), e = W({
    onSuccess: d,
    mutationFn: ({ prompt: c, currentHtml: l }) => {
      if (!n)
        throw new Error("Project UUID is required");
      p.current?.abort();
      const u = new AbortController();
      p.current = u;
      const m = setTimeout(() => {
        u.abort();
      }, me), b = t.map(
        (s) => ({
          name: s
        })
      );
      return pe(
        n,
        {
          prompt: c,
          fieldsContext: b,
          currentHtml: l
        },
        u.signal
      ).finally(() => {
        clearTimeout(m);
      });
    }
  }), a = f(
    (c, l) => {
      !n || !c.trim() || e.mutate({ prompt: c, currentHtml: l });
    },
    [n, e]
  ), h = f(() => {
    e.reset();
  }, [e]);
  return {
    generate: a,
    reset: h,
    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: p } = H(), [e, a] = I(""), h = f(
    (s) => {
      d(s.html), a("");
    },
    [d]
  ), { generate: c, isLoading: l, error: u } = he({
    projectUuid: p,
    fields: n,
    onSuccess: h
  }), m = 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(), m());
    },
    [m]
  );
  return U([["mod+Enter", m]], [], !0), /* @__PURE__ */ x(A, { className: T.container, children: [
    /* @__PURE__ */ x(K, { spacing: "xs", mb: "xs", children: [
      /* @__PURE__ */ i(E, { icon: F, 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(
        q,
        {
          size: "sm",
          radius: "xl",
          onClick: m,
          disabled: l || !e.trim() && !!t,
          loading: l,
          className: T.generateButton,
          children: /* @__PURE__ */ i(
            E,
            {
              icon: Y,
              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: (p, e) => {
      const a = p.getWordUntilPosition(e), h = {
        startLineNumber: e.lineNumber,
        endLineNumber: e.lineNumber,
        startColumn: a.startColumn,
        endColumn: a.endColumn
      };
      return { suggestions: d.map(
        (l) => {
          const m = p.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: m,
            range: h
          };
        }
      ) };
    },
    triggerCharacters: ["$"]
  });
}, Ne = 19, ve = 16, Ee = 10, w = (n) => Math.min(n || 1, Ee) * Ne + ve, Pe = ({ fields: n }) => {
  const { visualizationConfig: t } = Z(), { colorScheme: d } = j(), p = J(), e = X(t), [a, h] = I(
    e && t.chartConfig.tooltip || ""
  ), [c] = Q(a, 1e3), [l, u] = I(
    w(1)
  ), m = _(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) => {
    h(o ?? "");
    const r = (o ?? "").split(`
`).length;
    u(w(r));
  }, P = f((o) => {
    h(o);
    const r = o.split(`
`).length;
    u(w(r));
  }, []), [y, D] = I();
  ee(() => {
    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) => {
    m.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(te, { gap: "xs", children: [
    /* @__PURE__ */ x(oe, { gap: "xs", align: "center", children: [
      /* @__PURE__ */ i(ne.Label, { children: "Custom" }),
      /* @__PURE__ */ i(
        re,
        {
          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: ae,
              size: "md",
              display: "inline",
              color: "ldGray.5",
              style: { cursor: "pointer" }
            }
          )
        }
      ),
      /* @__PURE__ */ i(se, { checked: g, onChange: () => O(!g) })
    ] }),
    /* @__PURE__ */ i(ie, { in: g, children: /* @__PURE__ */ x(
      le,
      {
        className: M.editorWrapper,
        radius: "md",
        withBorder: !0,
        pos: "relative",
        children: [
          a?.length === 0 ? /* @__PURE__ */ i(
            ce,
            {
              ml: "sm",
              pos: "absolute",
              w: "400px",
              c: "ldGray.5",
              fz: "xs",
              className: M.placeholderText,
              style: {
                zIndex: ue("overlay")
              },
              children: "- Total orders: ${orders_total_amount}"
            }
          ) : null,
          /* @__PURE__ */ i(
            G,
            {
              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"
              }
            }
          ),
          p && /* @__PURE__ */ i(
            Te,
            {
              fields: n,
              currentHtml: a || void 0,
              onApply: P
            }
          )
        ]
      }
    ) })
  ] }) : null;
};
export {
  Pe as TooltipConfig
};
//# sourceMappingURL=TooltipConfig-yx7IuTta.mjs.map
