/**
 * Price Badge — Frontend interaction.
 *
 * Handles click-outside-to-close behaviour for non-always-expanded badges
 * and prevents toggle on always-expanded badges.
 */

function initPriceBadges(): void {
  const badges = document.querySelectorAll<HTMLElement>('.crtoday-price-badge');

  badges.forEach((badge) => {
    const details = badge.querySelector<HTMLDetailsElement>('.crtoday-price-badge__details');
    if (!details) return;

    const isAlwaysExpanded = badge.classList.contains('crtoday-price-badge--expanded');

    /* Always-expanded: keep open, prevent toggle */
    if (isAlwaysExpanded) {
      details.open = true;
      details.addEventListener('toggle', () => {
        if (!details.open) {
          details.open = true;
        }
      });
      return;
    }

    /* Collapsible: close when clicking outside */
    document.addEventListener('click', (event) => {
      if (!details.open) return;
      if (badge.contains(event.target as Node)) return;
      details.open = false;
    });
  });
}

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