(() => {
  const prefix = '[AssetManager][Performance]';
  const pageStart = performance.now();
  const active = new Map();
  const results = [];

  const now = () => Math.round((performance.now() - pageStart) * 10) / 10;
  const round = value => Math.round(value * 10) / 10;

  function start(name, details = {}) {
    active.set(name, performance.now());
    console.debug(prefix, `+${now()} ms`, `START ${name}`, details);
  }

  function end(name, details = {}) {
    const started = active.get(name);
    const duration = started == null ? null : performance.now() - started;
    active.delete(name);
    const result = {
      Modul: name,
      Start_ms: started == null ? null : round(started - pageStart),
      Dauer_ms: duration == null ? null : round(duration),
      ...details
    };
    results.push(result);
    const logger = duration != null && duration >= 50 ? console.warn : console.debug;
    logger(prefix, `+${now()} ms`, `ENDE ${name}`, result);
    return duration;
  }

  function measure(name, callback, details = {}) {
    const started = performance.now();
    try {
      return callback();
    } finally {
      const duration = performance.now() - started;
      const result = {
        Modul: name,
        Start_ms: round(started - pageStart),
        Dauer_ms: round(duration),
        ...details
      };
      results.push(result);
      const logger = duration >= 50 ? console.warn : console.debug;
      logger(prefix, `+${now()} ms`, name, result);
    }
  }

  async function measureAsync(name, callback, details = {}) {
    const started = performance.now();
    try {
      return await callback();
    } finally {
      const duration = performance.now() - started;
      const result = {
        Modul: name,
        Start_ms: round(started - pageStart),
        Dauer_ms: round(duration),
        ...details
      };
      results.push(result);
      const logger = duration >= 50 ? console.warn : console.debug;
      logger(prefix, `+${now()} ms`, name, result);
    }
  }

  function report(name, duration, details = {}, level = null) {
    const result = {
      Modul: name,
      Start_ms: details.Start_ms ?? null,
      Dauer_ms: round(duration),
      ...details
    };
    delete result.Start_ms;
    result.Start_ms = details.Start_ms ?? null;
    results.push(result);

    try {
      const safeName = name.replace(/[^a-zA-Z0-9:_-]+/g, '-');
      performance.mark(`${safeName}:end`);
      performance.measure(safeName, {
        start: Math.max(0, performance.now() - duration),
        end: performance.now()
      });
    } catch (_) {}

    const logger = level === 'warn' || (level == null && duration >= 50)
      ? console.warn
      : console.debug;
    logger(prefix, `+${now()} ms`, name, result);
    return result;
  }

  function summary() {
    const sorted = [...results].sort((a, b) => (b.Dauer_ms || 0) - (a.Dauer_ms || 0));
    console.groupCollapsed(`${prefix} Zusammenfassung – langsamste Vorgänge`);
    console.table(sorted.slice(0, 30));
    console.groupEnd();
    return sorted;
  }

  window.AssetPerf = { start, end, measure, measureAsync, report, summary, results };
})();