/*
 * Melhorias visuais/acessibilidade das telas de acesso v2 (entrar e mudar_senha).
 * NÃO substitui a lógica do entrar.js / mudar_senha.js: apenas complementa
 * (aria dos botões de mostrar senha, aviso de Caps Lock, estado "ocupado"
 * espelhando a linha de carregamento e teclado em elementos clicáveis).
 */
(function () {
  "use strict";

  // Mostrar/ocultar senha: o entrar.js / mudar_senha.js já trocam o type da input;
  // aqui apenas atualizamos o aria-pressed e o rótulo depois do clique deles.
  var toggles = document.querySelectorAll(".kl .toggle_view");
  Array.prototype.forEach.call(toggles, function (toggle) {
    toggle.addEventListener("click", function () {
      var input = toggle.parentNode.querySelector("input");
      setTimeout(function () {
        if (!input) return;
        var visible = input.type === "text";
        toggle.setAttribute("aria-pressed", visible ? "true" : "false");
        toggle.setAttribute("aria-label", visible ? "Ocultar senha" : "Mostrar senha");
        toggle.setAttribute("title", visible ? "Ocultar senha" : "Mostrar senha");
      }, 0);
    });
  });

  // Elementos clicáveis que não são botões (setas de voltar, reenviar código)
  var pseudoButtons = document.querySelectorAll(".kl [data-kl-key]");
  Array.prototype.forEach.call(pseudoButtons, function (el) {
    el.addEventListener("keydown", function (event) {
      if (event.key === "Enter" || event.key === " " || event.key === "Spacebar") {
        event.preventDefault();
        el.click();
      }
    });
  });

  // Aviso de Caps Lock nos campos de senha
  var caps = document.getElementById("kl_caps");
  if (caps) {
    var passwords = document.querySelectorAll(".kl input[type='password']");
    var checkCaps = function (event) {
      if (typeof event.getModifierState !== "function") return;
      caps.textContent = event.getModifierState("CapsLock") ? "Caps Lock ativado" : "";
    };
    Array.prototype.forEach.call(passwords, function (input) {
      input.addEventListener("keyup", checkCaps);
      input.addEventListener("keydown", checkCaps);
      input.addEventListener("blur", function () { caps.textContent = ""; });
    });
  }

  // Estado ocupado: espelha a opacidade que o JS original aplica em .father_line_loading
  var line = document.querySelector(".kl .father_line_loading");
  var card = document.querySelector(".kl .box_informations");
  if (line && card && typeof MutationObserver !== "undefined") {
    var sync = function () {
      var busy = line.style.opacity === "1";
      card.classList.toggle("kl-busy", busy);
      card.setAttribute("aria-busy", busy ? "true" : "false");
    };
    new MutationObserver(sync).observe(line, { attributes: true, attributeFilter: ["style"] });
    sync();
  }
})();
