(function () {
  var supportsServiceWorker = "serviceWorker" in navigator;
  var isSecureContext =
    window.location.protocol === "https:" ||
    window.location.hostname === "localhost" ||
    window.location.hostname === "127.0.0.1";

  if (!supportsServiceWorker || !isSecureContext) {
    return;
  }

  function normalizeBaseUrl(url) {
    if (!url) {
      return window.location.origin + "/";
    }

    return url.endsWith("/") ? url : url + "/";
  }

  function getBaseUrl() {
    var baseInput = document.getElementById("url");
    var rawBase = baseInput && baseInput.value ? baseInput.value : window.location.origin + "/";
    return normalizeBaseUrl(rawBase);
  }

  window.addEventListener("load", function () {
    var baseUrl = getBaseUrl();
    var serviceWorkerUrl = new URL("sw.js", baseUrl).toString();

    navigator.serviceWorker.register(serviceWorkerUrl, { scope: baseUrl }).catch(function (error) {
      console.warn("No se pudo registrar el Service Worker:", error);
    });
  });
})();
