/**
 * Profile Menu Block - Frontend JavaScript
 * Handles the dropdown toggle functionality
 */

(function() {
  'use strict';

  function initProfileMenu() {
    const menuButtons = document.querySelectorAll('.wp-block-memberpress-pro-profile-menu__button');

    menuButtons.forEach(function(button) {
      button.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        const buttonGroup = button.closest('.wp-block-memberpress-pro-profile-menu__button-group');
        const dropdown = buttonGroup.querySelector('.wp-block-memberpress-pro-profile-menu__dropdown');

        if (!dropdown) return;

        // Toggle dropdown
        const isExpanded = button.getAttribute('aria-expanded') === 'true';

        // Close all other dropdowns first
        document.querySelectorAll('.wp-block-memberpress-pro-profile-menu__button').forEach(function(otherButton) {
          if (otherButton !== button) {
            otherButton.setAttribute('aria-expanded', 'false');
            const otherDropdown = otherButton.closest('.wp-block-memberpress-pro-profile-menu__button-group').querySelector('.wp-block-memberpress-pro-profile-menu__dropdown');
            if (otherDropdown) {
              otherDropdown.style.display = 'none';
            }
          }
        });

        // Toggle current dropdown
        if (isExpanded) {
          button.setAttribute('aria-expanded', 'false');
          dropdown.style.display = 'none';
        } else {
          button.setAttribute('aria-expanded', 'true');
          dropdown.style.display = 'block';
        }
      });
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
      const isProfileMenu = e.target.closest('.wp-block-memberpress-pro-profile-menu');

      if (!isProfileMenu) {
        document.querySelectorAll('.wp-block-memberpress-pro-profile-menu__button').forEach(function(button) {
          button.setAttribute('aria-expanded', 'false');
        });
        document.querySelectorAll('.wp-block-memberpress-pro-profile-menu__dropdown').forEach(function(dropdown) {
          dropdown.style.display = 'none';
        });
      }
    });

    // Close dropdown on escape key
    document.addEventListener('keydown', function(e) {
      if (e.key === 'Escape') {
        document.querySelectorAll('.wp-block-memberpress-pro-profile-menu__button').forEach(function(button) {
          button.setAttribute('aria-expanded', 'false');
        });
        document.querySelectorAll('.wp-block-memberpress-pro-profile-menu__dropdown').forEach(function(dropdown) {
          dropdown.style.display = 'none';
        });
      }
    });
  }

  // Initialize on DOM ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initProfileMenu);
  } else {
    initProfileMenu();
  }
})();
