(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.hidden = true;
    }
    if (mobileNav) {
      mobileNav.hidden = true;
    }

    if (avatar && dropdown) {
      avatar.addEventListener('click', function (event) {
        event.stopPropagation();
        dropdown.hidden = !dropdown.hidden;
      });
    }

    if (hamburger && mobileNav) {
      hamburger.addEventListener('click', function (event) {
        event.stopPropagation();
        mobileNav.hidden = !mobileNav.hidden;
        hamburger.classList.toggle('open', !mobileNav.hidden);
      });
    }

    document.addEventListener('click', function (event) {
      if (dropdown && !event.target.closest('.user-menu')) {
        dropdown.hidden = true;
      }
      if (mobileNav && !event.target.closest('.navbar') && !event.target.closest('.mobile-nav')) {
        mobileNav.hidden = true;
        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.hidden = true;
        }
        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.hidden = true;
        }
        window.location.href = (window.CrankRoutes && window.CrankRoutes.settings) || '/settings';
      });
    });
  }

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