import { t as s } from "./defineProperty-Dt7ri80W-76aeaed7.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(t, o) {
    try {
      await this.onTelemetry?.(t, o);
    } catch (e) {
      console.warn("[DesmosProvider] telemetry callback failed:", e);
    }
  }
  getApiKey() {
    return this.apiKey;
  }
  async loadDesmosScript() {
    return new Promise((t, o) => {
      const e = document.createElement("script");
      e.src = this.apiKey ? `https://www.desmos.com/api/v1.10/calculator.js?apiKey=${this.apiKey}` : "https://www.desmos.com/api/v1.10/calculator.js", e.async = !0, e.onload = () => {
        window.Desmos ? (console.log("[DesmosProvider] Desmos API loaded successfully"), t()) : o(/* @__PURE__ */ new Error("Desmos API loaded but window.Desmos is undefined"));
      }, e.onerror = () => {
        o(/* @__PURE__ */ new Error("Failed to load Desmos API from CDN"));
      }, document.head.appendChild(e);
    });
  }
  async initialize(t) {
    if (!this.initialized) {
      if (this.onTelemetry = t?.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, t?.proxyEndpoint) {
        this.proxyEndpoint = t.proxyEndpoint;
        const o = Date.now();
        await this.emitTelemetry("pie-tool-backend-call-start", {
          toolId: "calculator",
          backend: "desmos",
          operation: "proxy-auth-fetch"
        });
        try {
          const e = await fetch(t.proxyEndpoint);
          if (!e.ok) throw new Error(`Proxy endpoint returned ${e.status}`);
          const i = await e.json();
          this.apiKey = i.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 (e) {
          throw await this.emitTelemetry("pie-tool-backend-call-error", {
            toolId: "calculator",
            backend: "desmos",
            operation: "proxy-auth-fetch",
            duration: Date.now() - o,
            errorType: "CalculatorProxyAuthError",
            message: e instanceof Error ? e.message : String(e)
          }), /* @__PURE__ */ new Error(`[DesmosProvider] Failed to fetch API key from proxy: ${e}`);
        }
      } else t?.apiKey ? (this.apiKey = t.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 (e) {
          throw await this.emitTelemetry("pie-tool-library-load-error", {
            toolId: "calculator",
            backend: "desmos",
            operation: "desmos-script-load",
            duration: Date.now() - o,
            errorType: "ToolLibraryLoadError",
            message: e instanceof Error ? e.message : String(e)
          }), e;
        }
      }
      this.initialized = !0;
    }
  }
  async createCalculator(t, o, e) {
    if (this.initialized || await this.initialize(), !this.supportsType(t)) throw new Error(`Desmos does not support calculator type: ${t}`);
    return new a(this, t, o, e, this.apiKey);
  }
  supportsType(t) {
    return this.supportedTypes.includes(t);
  }
  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(t, o, e, i, r) {
    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 = t, this.type = o, this.container = e, this.Desmos = window.Desmos, !this.Desmos) throw new Error("Desmos API not available");
    this._initializeCalculator(i, r);
  }
  _initializeCalculator(t, o) {
    const e = {
      ...t?.desmos || {},
      apiKey: o || t?.desmos?.apiKey
    };
    switch (t?.restrictedMode && Object.assign(e, {
      expressionsTopbar: !1,
      settingsMenu: !1,
      zoomButtons: !1,
      expressions: !1,
      links: !1
    }), this.type) {
      case "graphing":
        this.calculator = this.Desmos.GraphingCalculator(this.container, e);
        break;
      case "scientific":
        this.calculator = this.Desmos.ScientificCalculator(this.container, e);
        break;
      case "basic":
        this.calculator = this.Desmos.FourFunctionCalculator(this.container, e);
        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 t = this.calculator.getState();
      return JSON.stringify(t);
    }
    return "";
  }
  setValue(t) {
    if (this.type === "graphing" && this.calculator.setState) try {
      const o = JSON.parse(t);
      this.calculator.setState(o);
    } catch (o) {
      console.error("[DesmosCalculator] Failed to set state:", o);
    }
  }
  clear() {
    this.calculator.setBlank && this.calculator.setBlank();
  }
  async evaluate(t) {
    return this.type === "graphing" ? new Promise((o) => {
      const e = `eval_${Date.now()}`;
      this.calculator.setExpression({
        id: e,
        latex: t
      }), setTimeout(() => {
        const i = this.calculator.HelperExpression({ latex: t }).numericValue || t;
        this.calculator.removeExpression({ id: e }), o(String(i));
      }, 100);
    }) : t;
  }
  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 (t) {
      console.warn("[DesmosCalculator] focus() failed:", t);
    }
  }
  exportState() {
    let t = {};
    return this.type === "graphing" && this.calculator.getState && (t = this.calculator.getState()), {
      type: this.type,
      provider: "desmos",
      value: this.getValue(),
      providerState: t
    };
  }
  importState(t) {
    if (t.provider !== "desmos") throw new Error(`Cannot import state from provider: ${t.provider}`);
    t.providerState && this.calculator.setState ? this.calculator.setState(t.providerState) : t.value && this.setValue(t.value);
  }
  destroy() {
    this.calculator && this.calculator.destroy && this.calculator.destroy(), this.container.replaceChildren(), console.log("[DesmosCalculator] destroyed");
  }
};
export {
  n as DesmosCalculatorProvider
};
