document.addEventListener('DOMContentLoaded', function () {
  highlightActiveNav();
  loadUnreadNotifications();
  attachPhoneFormatting();
  attachLogoutConfirm();
  attachValidationHelpers();
});

function highlightActiveNav() {
  const path = window.location.pathname.split('/').pop() || 'dashboard.php';
  document.querySelectorAll('.portal-nav-link').forEach(function (link) {
    const href = link.getAttribute('href') || '';
    if (href.endsWith(path)) {
      link.classList.add('active');
    }
  });
}

function loadUnreadNotifications() {
  const badge = document.getElementById('portalUnreadBadge');
  const url = document.body.getAttribute('data-notifications-url');
  if (!badge || !url) {
    return;
  }

  fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'from_bell=1'
  })
    .then(function (response) { return response.json(); })
    .then(function (data) {
      const count = parseInt((data && data.unread_count) || 0, 10);
      badge.textContent = count > 99 ? '99+' : String(count);
      badge.style.display = count > 0 ? 'inline-flex' : 'none';
    })
    .catch(function () {
      badge.style.display = 'none';
    });
}

function attachPhoneFormatting() {
  document.querySelectorAll('[data-phone-input]').forEach(function (field) {
    field.addEventListener('input', function () {
      let value = field.value.replace(/\D/g, '');
      if (value.startsWith('233')) {
        value = '0' + value.slice(3);
      }
      if (value.length > 10) {
        value = value.slice(0, 10);
      }
      field.value = value;
    });
  });
}

function attachLogoutConfirm() {
  document.querySelectorAll('[data-logout-link]').forEach(function (link) {
    link.addEventListener('click', function (event) {
      if (!window.confirm('Sign out of the parent portal?')) {
        event.preventDefault();
      }
    });
  });
}

function attachValidationHelpers() {
  document.querySelectorAll('[data-confirm-password]').forEach(function (field) {
    field.addEventListener('input', function () {
      const targetId = field.getAttribute('data-confirm-password');
      const original = document.getElementById(targetId);
      if (!original) {
        return;
      }
      if (field.value !== '' && field.value !== original.value) {
        field.setCustomValidity('Passwords do not match');
      } else {
        field.setCustomValidity('');
      }
    });
  });
}
