(function attachTVMazeClient(root) {
  "use strict";

  function TVMazeClient(fetchImpl, baseUrl) {
    this.fetchImpl = fetchImpl;
    this.baseUrl = baseUrl || "https://api.tvmaze.com";
    this.timeoutMs = 5000;
    this.cacheTtlMs = 12 * 60 * 60 * 1000;
    this.cache = new Map();
  }

  TVMazeClient.prototype.getCached = async function getCached(key, loader) {
    var existing = this.cache.get(key);
    var now = Date.now();

    if (existing && existing.expiresAt > now) {
      return existing.value;
    }

    var value = await loader();
    this.cache.set(key, {
      value: value,
      expiresAt: now + this.cacheTtlMs
    });
    return value;
  };

  TVMazeClient.prototype.requestJson = async function requestJson(pathname) {
    var controller = new AbortController();
    var timeoutId = setTimeout(function onTimeout() {
      controller.abort();
    }, this.timeoutMs);
    var response = await this.fetchImpl(this.baseUrl + pathname, {
      headers: {
        "accept": "application/json"
      },
      signal: controller.signal
    });
    clearTimeout(timeoutId);

    if (!response.ok) {
      throw new Error("TVMaze request failed: " + response.status + " " + pathname);
    }

    return response.json();
  };

  TVMazeClient.prototype.searchShows = async function searchShows(query) {
    var cacheKey = "search|" + String(query || "").toLowerCase();
    var self = this;
    return this.getCached(cacheKey, function loadSearch() {
      return self.requestJson("/search/shows?q=" + encodeURIComponent(query));
    });
  };

  TVMazeClient.prototype.getEpisodeByNumber = async function getEpisodeByNumber(showId, seasonNumber, episodeNumber) {
    var cacheKey = ["episode", showId, seasonNumber, episodeNumber].join("|");
    var self = this;
    return this.getCached(cacheKey, function loadEpisode() {
      return self.requestJson("/shows/" + showId + "/episodebynumber?season=" + seasonNumber + "&number=" + episodeNumber);
    });
  };

  var api = {
    TVMazeClient: TVMazeClient
  };

  root.SafeSceneTVMaze = api;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = api;
  }
}(typeof globalThis !== "undefined" ? globalThis : this));
