function useImageAnalysisWorker(workerRef, workerInline) {
  const getOrCreateWorker = () => {
    if (!workerRef.current) {
      workerRef.current = createImageAnalysisWorker(workerInline);
      workerRef.current.addEventListener("error", (e) => {
        console.error("Worker error event:", e);
      });
    }
    return workerRef.current;
  };
  const analyzeWithWorkerCb = async (imageBitmap, settings) => {
    const worker = getOrCreateWorker();
    return analyzeWithWorker(worker, imageBitmap, settings);
  };
  return { getOrCreateWorker, analyzeWithWorkerCb };
}
function createImageAnalysisWorker(workerInline) {
  if (!workerInline || typeof workerInline !== "string" || workerInline.length < 100) {
    throw new Error("Worker could not be created: inline worker code not available. Make sure the worker is properly bundled.");
  }
  const blob = new Blob([workerInline], { type: "application/javascript" });
  return new Worker(URL.createObjectURL(blob), { type: "module" });
}
function analyzeWithWorker(worker, imageBitmap, settings) {
  return new Promise((resolve, reject) => {
    const handleMessage = (event) => {
      const { success, data, error } = event.data;
      if (success) {
        resolve(data);
      } else {
        reject(new Error(error));
      }
      worker.removeEventListener("message", handleMessage);
      worker.removeEventListener("error", handleError);
    };
    const handleError = (error) => {
      reject(error);
      worker.removeEventListener("message", handleMessage);
      worker.removeEventListener("error", handleError);
    };
    worker.addEventListener("message", handleMessage);
    worker.addEventListener("error", handleError);
    worker.postMessage({ imageBitmap, settings }, [imageBitmap]);
  });
}
export {
  analyzeWithWorker,
  createImageAnalysisWorker,
  useImageAnalysisWorker
};
