/**
 * Insight Dezign Shortcodes — Frontend JS
 * Handles: Tabs, Counter animation, TOC smooth scroll, dismissible Alerts
 */
(function() {
    'use strict';

    // ── Tabs ──
    function initTabs() {
        var tabGroups = document.querySelectorAll('[data-idsc-tabs]');
        for (var i = 0; i < tabGroups.length; i++) {
            setupTabGroup(tabGroups[i]);
        }
    }

    function setupTabGroup(container) {
        var buttons = container.querySelectorAll('.idsc-tabs__btn');
        var panels  = container.querySelectorAll('.idsc-tabs__panel');

        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener('click', (function(idx) {
                return function() {
                    // Deactivate all
                    for (var j = 0; j < buttons.length; j++) {
                        buttons[j].classList.remove('idsc-tabs__btn--active');
                        buttons[j].setAttribute('aria-selected', 'false');
                    }
                    for (var k = 0; k < panels.length; k++) {
                        panels[k].setAttribute('hidden', '');
                    }
                    // Activate clicked
                    buttons[idx].classList.add('idsc-tabs__btn--active');
                    buttons[idx].setAttribute('aria-selected', 'true');
                    if (panels[idx]) {
                        panels[idx].removeAttribute('hidden');
                    }
                };
            })(i));
        }
    }

    // ── Counter Animation ──
    function initCounters() {
        var counters = document.querySelectorAll('[data-idsc-counter]');
        if (counters.length === 0) return;

        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(function(entries) {
                for (var i = 0; i < entries.length; i++) {
                    if (entries[i].isIntersecting) {
                        animateCounter(entries[i].target);
                        observer.unobserve(entries[i].target);
                    }
                }
            }, { threshold: 0.3 });

            for (var i = 0; i < counters.length; i++) {
                observer.observe(counters[i]);
            }
        } else {
            // Fallback: animate all immediately
            for (var j = 0; j < counters.length; j++) {
                animateCounter(counters[j]);
            }
        }
    }

    function animateCounter(el) {
        var target   = parseInt(el.getAttribute('data-target'), 10) || 0;
        var duration = parseInt(el.getAttribute('data-duration'), 10) || 2000;
        var valueEl  = el.querySelector('.idsc-counter__value');
        if (!valueEl) return;

        var startTime = null;

        function step(timestamp) {
            if (!startTime) startTime = timestamp;
            var progress = Math.min((timestamp - startTime) / duration, 1);
            // Ease out
            var eased = 1 - Math.pow(1 - progress, 3);
            var current = Math.round(eased * target);
            valueEl.textContent = current.toLocaleString();
            if (progress < 1) {
                requestAnimationFrame(step);
            }
        }

        requestAnimationFrame(step);
    }

    // ── TOC Smooth Scroll ──
    function initSmoothScroll() {
        var links = document.querySelectorAll('[data-idsc-smooth]');
        for (var i = 0; i < links.length; i++) {
            links[i].addEventListener('click', function(e) {
                var href = this.getAttribute('href');
                if (!href || href.charAt(0) !== '#') return;
                var target = document.getElementById(href.substring(1));
                if (target) {
                    e.preventDefault();
                    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    // Update URL hash without jumping
                    if (history.pushState) {
                        history.pushState(null, null, href);
                    }
                }
            });
        }
    }

    // ── Dismissible Alerts ──
    function initDismissibleAlerts() {
        var closeButtons = document.querySelectorAll('.idsc-alert__close');
        for (var i = 0; i < closeButtons.length; i++) {
            closeButtons[i].addEventListener('click', function() {
                var alert = this.closest('.idsc-alert');
                if (alert) {
                    alert.style.transition = 'opacity 0.3s, max-height 0.3s';
                    alert.style.opacity = '0';
                    alert.style.maxHeight = alert.offsetHeight + 'px';
                    setTimeout(function() {
                        alert.style.maxHeight = '0';
                        alert.style.padding = '0';
                        alert.style.margin = '0';
                        alert.style.overflow = 'hidden';
                    }, 50);
                    setTimeout(function() {
                        if (alert.parentNode) {
                            alert.parentNode.removeChild(alert);
                        }
                    }, 350);
                }
            });
        }
    }

    // ── Init ──
    function init() {
        initTabs();
        initCounters();
        initSmoothScroll();
        initDismissibleAlerts();
    }

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