export function initPasswordToggles() {
  const inputs = document.querySelectorAll('input[type="password"]');
  if (!inputs.length) {return;}

  const showLabel = (document.documentElement.dataset.passwordToggleShowLabel || '').trim();
  const hideLabel = (document.documentElement.dataset.passwordToggleHideLabel || '').trim();
  if (!showLabel || !hideLabel) {return;}

  inputs.forEach((input) => {
    if (!(input instanceof HTMLInputElement)) {return;}
    if (input.dataset.passwordToggleBound === '1') {return;}

    const label = input.closest('label');
    if (!label) {return;}

    const parent = input.parentElement;
    if (parent instanceof HTMLElement && parent.classList.contains('login-password-wrapper')) {
      const existingToggle = parent.querySelector('.login-password-toggle');
      if (existingToggle instanceof HTMLButtonElement) {
        input.dataset.passwordToggleBound = '1';
        existingToggle.dataset.passwordToggleBound = '1';
        existingToggle.setAttribute('aria-label', input.type === 'password' ? showLabel : hideLabel);
        return;
      }
    }

    const wrapper = document.createElement('div');
    wrapper.className = 'login-password-wrapper';

    const toggle = document.createElement('button');
    toggle.type = 'button';
    toggle.className = 'login-password-toggle';
    toggle.setAttribute('aria-label', showLabel);
    toggle.innerHTML = '<i class="bi bi-eye" aria-hidden="true"></i>';

    input.replaceWith(wrapper);
    wrapper.appendChild(input);
    wrapper.appendChild(toggle);

    input.dataset.passwordToggleBound = '1';
    toggle.dataset.passwordToggleBound = '1';

    toggle.addEventListener('click', () => {
      const isPassword = input.type === 'password';
      input.type = isPassword ? 'text' : 'password';
      toggle.innerHTML = isPassword
        ? '<i class="bi bi-eye-slash" aria-hidden="true"></i>'
        : '<i class="bi bi-eye" aria-hidden="true"></i>';
      toggle.setAttribute('aria-label', isPassword ? hideLabel : showLabel);
      input.focus();
    });
  });
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initPasswordToggles);
} else {
  initPasswordToggles();
}
