/**
 * @file
 * Project Status Dropdown functionality.
 */

(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.projectStatusDropdown = {
    attach: function (context, settings) {
      // Make the entire pill clickable instead of just the arrow
      $('.project-status-wrapper .language-icon', context).not('.processed').addClass('processed').on('click', function (e) {
        // Don't prevent default if clicking on a dropdown menu item
        if ($(e.target).closest('.project-status-dropdown-menu').length > 0) {
          return; // Allow normal link behavior for menu items
        }
        
        e.preventDefault();
        e.stopPropagation();
        
        var $pill = $(this);
        var $wrapper = $pill.closest('.project-status-wrapper');
        var $menu = $wrapper.find('.project-status-dropdown-menu');
        var isVisible = $menu.hasClass('show');
        
        // Hide all other dropdowns and remove open class
        $('.project-status-dropdown-menu').removeClass('show');
        $('.project-status-wrapper').removeClass('open');
        
        // Toggle this dropdown
        if (isVisible) {
          $menu.removeClass('show');
          $wrapper.removeClass('open');
        } else {
          $menu.addClass('show');
          $wrapper.addClass('open');
        }
      });
      
      // Close dropdown when clicking outside (only attach once)
      if (!$(document).data('project-status-dropdown-attached')) {
        $(document).data('project-status-dropdown-attached', true);
        
        $(document).on('click.project-status-dropdown', function (e) {
          if (!$(e.target).closest('.project-status-wrapper').length) {
            $('.project-status-dropdown-menu').removeClass('show');
            $('.project-status-wrapper').removeClass('open');
          }
        });
        
        // Close dropdown when pressing escape
        $(document).on('keydown.project-status-dropdown', function (e) {
          if (e.key === 'Escape') {
            $('.project-status-dropdown-menu').removeClass('show');
            $('.project-status-wrapper').removeClass('open');
          }
        });
        
        // Close dropdown when clicking on menu items
        $(document).on('click.project-status-dropdown', '.project-status-dropdown-menu a', function (e) {
          // Allow the link to work normally, but close the dropdown
          $('.project-status-dropdown-menu').removeClass('show');
          $('.project-status-wrapper').removeClass('open');
        });
      }
    },
    
    detach: function (context, settings, trigger) {
      if (trigger === 'unload') {
        $(document).removeData('project-status-dropdown-attached');
        $(document).off('click.project-status-dropdown keydown.project-status-dropdown');
      }
    }
  };

})(jQuery, Drupal);