// ═══════════════════════════════════════════════════════
// Landing Page — Scroll Animations & Counter
// ═══════════════════════════════════════════════════════

/**
 * Initialize Intersection Observer for fade-in-up animations.
 * Elements with class "fade-in-up" become visible when scrolled into view.
 */
window.initScrollAnimations = () => {
    const elements = document.querySelectorAll('.fade-in-up');
    if (!elements.length) return;

    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                // stagger: each child fades in 80ms after the previous
                const delay = entry.target.dataset.delay || (index * 80);
                setTimeout(() => {
                    entry.target.classList.add('visible');
                }, delay);
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });

    elements.forEach(el => observer.observe(el));
};

/**
 * Animate a numeric counter from 0 to `target`.
 * Triggered once by Intersection Observer so it only fires when visible.
 * @param {string} elementId   - DOM id of the element to update
 * @param {number} target      - final number
 * @param {number} duration    - animation length in ms (default 2000)
 * @param {string} suffix      - optional suffix like "+" or "%"
 */
window.animateCounter = (elementId, target, duration, suffix) => {
    const el = document.getElementById(elementId);
    if (!el) return;

    duration = duration || 2000;
    suffix = suffix || '';

    // Use IntersectionObserver so animation starts only when visible
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                observer.unobserve(entry.target);
                runCounter(el, target, duration, suffix);
            }
        });
    }, { threshold: 0.3 });

    observer.observe(el);
};

function runCounter(el, target, duration, suffix) {
    const start = performance.now();
    const isFloat = target % 1 !== 0;

    function tick(now) {
        const elapsed = now - start;
        const progress = Math.min(elapsed / duration, 1);
        // ease-out cubic
        const eased = 1 - Math.pow(1 - progress, 3);
        const current = eased * target;

        if (isFloat) {
            el.textContent = current.toFixed(1).replace(/\B(?=(\d{3})+(?!\d))/g, '٬') + suffix;
        } else {
            el.textContent = Math.floor(current).toLocaleString('fa-IR') + suffix;
        }

        if (progress < 1) {
            requestAnimationFrame(tick);
        }
    }

    requestAnimationFrame(tick);
}

/**
 * Dispose scroll observers (called from Blazor Dispose).
 */
window.disposeScrollAnimations = () => {
    // Nothing to explicitly clean; observers auto-GC when targets are removed.
};
