import { Value as c, Use as B, html as W, Task as F, attr as m, WithElement as I, OnDispose as R, effectOf as $ } from "@tempots/dom";
import { x as _ } from "../timer-Rd2sKnvH.js";
import { L as z } from "../link-portal-Cr2l9f3k.js";
import { T as N } from "../theme-BzpMLdvH.js";
const g = "https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/", G = (e) => {
  if (!e || typeof e != "object") return !1;
  const o = e;
  return !!(o.editor && typeof o.editor.create == "function" && o.languages);
};
function M() {
  if (typeof self > "u") return;
  const e = self.MonacoEnvironment;
  if (e && (typeof e.getWorkerUrl == "function" || typeof e.getWorker == "function"))
    return;
  const o = () => {
    const n = [
      `self.MonacoEnvironment = { baseUrl: '${g}' };`,
      `importScripts('${g}vs/base/worker/workerMain.js');`
    ].join(`
`), r = new Blob([n], { type: "text/javascript" });
    return URL.createObjectURL(r);
  };
  self.MonacoEnvironment = {
    getWorkerUrl(n, r) {
      return o();
    }
  };
}
const H = (e) => new Promise((o, n) => {
  if (document.querySelector(`script[src="${e}"]`)) return o();
  const a = document.createElement("script");
  a.src = e, a.async = !0;
  const l = document.querySelector("script[nonce]")?.getAttribute("nonce");
  l && a.setAttribute("nonce", l), a.onload = () => o(), a.onerror = (w) => {
    console.error("[BeatUI] Failed to load script", e, w), n(new Error(`Failed to load script ${e}`));
  }, document.head.appendChild(a);
}), K = async () => {
  const e = window;
  if ((!e.require || !e.require.config) && (await H(`${g}vs/loader.js`), await new Promise((o) => setTimeout(o, 100)), !e.require))
    throw new Error("AMD loader failed to initialize");
  return e.require.config?.({ baseUrl: g, paths: { vs: "vs" } }), e.require;
}, Q = async () => {
  const e = window;
  if (e.monaco && G(e.monaco)) return e.monaco;
  M();
  const o = await K();
  if (await new Promise((n, r) => {
    const a = setTimeout(
      () => r(new Error("Timeout loading editor.main")),
      3e4
    );
    try {
      o(
        ["vs/editor/editor.main"],
        () => {
          clearTimeout(a), n();
        },
        (l) => {
          clearTimeout(a), r(l);
        }
      );
    } catch (l) {
      clearTimeout(a), r(l);
    }
  }), !e.monaco)
    throw new Error("Monaco failed to initialize after loading editor.main");
  return e.monaco;
};
let b = null;
const v = /* @__PURE__ */ new Map();
let h = !1;
async function j() {
  if (b)
    return b;
  !h && typeof window < "u" && (M(), h = !0);
  const e = await Q();
  return b = e, e;
}
async function X(e) {
  if (v.has(e))
    return v.get(e);
  const o = (async () => {
    const n = await j();
    switch (e) {
      case "typescript":
      case "javascript": {
        n.typescript.javascriptDefaults.setDiagnosticsOptions({
          noSemanticValidation: !1,
          noSyntaxValidation: !1
        }), n.typescript.typescriptDefaults.setDiagnosticsOptions({
          noSemanticValidation: !1,
          noSyntaxValidation: !1
        });
        break;
      }
      case "json": {
        n.json.jsonDefaults.setDiagnosticsOptions({
          validate: !0,
          schemas: [],
          enableSchemaRequest: !0
        });
        break;
      }
      case "css":
      case "scss":
      case "less": {
        n.css.cssDefaults.setOptions({
          validate: !0
        });
        break;
      }
      case "html":
        break;
      case "markdown":
        break;
      case "yaml": {
        n.languages.getLanguages().some((a) => a.id === "yaml") || n.languages.register({
          id: "yaml",
          extensions: [".yml", ".yaml"]
        });
        break;
      }
    }
  })();
  return v.set(e, o), o;
}
async function S(e) {
  const [o] = await Promise.all([
    j(),
    X(e)
  ]);
  return o;
}
function ae(e) {
  if (typeof window > "u") return;
  const o = window;
  e ? (o.MonacoEnvironment = {
    getWorker: e
  }, h = !0) : o.MonacoEnvironment || (M(), h = !0);
}
const se = (e) => {
  const {
    value: o,
    onChange: n,
    onBlur: r,
    language: a = "plaintext",
    readOnly: l = !1,
    editorOptions: w,
    jsonSchemas: D,
    autofocus: x,
    class: L,
    disabled: q,
    hasError: C,
    id: T,
    name: U,
    placeholder: V
  } = e, E = c.toSignal(l);
  return B(
    N,
    ({ appearance: A }) => W.div(
      (e.cssInjection ?? "none") === "none" ? null : F(
        () => import("../styles-url-CSXq0ZRz.js"),
        ({ default: u }) => z({ id: "beatui-monaco-css", href: u })
      ),
      m.class("bc-monaco-editor-container"),
      m.class(L),
      m.class(
        c.map(
          C ?? !1,
          (u) => u ? "bc-input-container--error" : ""
        )
      ),
      m.id(T),
      m.name(U),
      I((u) => {
        let f = null;
        const i = [];
        return (async () => {
          try {
            let d = function() {
              const t = s.getValue();
              n?.(t);
            };
            const p = c.get(a) ?? "plaintext";
            if (f = (await S(p)).editor.create(u, {
              value: c.get(o) ?? "",
              language: p,
              readOnly: c.get(E) ?? !1,
              automaticLayout: !0,
              minimap: { enabled: !1 },
              ...w ?? {}
            }), !f)
              throw new Error("Failed to create Monaco editor");
            const s = f;
            i.push(
              $(
                a,
                D
              )(async (t, y) => {
                const k = await S(t);
                if (t === "json") {
                  const P = {
                    validate: !0,
                    enableSchemaRequest: !0,
                    schemas: !!(y && y.length) ? y : []
                  };
                  k.json.jsonDefaults.setDiagnosticsOptions(P);
                }
                const O = s.getModel();
                O && k.editor.setModelLanguage(O, t);
              })
            ), i.push(
              s.onDidChangeModelContent(_(500, d)).dispose
            ), i.push(
              s.onDidBlurEditorText(() => {
                d(), r?.();
              }).dispose
            ), i.push(
              c.on(o, (t) => {
                t !== s.getValue() && s.setValue(t ?? "");
              })
            ), i.push(
              c.on(E, (t) => {
                s.updateOptions({ readOnly: t ?? !1 });
              })
            ), i.push(
              c.on(q ?? !1, (t) => {
                s.updateOptions({ readOnly: t ?? !1 });
              })
            ), i.push(
              c.on(x ?? !1, (t) => {
                t && s.focus();
              })
            ), i.push(
              c.on(V ?? "", (t) => {
                s.updateOptions({ placeholder: t ?? "" });
              })
            ), i.push(
              A.on((t) => {
                s.updateOptions({ theme: t === "dark" ? "vs-dark" : "vs" });
              })
            );
          } catch (d) {
            console.error("[BeatUI] Failed to initialize Monaco editor:", d);
            const p = u;
            p.textContent = "Failed to load Monaco Editor. Please ensure monaco-editor is installed.";
          }
        })(), R(() => {
          try {
            i.forEach((d) => d());
          } catch {
          }
          try {
            f?.dispose();
          } catch {
          }
        });
      })
    )
  );
};
export {
  se as MonacoEditorInput,
  ae as configureMonacoEnvironment
};
