(function attachPyroWorkerClient(root) {
  'use strict';

  function createWorkerClient(url, options = {}) {
    const WorkerConstructor = options.Worker || root.Worker;
    let worker = null; let disabled = false; let generation = 0; let requestId = 0;
    const pending = new Map();

    function disable(error) {
      disabled = true;
      worker?.terminate?.(); worker = null;
      pending.forEach(({ reject }) => reject(error || new Error('Worker nicht verfügbar'))); pending.clear();
      options.onFallback?.(error);
    }

    function ensure() {
      if (disabled || typeof WorkerConstructor !== 'function') return null;
      if (worker) return worker;
      try {
        worker = new WorkerConstructor(url); generation += 1;
        worker.onmessage = ({ data = {} }) => {
          const task = pending.get(data.id); if (!task) return;
          pending.delete(data.id);
          if (data.cancelled) { const error = new Error('Worker-Berechnung ersetzt'); error.name = 'AbortError'; task.reject(error); return; }
          if (data.error) { task.reject(new Error(data.error)); return; }
          options.onResult?.(task.type, data.result); task.resolve(data.result);
        };
        worker.onerror = (event) => { event.preventDefault?.(); disable(new Error(event.message || 'Worker fehlgeschlagen')); };
        return worker;
      } catch (error) {
        disable(error); return null;
      }
    }

    function run(type, payload = {}, transfers = []) {
      const activeWorker = ensure();
      if (!activeWorker) return Promise.reject(new Error('Worker nicht verfügbar'));
      const id = `${options.idPrefix || 'worker-task'}-${++requestId}`;
      return new Promise((resolveTask, rejectTask) => {
        pending.set(id, { resolve: resolveTask, reject: rejectTask, type });
        try { activeWorker.postMessage({ id, type, ...payload }, transfers); }
        catch (error) { pending.delete(id); rejectTask(error); }
      });
    }

    return Object.freeze({
      ensure,
      run,
      disable,
      get generation() { return generation; },
      get active() { return Boolean(worker); },
      get disabled() { return disabled; }
    });
  }

  const api = Object.freeze({ createWorkerClient });
  root.PyroWorkerClient = api;
  if (typeof module === 'object' && module?.exports) module.exports = api;
})(typeof globalThis !== 'undefined' ? globalThis : window);
