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

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

  Drupal.behaviors.targetStatusDropdown = {
    attach: function (context, settings) {
      // Make the entire pill clickable instead of just the arrow
      $('.target-status-pill-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('.target-status-dropdown-menu').length > 0) {
          return; // Allow normal link behavior for menu items
        }
        
        e.preventDefault();
        e.stopPropagation();
        
        var $pill = $(this);
        var $wrapper = $pill.closest('.target-status-pill-wrapper');
        var $menu = $wrapper.find('.target-status-dropdown-menu');
        var isVisible = $menu.hasClass('show');
        
        // Hide all other dropdowns and remove open class
        $('.target-status-dropdown-menu').removeClass('show');
        $('.target-status-pill-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('target-status-dropdown-attached')) {
        $(document).data('target-status-dropdown-attached', true);
        
        $(document).on('click.target-status-dropdown', function (e) {
          if (!$(e.target).closest('.target-status-pill-wrapper').length) {
            $('.target-status-dropdown-menu').removeClass('show');
            $('.target-status-pill-wrapper').removeClass('open');
          }
        });
        
        // Close dropdown when pressing escape
        $(document).on('keydown.target-status-dropdown', function (e) {
          if (e.key === 'Escape') {
            $('.target-status-dropdown-menu').removeClass('show');
            $('.target-status-pill-wrapper').removeClass('open');
          }
        });
        
        // Close dropdown when clicking on menu items
        $(document).on('click.target-status-dropdown', '.target-status-dropdown-menu a', function (e) {
          // Allow the link to work normally, but close the dropdown
          $('.target-status-dropdown-menu').removeClass('show');
          $('.target-status-pill-wrapper').removeClass('open');
        });
      }
    }
  };

})(jQuery, Drupal);