function supernovaHomeInit() {
    // 1. Rolling Digit Countdown
    const targetDate = new Date('2026-09-04T09:00:00+05:30').getTime();

    // Column IDs mapped to which digit (tens/ones) of which unit
    const colMap = {
        'sn-days-t':  { unit: 'days',    pos: 'tens' },
        'sn-days-o':  { unit: 'days',    pos: 'ones' },
        'sn-hours-t': { unit: 'hours',   pos: 'tens' },
        'sn-hours-o': { unit: 'hours',   pos: 'ones' },
        'sn-mins-t':  { unit: 'minutes', pos: 'tens' },
        'sn-mins-o':  { unit: 'minutes', pos: 'ones' },
        'sn-secs-t':  { unit: 'seconds', pos: 'tens' },
        'sn-secs-o':  { unit: 'seconds', pos: 'ones' },
    };

    // Build digit strips (0–9 repeated so we can loop)
    function buildStrip(colEl) {
        const strip = colEl.querySelector('.sn-digit-strip');
        strip.style.willChange = 'transform';
        // Clear any previously built strip (safe re-init on bfcache)
        strip.innerHTML = '';
        for (let d = 0; d <= 10; d++) {
            const cell = document.createElement('div');
            cell.className = 'sn-digit-cell';
            cell.textContent = d % 10;
            strip.appendChild(cell);
        }
    }

    Object.keys(colMap).forEach(id => {
        const el = document.getElementById(id);
        if (el) buildStrip(el);
    });

    // Cache the cell height dynamically
    let cachedCellHeight = 52;
    function getCellHeight(colEl) {
        if (cachedCellHeight !== 52) return cachedCellHeight;
        const cell = colEl.querySelector('.sn-digit-cell');
        cachedCellHeight = cell ? cell.getBoundingClientRect().height || colEl.getBoundingClientRect().height : 52;
        return cachedCellHeight;
    }
    
    // Recalculate on resize
    window.addEventListener('resize', () => { cachedCellHeight = 52; });

    // Slide the strip to show digit `d`
    function setDigit(colId, d) {
        const col = document.getElementById(colId);
        if (!col) return;
        const strip = col.querySelector('.sn-digit-strip');
        const h = getCellHeight(col);
        strip.style.transform = `translateY(-${d * h}px)`;
    }

    function updateRollingTimer() {
        const now  = Date.now();
        const diff = Math.max(0, targetDate - now);

        const totalSecs = Math.floor(diff / 1000);
        const days    = Math.floor(totalSecs / 86400);
        const hours   = Math.floor((totalSecs % 86400) / 3600);
        const minutes = Math.floor((totalSecs % 3600) / 60);
        const seconds = totalSecs % 60;

        const pad = (n, w=2) => String(n).padStart(w, '0');

        const dayStr  = pad(Math.min(days, 99));
        const hrStr   = pad(hours);
        const minStr  = pad(minutes);
        const secStr  = pad(seconds);

        setDigit('sn-days-t',  parseInt(dayStr[0]));
        setDigit('sn-days-o',  parseInt(dayStr[1]));
        setDigit('sn-hours-t', parseInt(hrStr[0]));
        setDigit('sn-hours-o', parseInt(hrStr[1]));
        setDigit('sn-mins-t',  parseInt(minStr[0]));
        setDigit('sn-mins-o',  parseInt(minStr[1]));
        setDigit('sn-secs-t',  parseInt(secStr[0]));
        setDigit('sn-secs-o',  parseInt(secStr[1]));
    }

    // Init without transition, then enable transition for live updates
    Object.keys(colMap).forEach(id => {
        const col = document.getElementById(id);
        if (col) col.querySelector('.sn-digit-strip').style.transition = 'none';
    });
    updateRollingTimer();
    setTimeout(() => {
        Object.keys(colMap).forEach(id => {
            const col = document.getElementById(id);
            if (col) col.querySelector('.sn-digit-strip').style.transition = '';
        });
        setInterval(updateRollingTimer, 1000);
    }, 100);

    // 2. Events Filtering
    const eventBtns = document.querySelectorAll('.event-filter-btn');
    const eventCards = document.querySelectorAll('.event-card');

    eventBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            eventBtns.forEach(b => {
                b.classList.remove('bg-gradient-to-r', 'from-cyan-500', 'to-purple-600', 'text-slate-950', 'font-black', 'shadow-glow-cyan');
                b.classList.add('glass-panel', 'text-slate-400', 'hover:text-white', 'hover:border-cyan-500/40');
            });
            btn.classList.remove('glass-panel', 'text-slate-400', 'hover:text-white', 'hover:border-cyan-500/40');
            btn.classList.add('bg-gradient-to-r', 'from-cyan-500', 'to-purple-600', 'text-slate-950', 'font-black', 'shadow-glow-cyan');

            const selectedTab = btn.getAttribute('data-tab');

            eventCards.forEach(card => {
                if (selectedTab === 'ALL' || card.getAttribute('data-category') === selectedTab) {
                    card.style.display = 'flex';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    });

    // 3. Schedule Tabs
    const scheduleBtns = document.querySelectorAll('.schedule-tab-btn');
    const scheduleLists = document.querySelectorAll('.schedule-list');

    scheduleBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const currentBtn = e.currentTarget;
            const targetDay = currentBtn.getAttribute('data-day');

            scheduleBtns.forEach(b => {
                // Remove active classes
                b.classList.remove('bg-gradient-to-r', 'from-cyan-500', 'to-purple-600', 'text-slate-950', 'shadow-glow-cyan');
                // Add inactive classes
                b.classList.add('glass-panel', 'bg-slate-900/30', 'border', 'border-white/20', 'text-slate-200');
            });
            
            // Remove inactive classes from clicked button
            currentBtn.classList.remove('glass-panel', 'bg-slate-900/30', 'border', 'border-white/20', 'text-slate-200');
            // Add active classes to clicked button
            currentBtn.classList.add('bg-gradient-to-r', 'from-cyan-500', 'to-purple-600', 'text-slate-950', 'shadow-glow-cyan');

            scheduleLists.forEach(list => {
                if (list.id === 'schedule-' + targetDay) {
                    list.classList.remove('hidden');
                } else {
                    list.classList.add('hidden');
                }
            });
        });
    });

    // 4. FAQ Accordion
    const faqItems = document.querySelectorAll('.faq-item');

    // Open the first one by default
    if (faqItems.length > 0) {
        faqItems[0].classList.add('border-cyan-400/80', 'shadow-glow-cyan');
        faqItems[0].querySelector('.faq-content').classList.remove('hidden');
        faqItems[0].querySelector('.faq-icon').classList.add('rotate-180');
    }

    faqItems.forEach(item => {
        const btn = item.querySelector('.faq-btn');
        const content = item.querySelector('.faq-content');
        const icon = item.querySelector('.faq-icon');

        btn.addEventListener('click', () => {
            const isOpen = !content.classList.contains('hidden');

            // Close all
            faqItems.forEach(i => {
                i.classList.remove('border-cyan-400/80', 'shadow-glow-cyan');
                i.querySelector('.faq-content').classList.add('hidden');
                i.querySelector('.faq-icon').classList.remove('rotate-180');
            });

            // If it wasn't open, open it
            if (!isOpen) {
                item.classList.add('border-cyan-400/80', 'shadow-glow-cyan');
                content.classList.remove('hidden');
                icon.classList.add('rotate-180');
            }
        });
    });

    // 5. Gallery Coverflow Carousel (shortestOffset transition)
    const galleryWrapper = document.getElementById('gallery-carousel');
    if (galleryWrapper) {
        const slides = Array.from(document.querySelectorAll('.gallery-slide'));
        const dotsContainer = document.getElementById('gallery-dots');
        const prevBtn = document.getElementById('gallery-prev');
        const nextBtn = document.getElementById('gallery-next');
        const total = slides.length;
        let current = 0;
        let autoTimer = null;

        // Clear and rebuild dot indicators (handles re-init safely)
        dotsContainer.innerHTML = '';
        slides.forEach((_, i) => {
            const dot = document.createElement('button');
            dot.className = 'gallery-dot' + (i === 0 ? ' active' : '');
            dot.setAttribute('aria-label', 'Go to slide ' + (i + 1));
            dot.addEventListener('click', () => goTo(i));
            dotsContainer.appendChild(dot);
        });

        // Shortest path offset — picks the closest direction around the loop
        function shortestOffset(index) {
            let diff = (index - current + total) % total;
            if (diff > total / 2) diff -= total;
            return diff;
        }

        // Render — assigns pos-{offset} class to each slide
        function render() {
            slides.forEach((card, i) => {
                const offset = shortestOffset(i);
                card.className = 'gallery-slide'; // reset all state classes
                card.classList.add(Math.abs(offset) <= 2 ? `pos-${offset}` : 'pos-hidden');
            });
            // Update dots
            const dots = dotsContainer.querySelectorAll('.gallery-dot');
            dots.forEach((d, i) => d.classList.toggle('active', i === current));
        }

        function goTo(index) {
            current = ((index % total) + total) % total;
            render();
            resetAutoplay();
        }

        function next() { goTo(current + 1); }
        function prev() { goTo(current - 1); }

        function resetAutoplay() {
            clearInterval(autoTimer);
            autoTimer = setInterval(next, 2800);
        }

        // Arrow controls
        nextBtn.addEventListener('click', next);
        prevBtn.addEventListener('click', prev);

        // Side slides clickable to navigate
        slides.forEach((slide, i) => {
            slide.addEventListener('click', () => {
                if (i !== current) goTo(i);
            });
        });

        // Pause on hover, resume on leave
        galleryWrapper.addEventListener('mouseenter', () => clearInterval(autoTimer));
        galleryWrapper.addEventListener('mouseleave', resetAutoplay);

        // Keyboard arrow support
        document.addEventListener('keydown', e => {
            if (e.key === 'ArrowLeft')  prev();
            if (e.key === 'ArrowRight') next();
        });

        // Touch swipe support
        let touchStartX = 0;
        galleryWrapper.addEventListener('touchstart', e => {
            touchStartX = e.changedTouches[0].clientX;
        }, { passive: true });
        galleryWrapper.addEventListener('touchend', e => {
            const dx = e.changedTouches[0].clientX - touchStartX;
            if (Math.abs(dx) > 40) dx < 0 ? next() : prev();
        });

        // Init
        render();
        resetAutoplay();
    }
}

/**
 * Force CSS @keyframes animations to replay on the hero section.
 * Used for bfcache restores (back/forward navigation) where the page is
 * served from memory and CSS animations don't auto-restart.
 */
function replayHeroAnimations() {
    const heroEls = [
        document.querySelector('.sn-hero-badge'),
        document.querySelector('#supernova-hero-heading .supernova-chrome-title'),
        document.querySelector('#supernova-hero-heading .supernova-spark-outline'),
        document.getElementById('sn-hero-tagline'),
        ...document.querySelectorAll('.sn-hero-stat'),
    ].filter(Boolean);

    heroEls.forEach(el => {
        // Remove animation, force a reflow, then re-add it
        el.style.animation = 'none';
        // void el.offsetHeight triggers a reflow synchronously
        void el.offsetHeight;
        el.style.animation = '';
    });
}

// ── Expose globally so soft-nav.js can re-run after a content swap ──
window.supernovaHomeInit = supernovaHomeInit;

// ── Run on first full page load ──
document.addEventListener('DOMContentLoaded', supernovaHomeInit);

// ── Re-run when page is restored from browser back/forward cache (bfcache) ──
// When navigating back, DOMContentLoaded does NOT fire — only pageshow fires.
// e.persisted = true means the browser served the page from bfcache (memory).
window.addEventListener('pageshow', (e) => {
    if (e.persisted) {
        supernovaHomeInit();
        replayHeroAnimations();
    }
});
