/**
 * RSL Badge Component
 *
 * Interactive badge system with dismissible badges, counter badges,
 * and dynamic updates. Designed for JSON API V2 compatibility.
 *
 * @fileoverview Interactive badge component with dismiss, counter, and toggle features
 * @version 1.0.0
 * @license MIT
 *
 * Key Features:
 * - Dismissible badges with smooth animation
 * - Counter badges with increment/decrement/set methods
 * - Toggle badges for on/off states
 * - Keyboard accessible (Enter/Space to dismiss)
 * - Event callbacks for badge interactions
 * - JSON API V2 compatible (init/create pattern)
 *
 * Usage:
 * // Dismissible badge:
 * <span class="rsl-badge rsl-badge-primary rsl-badge-dismissible" data-rsl-badge>
 *     New Feature
 *     <button class="rsl-badge-dismiss" aria-label="Dismiss">&times;</button>
 * </span>
 *
 * // Counter badge:
 * <span class="rsl-badge rsl-badge-danger rsl-badge-counter" data-rsl-badge data-counter="5">5</span>
 *
 * Public API:
 * - RSL.Badge.init() - Initialize all badges on the page
 * - RSL.Badge.create(element) - Initialize a specific badge
 * - RSL.Badge.dismiss(element) - Programmatically dismiss a badge
 * - RSL.Badge.setCounter(element, value) - Set counter value
 * - RSL.Badge.incrementCounter(element, amount) - Increment counter
 * - RSL.Badge.decrementCounter(element, amount) - Decrement counter
 */

(function() {
    'use strict';

    // Initialize RSL namespace
    window.RSL = window.RSL || {};

    // Track initialized badges to prevent double-initialization
    const initializedBadges = new WeakSet();

    /**
     * RSL Badge Component
     * Public API for badge management
     */
    window.RSL.Badge = {

        /**
         * Initialize all badges on the page
         * Scans for [data-rsl-badge] elements and initializes them
         * Safe to call multiple times - prevents double-initialization
         */
        init: function() {
            const badges = document.querySelectorAll('[data-rsl-badge]');
            badges.forEach(badge => {
                if (!initializedBadges.has(badge)) {
                    this.create(badge);
                }
            });
        },

        /**
         * Initialize a specific badge element
         * @param {HTMLElement} element - The badge element to initialize
         * @returns {Object} Badge instance with control methods
         */
        create: function(element) {
            if (!element || initializedBadges.has(element)) {
                return null;
            }

            const instance = initializeBadge(element);
            initializedBadges.add(element);
            return instance;
        },

        /**
         * Programmatically dismiss a badge
         * @param {HTMLElement} element - The badge element to dismiss
         * @param {boolean} animate - Whether to animate the dismissal (default: true)
         */
        dismiss: function(element, animate = true) {
            if (!element) return;

            if (animate) {
                element.style.transition = 'opacity 0.2s ease, transform 0.2s ease';
                element.style.opacity = '0';
                element.style.transform = 'scale(0.8)';

                setTimeout(() => {
                    removeBadge(element);
                }, 200);
            } else {
                removeBadge(element);
            }
        },

        /**
         * Set counter badge value
         * @param {HTMLElement} element - The counter badge element
         * @param {number} value - The new counter value
         * @param {number} max - Optional maximum before showing "max+" (default: 99)
         */
        setCounter: function(element, value, max = 99) {
            if (!element) return;

            const numValue = parseInt(value, 10) || 0;
            element.setAttribute('data-counter', numValue);

            if (numValue > max) {
                // Don't include '+' in text - CSS ::after handles it via .rsl-badge-counter-max
                element.textContent = max;
                element.classList.add('rsl-badge-counter-max');
            } else {
                element.textContent = numValue;
                element.classList.remove('rsl-badge-counter-max');
            }

            // Hide if zero and has hide-zero attribute
            if (numValue === 0 && element.hasAttribute('data-hide-zero')) {
                element.style.display = 'none';
            } else {
                element.style.display = '';
            }

            // Trigger custom event
            element.dispatchEvent(new CustomEvent('rsl-badge-counter-change', {
                bubbles: true,
                detail: { value: numValue, max: max }
            }));
        },

        /**
         * Increment counter badge
         * @param {HTMLElement} element - The counter badge element
         * @param {number} amount - Amount to increment (default: 1)
         * @param {number} max - Optional maximum display value
         */
        incrementCounter: function(element, amount = 1, max = 99) {
            if (!element) return;

            const current = parseInt(element.getAttribute('data-counter') || 0, 10);
            this.setCounter(element, current + amount, max);
        },

        /**
         * Decrement counter badge
         * @param {HTMLElement} element - The counter badge element
         * @param {number} amount - Amount to decrement (default: 1)
         * @param {number} min - Optional minimum value (default: 0)
         * @param {number} max - Optional maximum display value
         */
        decrementCounter: function(element, amount = 1, min = 0, max = 99) {
            if (!element) return;

            const current = parseInt(element.getAttribute('data-counter') || 0, 10);
            const newValue = Math.max(min, current - amount);
            this.setCounter(element, newValue, max);
        },

        /**
         * Toggle badge visibility
         * @param {HTMLElement} element - The badge element
         * @param {boolean} visible - Optional explicit visibility state
         */
        toggle: function(element, visible) {
            if (!element) return;

            const isVisible = visible !== undefined ? visible : element.style.display === 'none';

            if (isVisible) {
                element.style.display = '';
                element.style.opacity = '0';
                element.style.transform = 'scale(0.8)';

                // Force reflow
                element.offsetHeight;

                element.style.transition = 'opacity 0.2s ease, transform 0.2s ease';
                element.style.opacity = '1';
                element.style.transform = 'scale(1)';
            } else {
                element.style.transition = 'opacity 0.2s ease, transform 0.2s ease';
                element.style.opacity = '0';
                element.style.transform = 'scale(0.8)';

                setTimeout(() => {
                    element.style.display = 'none';
                }, 200);
            }
        }
    };

    /**
     * Initialize a single badge
     * @private
     * @param {HTMLElement} badge - The badge element
     * @returns {Object} Badge instance
     */
    function initializeBadge(badge) {
        const instance = {
            element: badge,
            isDismissible: badge.classList.contains('rsl-badge-dismissible'),
            isCounter: badge.classList.contains('rsl-badge-counter')
        };

        // Set up dismissible badge
        if (instance.isDismissible) {
            setupDismissible(badge);
        }

        // Set up counter badge
        if (instance.isCounter) {
            setupCounter(badge);
        }

        // Set up clickable badge
        if (badge.hasAttribute('data-clickable') || badge.classList.contains('rsl-badge-clickable')) {
            setupClickable(badge);
        }

        return instance;
    }

    /**
     * Set up dismissible badge functionality
     * @private
     * @param {HTMLElement} badge - The badge element
     */
    function setupDismissible(badge) {
        const dismissBtn = badge.querySelector('.rsl-badge-dismiss');

        if (dismissBtn) {
            // Click handler
            dismissBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                RSL.Badge.dismiss(badge);
            });

            // Keyboard handler
            dismissBtn.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();
                    RSL.Badge.dismiss(badge);
                }
            });
        }

        // Also allow dismissing with Escape key when badge is focused
        badge.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                RSL.Badge.dismiss(badge);
            }
        });
    }

    /**
     * Set up counter badge functionality
     * @private
     * @param {HTMLElement} badge - The badge element
     */
    function setupCounter(badge) {
        // Initialize from data attribute if present
        const initialValue = badge.getAttribute('data-counter');
        if (initialValue !== null) {
            const max = parseInt(badge.getAttribute('data-counter-max') || 99, 10);
            RSL.Badge.setCounter(badge, parseInt(initialValue, 10), max);
        }
    }

    /**
     * Set up clickable badge functionality
     * @private
     * @param {HTMLElement} badge - The badge element
     */
    function setupClickable(badge) {
        // Make focusable if not already
        if (!badge.hasAttribute('tabindex') && badge.tagName !== 'A' && badge.tagName !== 'BUTTON') {
            badge.setAttribute('tabindex', '0');
        }

        // Add role if needed
        if (!badge.hasAttribute('role') && badge.tagName !== 'A' && badge.tagName !== 'BUTTON') {
            badge.setAttribute('role', 'button');
        }

        // Keyboard activation
        badge.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                badge.click();
            }
        });
    }

    /**
     * Remove badge from DOM and trigger event
     * @private
     * @param {HTMLElement} badge - The badge element to remove
     */
    function removeBadge(badge) {
        // Trigger custom event before removal
        const event = new CustomEvent('rsl-badge-dismiss', {
            bubbles: true,
            cancelable: true,
            detail: { badge: badge }
        });

        const shouldRemove = badge.dispatchEvent(event);

        if (shouldRemove && badge.parentNode) {
            badge.parentNode.removeChild(badge);
        }
    }

    /**
     * Auto-initialize on DOM ready
     */
    document.addEventListener('DOMContentLoaded', function() {
        RSL.Badge.init();
    });

})();
