if (!globalThis.requestIdleCallback) {
  globalThis.requestIdleCallback = (callback) =>
    window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 0 }), 0);
}

if (!globalThis.cancelIdleCallback) {
  globalThis.cancelIdleCallback = (handle) => window.clearTimeout(handle);
}

if (!globalThis.Headers) {
  class SimpleHeaders {
    constructor(init = {}) {
      this.map = new Map();
      const entries = init instanceof SimpleHeaders ? init.entries() : Object.entries(init || {});
      for (const [key, value] of entries) {
        this.set(key, value);
      }
    }

    get(name) {
      return this.map.get(String(name).toLowerCase()) ?? null;
    }

    set(name, value) {
      this.map.set(String(name).toLowerCase(), String(value));
    }

    entries() {
      return this.map.entries();
    }
  }

  globalThis.Headers = SimpleHeaders;
}

if (!globalThis.Response) {
  class SimpleResponse {
    constructor(body = "", init = {}) {
      this.body = body;
      this.status = Number(init.status ?? 200);
      this.ok = this.status >= 200 && this.status < 300;
      this.headers = new Headers(init.headers || {});
    }

    async text() {
      return String(this.body);
    }

    async json() {
      return JSON.parse(String(this.body));
    }
  }

  globalThis.Response = SimpleResponse;
}
