var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
import { useState, useEffect, createElement } from "react";
import { DevErrorBadge, DevErrorList } from "@contember/ui";
import { useProcessedError } from "./useParsedStacktrace.js";
class ErrorBus {
  constructor() {
    __publicField(this, "queue", []);
    __publicField(this, "listener", null);
  }
  async handleError(source, error) {
    const boxedError = { error, source };
    if (!this.listener) {
      this.queue.push(boxedError);
    } else {
      this.listener(boxedError);
    }
  }
  register(listener) {
    this.listener = listener;
    this.queue.forEach(listener);
    this.queue = [];
    return () => {
      this.listener = null;
    };
  }
}
function DevErrorManager(props) {
  const [errors, setErrors] = useState([]);
  const [errIndex, setErrorIndex] = useState(0);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    return props.bus.register((err) => {
      setTimeout(() => {
        setErrors((errors2) => [err, ...errors2]);
        setOpen(true);
      }, 0);
    });
  }, [props.bus]);
  const currentError = errors[errIndex];
  const processedError = useProcessedError(currentError?.error);
  if (!currentError) {
    return null;
  }
  const onPrevious = () => setErrorIndex((it) => Math.max(0, it - 1));
  const onNext = () => setErrorIndex((it) => Math.min(errors.length - 1, it + 1));
  const onClose = () => setOpen(false);
  if (!open) {
    return /* @__PURE__ */ createElement(DevErrorBadge, {
      errorCount: errors.length,
      onOpen: () => setOpen(true)
    });
  }
  return /* @__PURE__ */ createElement(DevErrorList, {
    currentError: processedError,
    currentErrorSource: currentError.source,
    currentErrorIndex: errIndex,
    errorCount: errors.length,
    onPrevious,
    onNext,
    onClose
  });
}
export { DevErrorManager, ErrorBus };
//# sourceMappingURL=DevErrorManager.js.map
