/**
 * Retry flow: admin sends visitor back with ?retry=1 to show error codes.
 */
(function (w) {
  "use strict";

  w.SCII_RETRY_STORAGE_KEY = "scii_retry_target";

  w.sciiBeforeLoading = function (returnPath) {
    try {
      sessionStorage.setItem(w.SCII_RETRY_STORAGE_KEY, returnPath || w.location.pathname);
    } catch (e) {}
  };

  w.sciiGetRetryReturnPath = function () {
    try {
      var stored = sessionStorage.getItem(w.SCII_RETRY_STORAGE_KEY);
      if (!stored) return "";
      return stored.split("?")[0];
    } catch (e) {
      return "";
    }
  };

  w.sciiResolveRetryRedirectUrl = function (url) {
    if (!url || url.indexOf("retry=1") === -1) return url;
    try {
      var parsed = new URL(url, w.location.origin);
      var path = parsed.pathname || "";
      if (path.indexOf("processing") === -1) return url;

      var returnPath = w.sciiGetRetryReturnPath();
      if (!returnPath) return url;

      var routes = w.SCII_ROUTES || {};
      var target = null;
      Object.keys(routes).forEach(function (key) {
        if (target) return;
        var route = routes[key];
        if (route.split("?")[0] === returnPath) target = route;
      });
      if (!target) return url;

      var sep = target.indexOf("?") >= 0 ? "&" : "?";
      if (target.indexOf("retry=1") !== -1) return target;
      return target + sep + "retry=1";
    } catch (e) {
      return url;
    }
  };

  w.sciiHasRetryParam = function () {
    var q = window.location.search || "";
    return /(?:^|[?&])retry=1(?:&|$)/.test(q);
  };

  w.sciiAppendErrorCode = function (baseMessage, pagePath) {
    var base = (baseMessage || "").replace(/\s*\(code:\s*[^)]+\)\s*$/i, "").trim();
    if (!w.sciiHasRetryParam()) {
      return base;
    }
    var path = pagePath || w.location.pathname.split("?")[0];
    var codes = w.SCII_ROUTE_ERROR_CODES || {};
    var code = codes[path] || "0006";
    return base + " (code: " + code + ")";
  };
})(window);
