// src/contexts/StudioEventsContext.tsx
import { createContext, useContext, useEffect, useRef, useCallback } from "react";

// src/lib/api.ts
function getBasePath() {
  const win = typeof globalThis !== "undefined" ? (
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- runtime global check at system boundary
    globalThis["window"]
  ) : void 0;
  if (win && typeof win["__STUDIO_BASE_PATH__"] === "string") {
    return win["__STUDIO_BASE_PATH__"];
  }
  return "";
}
function studioApiUrl(path) {
  return `${getBasePath()}${path}`;
}

// src/contexts/StudioEventsContext.tsx
import { jsx } from "react/jsx-runtime";
var STUDIO_EVENT_TYPES = [
  "store_updated",
  "session_updated",
  "feedback_created",
  "automation_started",
  "automation_completed"
];
var SSE_ENDPOINT_PATH = "/api/events";
var StudioEventsContext = createContext({
  subscribe: () => () => {
  }
});
function StudioEventsProvider({ children }) {
  const listenersRef = useRef(/* @__PURE__ */ new Map());
  useEffect(() => {
    const es = new EventSource(studioApiUrl(SSE_ENDPOINT_PATH));
    for (const type of STUDIO_EVENT_TYPES) {
      es.addEventListener(type, (e) => {
        const handlers = listenersRef.current.get(type);
        if (!handlers) return;
        let payload;
        const rawData = e.data;
        try {
          payload = typeof rawData === "string" ? JSON.parse(rawData) : rawData;
        } catch {
          payload = rawData;
        }
        for (const handler of handlers) {
          handler(payload);
        }
      });
    }
    return () => {
      es.close();
    };
  }, []);
  const subscribe = useCallback(
    (types, handler) => {
      for (const type of types) {
        if (!listenersRef.current.has(type)) {
          listenersRef.current.set(type, /* @__PURE__ */ new Set());
        }
        listenersRef.current.get(type).add(handler);
      }
      return () => {
        for (const type of types) {
          listenersRef.current.get(type)?.delete(handler);
        }
      };
    },
    []
  );
  return /* @__PURE__ */ jsx(StudioEventsContext.Provider, { value: { subscribe }, children });
}
function useStudioEvents(types, handler) {
  const { subscribe } = useContext(StudioEventsContext);
  const handlerRef = useRef(handler);
  handlerRef.current = handler;
  useEffect(
    () => subscribe(types, (payload) => handlerRef.current(payload)),
    [subscribe, ...types]
  );
}
export {
  STUDIO_EVENT_TYPES,
  StudioEventsContext,
  StudioEventsProvider,
  useStudioEvents
};
/**
 * @license
 * Copyright 2026 Amodal Labs, Inc.
 * SPDX-License-Identifier: MIT
 */
//# sourceMappingURL=events.js.map
