import {
  Syntro
} from "./chunk-RUKIPJEJ.js";
import "./chunk-AYTRRBR5.js";

// src/react.tsx
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { jsx } from "react/jsx-runtime";
var SyntroContext = createContext(null);
var globalInitPromise = null;
var globalInitToken = null;
function SyntroProvider({
  token,
  canvasOptions,
  fetcher,
  children,
  onReady,
  onError
}) {
  const [state, setState] = useState({
    canvas: null,
    experiments: null,
    telemetry: null,
    isReady: false,
    error: null
  });
  const initRef = useRef(false);
  const handleRef = useRef(null);
  useEffect(() => {
    if (!token) return;
    if (globalInitPromise && globalInitToken === token) {
      globalInitPromise.then((result) => {
        var _a, _b;
        handleRef.current = result.canvas;
        setState({
          canvas: result.canvas,
          experiments: (_a = result.experiments) != null ? _a : null,
          telemetry: (_b = result.telemetry) != null ? _b : null,
          isReady: true,
          error: null
        });
      });
      return;
    }
    if (initRef.current) return;
    initRef.current = true;
    globalInitToken = token;
    globalInitPromise = Syntro.init({ token, canvas: canvasOptions, fetcher });
    globalInitPromise.then((result) => {
      var _a, _b;
      handleRef.current = result.canvas;
      setState({
        canvas: result.canvas,
        experiments: (_a = result.experiments) != null ? _a : null,
        telemetry: (_b = result.telemetry) != null ? _b : null,
        isReady: true,
        error: null
      });
      onReady == null ? void 0 : onReady(result);
    }).catch((err) => {
      const error = err instanceof Error ? err : new Error(String(err));
      setState((prev) => ({ ...prev, error, isReady: true }));
      onError == null ? void 0 : onError(error);
      globalInitPromise = null;
      globalInitToken = null;
    });
  }, [token, canvasOptions, fetcher, onError, onReady]);
  return /* @__PURE__ */ jsx(SyntroContext.Provider, { value: state, children });
}
function useSyntro() {
  const context = useContext(SyntroContext);
  if (!context) {
    throw new Error("useSyntro must be used within a SyntroProvider");
  }
  return context;
}
function useSyntroReady() {
  return useSyntro().isReady;
}
function useSyntroExperiments() {
  return useSyntro().experiments;
}
function useSyntroTelemetry() {
  return useSyntro().telemetry;
}
function useSyntroCanvas() {
  return useSyntro().canvas;
}
export {
  SyntroProvider,
  useSyntro,
  useSyntroCanvas,
  useSyntroExperiments,
  useSyntroReady,
  useSyntroTelemetry
};
//# sourceMappingURL=react.js.map
