(function () {
  function initNav() {
    if (window.CrankAuth && typeof window.CrankAuth.renderShellIdentity === 'function') {
      window.CrankAuth.renderShellIdentity();
    }

    var dropdown = document.querySelector('.user-dropdown');
    var avatar = document.querySelector('.nav-avatar');
    var hamburger = document.querySelector('.nav-hamburger');
    var mobileNav = document.querySelector('.mobile-nav');

    if (dropdown) {
      dropdown.style.display = 'none';
    }
    if (mobileNav) {
      mobileNav.style.display = 'none';
    }

    if (avatar && dropdown) {
      avatar.addEventListener('click', function (event) {
        event.stopPropagation();
        dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
      });
    }

    if (hamburger && mobileNav) {
      hamburger.addEventListener('click', function (event) {
        event.stopPropagation();
        mobileNav.style.display = mobileNav.style.display === 'none' ? 'block' : 'none';
        hamburger.classList.toggle('open', mobileNav.style.display !== 'none');
      });
    }

    document.addEventListener('click', function (event) {
      if (dropdown && !event.target.closest('.user-menu')) {
        dropdown.style.display = 'none';
      }
      if (mobileNav && !event.target.closest('.navbar') && !event.target.closest('.mobile-nav')) {
        mobileNav.style.display = 'none';
        if (hamburger) {
          hamburger.classList.remove('open');
        }
      }
    });

    document.querySelectorAll('[data-action="logout"]').forEach(function (button) {
      button.addEventListener('click', function () {
        window.CrankAuth.logout();
      });
    });

    document.querySelectorAll('[data-action="profile"]').forEach(function (button) {
      button.addEventListener('click', function () {
        if (dropdown) {
          dropdown.style.display = 'none';
        }
        window.location.href = ((window.CrankRoutes && window.CrankRoutes.settings) || '/settings') + '#profile';
      });
    });

    document.querySelectorAll('[data-action="settings-link"]').forEach(function (button) {
      button.addEventListener('click', function () {
        if (dropdown) {
          dropdown.style.display = 'none';
        }
        window.location.href = (window.CrankRoutes && window.CrankRoutes.settings) || '/settings';
      });
    });
  }

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