import { t as s } from "./defineProperty-8fd4b6d7.js";
var n = class {
  constructor() {
    s(this, "providerId", "desmos"), s(this, "providerName", "Desmos"), s(this, "supportedTypes", [
      "basic",
      "scientific",
      "graphing"
    ]), s(this, "version", "1.10"), s(this, "initialized", !1), s(this, "apiKey", void 0), s(this, "proxyEndpoint", void 0), s(this, "isDevelopment", !1), s(this, "onTelemetry", void 0);
  }
  async emitTelemetry(e, o) {
    try {
      await this.onTelemetry?.(e, o);
    } catch (t) {
      console.warn("[DesmosProvider] telemetry callback failed:", t);
    }
  }
  getApiKey() {
    return this.apiKey;
  }
  async loadDesmosScript() {
    return new Promise((e, o) => {
      const t = document.createElement("script");
      t.src = this.apiKey ? `https://www.desmos.com/api/v1.10/calculator.js?apiKey=${this.apiKey}` : "https://www.desmos.com/api/v1.10/calculator.js", t.async = !0, t.onload = () => {
        window.Desmos ? (console.log("[DesmosProvider] Desmos API loaded successfully"), e()) : o(/* @__PURE__ */ new Error("Desmos API loaded but window.Desmos is undefined"));
      }, t.onerror = () => {
        o(/* @__PURE__ */ new Error("Failed to load Desmos API from CDN"));
      }, document.head.appendChild(t);
    });
  }
  async initialize(e) {
    if (!this.initialized) {
      if (this.onTelemetry = e?.onTelemetry, typeof window > "u") throw new Error("Desmos calculators can only be initialized in the browser");
      if (this.isDevelopment = process.env.NODE_ENV === "development" || typeof process > "u" || !process.env.NODE_ENV, e?.proxyEndpoint) {
        this.proxyEndpoint = e.proxyEndpoint;
        const o = Date.now();
        await this.emitTelemetry("pie-tool-backend-call-start", {
          toolId: "calculator",
          backend: "desmos",
          operation: "proxy-auth-fetch"
        });
        try {
          const t = await fetch(e.proxyEndpoint);
          if (!t.ok) throw new Error(`Proxy endpoint returned ${t.status}`);
          const r = await t.json();
          this.apiKey = r.apiKey, await this.emitTelemetry("pie-tool-backend-call-success", {
            toolId: "calculator",
            backend: "desmos",
            operation: "proxy-auth-fetch",
            duration: Date.now() - o
          }), console.log("[DesmosProvider] Initialized with server-side proxy (SECURE)");
        } catch (t) {
          throw await this.emitTelemetry("pie-tool-backend-call-error", {
            toolId: "calculator",
            backend: "desmos",
            operation: "proxy-auth-fetch",
            duration: Date.now() - o,
            errorType: "CalculatorProxyAuthError",
            message: t instanceof Error ? t.message : String(t)
          }), new Error(`[DesmosProvider] Failed to fetch API key from proxy: ${t}`);
        }
      } else e?.apiKey ? (this.apiKey = e.apiKey, this.isDevelopment ? console.log("[DesmosProvider] Initialized with direct API key (DEVELOPMENT MODE)") : console.error(`⚠️ [DesmosProvider] SECURITY WARNING: API key exposed in client-side code!
This is insecure for production. Use proxyEndpoint instead.
See: https://pie-players.dev/docs/calculator-desmos#security`)) : console.warn(`[DesmosProvider] No API key or proxy endpoint provided.
Production usage requires authentication. Obtain API key from https://www.desmos.com/api
Recommended: Use proxyEndpoint for production, apiKey for development only.`);
      if (!window.Desmos) {
        console.log("[DesmosProvider] Loading Desmos API library...");
        const o = Date.now();
        await this.emitTelemetry("pie-tool-library-load-start", {
          toolId: "calculator",
          backend: "desmos",
          operation: "desmos-script-load"
        });
        try {
          await this.loadDesmosScript(), await this.emitTelemetry("pie-tool-library-load-success", {
            toolId: "calculator",
            backend: "desmos",
            operation: "desmos-script-load",
            duration: Date.now() - o
          });
        } catch (t) {
          throw await this.emitTelemetry("pie-tool-library-load-error", {
            toolId: "calculator",
            backend: "desmos",
            operation: "desmos-script-load",
            duration: Date.now() - o,
            errorType: "ToolLibraryLoadError",
            message: t instanceof Error ? t.message : String(t)
          }), t;
        }
      }
      this.initialized = !0;
    }
  }
  async createCalculator(e, o, t) {
    if (this.initialized || await this.initialize(), !this.supportsType(e)) throw new Error(`Desmos does not support calculator type: ${e}`);
    return new a(this, e, o, t, this.apiKey);
  }
  supportsType(e) {
    return this.supportedTypes.includes(e);
  }
  destroy() {
    this.initialized = !1, this.onTelemetry = void 0;
  }
  getCapabilities() {
    return {
      supportsHistory: !1,
      supportsGraphing: !0,
      supportsExpressions: !0,
      canExport: !0,
      maxPrecision: 15,
      inputMethods: [
        "keyboard",
        "mouse",
        "touch"
      ]
    };
  }
}, a = class {
  constructor(e, o, t, r, i) {
    if (s(this, "provider", void 0), s(this, "type", void 0), s(this, "Desmos", void 0), s(this, "calculator", void 0), s(this, "container", void 0), this.provider = e, this.type = o, this.container = t, this.Desmos = window.Desmos, !this.Desmos) throw new Error("Desmos API not available");
    this._initializeCalculator(r, i);
  }
  _initializeCalculator(e, o) {
    const t = {
      ...e?.desmos || {},
      apiKey: o || e?.desmos?.apiKey
    };
    switch (e?.restrictedMode && Object.assign(t, {
      expressionsTopbar: !1,
      settingsMenu: !1,
      zoomButtons: !1,
      expressions: !1,
      links: !1
    }), this.type) {
      case "graphing":
        this.calculator = this.Desmos.GraphingCalculator(this.container, t);
        break;
      case "scientific":
        this.calculator = this.Desmos.ScientificCalculator(this.container, t);
        break;
      case "basic":
        this.calculator = this.Desmos.FourFunctionCalculator(this.container, t);
        break;
      default:
        throw new Error(`Unsupported calculator type: ${this.type}`);
    }
    console.log(`[DesmosCalculator] Created ${this.type} calculator`);
  }
  getValue() {
    if (this.type === "graphing" && this.calculator.getState) {
      const e = this.calculator.getState();
      return JSON.stringify(e);
    }
    return "";
  }
  setValue(e) {
    if (this.type === "graphing" && this.calculator.setState) try {
      const o = JSON.parse(e);
      this.calculator.setState(o);
    } catch (o) {
      console.error("[DesmosCalculator] Failed to set state:", o);
    }
  }
  clear() {
    this.calculator.setBlank && this.calculator.setBlank();
  }
  async evaluate(e) {
    return this.type === "graphing" ? new Promise((o) => {
      const t = `eval_${Date.now()}`;
      this.calculator.setExpression({
        id: t,
        latex: e
      }), setTimeout(() => {
        const r = this.calculator.HelperExpression({ latex: e }).numericValue || e;
        this.calculator.removeExpression({ id: t }), o(String(r));
      }, 100);
    }) : e;
  }
  resize() {
    this.calculator.resize && this.calculator.resize();
  }
  focus() {
    try {
      if (this.type === "graphing" && typeof this.calculator?.focusFirstExpression == "function") {
        this.calculator.focusFirstExpression();
        return;
      }
      this.container.querySelector('.dcg-mq-editable-field[tabindex="0"], textarea, [contenteditable="true"], [tabindex]:not([tabindex="-1"])')?.focus();
    } catch (e) {
      console.warn("[DesmosCalculator] focus() failed:", e);
    }
  }
  exportState() {
    let e = {};
    return this.type === "graphing" && this.calculator.getState && (e = this.calculator.getState()), {
      type: this.type,
      provider: "desmos",
      value: this.getValue(),
      providerState: e
    };
  }
  importState(e) {
    if (e.provider !== "desmos") throw new Error(`Cannot import state from provider: ${e.provider}`);
    e.providerState && this.calculator.setState ? this.calculator.setState(e.providerState) : e.value && this.setValue(e.value);
  }
  destroy() {
    this.calculator && this.calculator.destroy && this.calculator.destroy(), this.container.replaceChildren(), console.log("[DesmosCalculator] destroyed");
  }
};
export {
  n as DesmosCalculatorProvider
};
