/**
 * WPUF User Bio Block - Frontend functionality
 * Handles read more/show less toggle functionality
 *
 * @since 4.2.0
 */

document.addEventListener('DOMContentLoaded', function() {
    // Find all read more toggle buttons
    const toggleButtons = document.querySelectorAll('.wpuf-read-more-toggle');

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

            const targetId = this.getAttribute('data-target');
            const readMoreText = this.getAttribute('data-read-more-text') || 'Read More';
            const showLessText = this.getAttribute('data-show-less-text') || 'Show Less';

            if (!targetId) {
                return;
            }

            const container = document.getElementById(targetId);
            if (!container) {
                return;
            }

            const truncatedElement = container.querySelector('.wpuf-bio-truncated');
            const fullElement = container.querySelector('.wpuf-bio-full');

            if (!truncatedElement || !fullElement) {
                return;
            }

            // Check current state
            const isExpanded = fullElement.style.display !== 'none';

            if (isExpanded) {
                // Currently expanded, collapse it
                fullElement.style.display = 'none';
                truncatedElement.style.display = 'block';
                this.textContent = readMoreText;
                this.setAttribute('aria-expanded', 'false');
            } else {
                // Currently collapsed, expand it
                truncatedElement.style.display = 'none';
                fullElement.style.display = 'block';
                this.textContent = showLessText;
                this.setAttribute('aria-expanded', 'true');
            }
        });

        // Initialize ARIA attributes
        button.setAttribute('aria-expanded', 'false');
        button.setAttribute('type', 'button');
    });
});
