(function() {
    // Mobile navigation toggle + backdrop
    const navbar = document.querySelector('.navbar');
    const toggle = document.querySelector('.nav-toggle');
    const backdrop = document.querySelector('.nav-backdrop');

    function closeNav() {
        if (!navbar) return;
        navbar.classList.remove('open');
        toggle && toggle.setAttribute('aria-expanded', 'false');
        document.querySelectorAll('.nav-links .dropdown.open').forEach(li => li.classList.remove('open'));
        document.body.style.overflow = ''; // re-enable scroll
    }

    if (navbar && toggle) {
        toggle.addEventListener('click', () => {
            const isOpen = navbar.classList.toggle('open');
            toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
            document.body.style.overflow = isOpen ? 'hidden' : '';
        });
    }

    // Tap backdrop to close
    if (backdrop) {
        backdrop.addEventListener('click', closeNav);
    }

    // Dropdowns: tap-to-open on mobile
    document.querySelectorAll('.nav-links .dropdown > a').forEach(anchor => {
        anchor.addEventListener('click', (e) => {
            if (window.innerWidth <= 768) {
                e.preventDefault();
                anchor.parentElement.classList.toggle('open');
            }
        });
    });

    function initCarousel(id) {
        const wrap = document.getElementById(id);
        if (!wrap) return;
        const track = wrap.querySelector('.carousel-track');
        const items = wrap.querySelectorAll('.product-card');
        const left = wrap.querySelector('.nav-btn.left');
        const right = wrap.querySelector('.nav-btn.right');
    
        let index = 0;
        function itemWidth() { return items[0] ? items[0].offsetWidth : 240; }
        function perView() { return Math.max(1, Math.floor(wrap.clientWidth / itemWidth())); }
        function update() {
            const x = -index * itemWidth();
            track.style.transform = `translateX(${x}px)`;
        }
        function next() {
            const pv = perView();
            index = (index + 1) % Math.max(1, items.length - pv + 1);
            update();
        }
        function prev() {
            index = Math.max(0, index - 1);
            update();
        }
    
        let timer = setInterval(next, 4000);
        wrap.addEventListener('mouseenter', () => clearInterval(timer));
        wrap.addEventListener('mouseleave', () => timer = setInterval(next, 4000));
        left && left.addEventListener('click', prev);
        right && right.addEventListener('click', next);
        window.addEventListener('resize', () => {
            index = Math.min(index, Math.max(0, items.length - perView()));
            update();
        });
        update();
    }

    ['featuredCarousel', 'seasonalCarousel', 'bestSellerCarousel'].forEach(initCarousel);

    // Animated Background (premium gradient blobs)
    const AnimatedBackground = (() => {
        const state = {
            canvas: null,
            ctx: null,
            width: 0,
            height: 0,
            dpr: Math.max(1, Math.min(window.devicePixelRatio || 1, 2)),
            blobs: [],
            rafId: null,
            running: false
        };

        const COLORS = ['#6E8EFB', '#A777E3', '#F9A8D4']; // premium gradient palette

        function init() {
            if (state.running) return;
            state.canvas = document.createElement('canvas');
            state.canvas.className = 'canvas-bg';
            state.ctx = state.canvas.getContext('2d');
            document.body.appendChild(state.canvas);
            resize();
            createBlobs(8);
            state.running = true;
            loop();
            window.addEventListener('resize', resize);
            window.addEventListener('visibilitychange', onVisibility);
        }

        function stop() {
            state.running = false;
            if (state.rafId) cancelAnimationFrame(state.rafId);
            window.removeEventListener('resize', resize);
            window.removeEventListener('visibilitychange', onVisibility);
            if (state.canvas && state.canvas.parentNode) {
                state.canvas.parentNode.removeChild(state.canvas);
            }
            state.canvas = null;
            state.ctx = null;
            state.blobs = [];
        }

        function onVisibility() {
            if (document.hidden) {
                if (state.rafId) cancelAnimationFrame(state.rafId);
            } else if (state.running) {
                loop();
            }
        }

        function resize() {
            if (!state.canvas) return;
            state.width = window.innerWidth;
            state.height = window.innerHeight;
            state.canvas.width = Math.floor(state.width * state.dpr);
            state.canvas.height = Math.floor(state.height * state.dpr);
            state.canvas.style.width = state.width + 'px';
            state.canvas.style.height = state.height + 'px';
            if (state.ctx) {
                state.ctx.setTransform(state.dpr, 0, 0, state.dpr, 0, 0);
            }
        }

        function createBlobs(count) {
            const minR = Math.min(state.width, state.height) * 0.10;
            const maxR = Math.min(state.width, state.height) * 0.25;
            state.blobs = new Array(count).fill(0).map(() => {
                const r = rand(minR, maxR);
                return {
                    x: rand(-r, state.width + r),
                    y: rand(-r, state.height + r),
                    r,
                    vx: rand(-0.15, 0.15),
                    vy: rand(-0.10, 0.10),
                    color: COLORS[Math.floor(Math.random() * COLORS.length)],
                };
            });
        }

        function draw() {
            const ctx = state.ctx;
            if (!ctx) return;
            ctx.clearRect(0, 0, state.width, state.height);
            ctx.globalCompositeOperation = 'lighter';

            for (const b of state.blobs) {
                const grd = ctx.createRadialGradient(b.x, b.y, b.r * 0.15, b.x, b.y, b.r);
                grd.addColorStop(0, hexToRgba(b.color, 0.45));
                grd.addColorStop(1, hexToRgba(b.color, 0.0));

                ctx.fillStyle = grd;
                ctx.beginPath();
                ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2);
                ctx.fill();

                // Move and bounce softly
                b.x += b.vx * 16;
                b.y += b.vy * 16;
                if (b.x < -b.r || b.x > state.width + b.r) b.vx *= -1;
                if (b.y < -b.r || b.y > state.height + b.r) b.vy *= -1;
            }
        }

        function loop() {
            state.rafId = requestAnimationFrame(() => {
                draw();
                if (state.running) loop();
            });
        }

        function rand(min, max) { return Math.random() * (max - min) + min; }
        function hexToRgba(hex, a) {
            const m = hex.replace('#', '');
            const bigint = parseInt(m, 16);
            const r = (bigint >> 16) & 255;
            const g = (bigint >> 8) & 255;
            const b = bigint & 255;
            return `rgba(${r}, ${g}, ${b}, ${a})`;
        }

        return { init, stop };
    })();

    // Respect reduced motion
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
    function handleMotionPref(e) {
        if (e.matches) {
            AnimatedBackground.stop();
        } else {
            AnimatedBackground.init();
        }
    }

    // Scroll-in animations
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize based on motion preference
        handleMotionPref(prefersReducedMotion);
        prefersReducedMotion.addEventListener('change', handleMotionPref);

        // Page animations
        splitText();           // NEW: prepare animated text
        initScrollAnimations();
        initParallax();
    });

    // Parallax effect
    function initParallax() {
        const els = Array.from(document.querySelectorAll('[data-parallax]'));
        if (!els.length) return;
        let ticking = false;

        function update() {
            const scrollY = window.scrollY || window.pageYOffset;
            for (const el of els) {
                const speed = parseFloat(el.getAttribute('data-parallax')) || 0.15;
                el.style.transform = `translate3d(0, ${Math.round(scrollY * speed)}px, 0)`;
            }
            ticking = false;
        }

        function onScroll() {
            if (!ticking) {
                ticking = true;
                requestAnimationFrame(update);
            }
        }

        window.addEventListener('scroll', onScroll, { passive: true });
        update();
    }

    // Scroll-in animations
    function initScrollAnimations() {
        // Observe both [data-animate] and [data-split] elements
        const els = document.querySelectorAll('[data-animate], [data-split]');
        if (!els.length) return;

        const observer = new IntersectionObserver((entries) => {
            for (const entry of entries) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('in');
                    observer.unobserve(entry.target);
                }
            }
        }, { rootMargin: '0px 0px -10% 0px', threshold: 0.12 });

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

    // NEW: split text into characters/words for staggered animations
    function splitText() {
        const targets = document.querySelectorAll('[data-split]');
        if (!targets.length) return;

        targets.forEach(el => {
            if (el.dataset.splitInitialized === '1') return;

            const mode = el.getAttribute('data-split') || 'chars';
            const raw = el.textContent;
            if (!raw || raw.trim().length === 0) return;

            const staggerStep = parseInt(el.getAttribute('data-stagger') || '', 10);
            if (!Number.isNaN(staggerStep)) {
                el.style.setProperty('--stagger-step', `${staggerStep}ms`);
            }

            // Clear and rebuild content
            el.textContent = '';

            if (mode === 'words') {
                const parts = raw.split(/(\s+)/);
                let wIdx = 0;
                parts.forEach(part => {
                    if (/\s+/.test(part)) {
                        el.appendChild(document.createTextNode(part));
                    } else {
                        const span = document.createElement('span');
                        span.className = 'word';
                        span.style.setProperty('--word-index', String(wIdx++));
                        span.textContent = part;
                        el.appendChild(span);
                    }
                });
            } else {
                const chars = Array.from(raw);
                let cIdx = 0;
                chars.forEach(ch => {
                    if (ch === ' ') {
                        el.appendChild(document.createTextNode(' '));
                    } else {
                        const span = document.createElement('span');
                        span.className = 'char';
                        span.style.setProperty('--char-index', String(cIdx++));
                        span.textContent = ch;
                        el.appendChild(span);
                    }
                });
            }

            // Enable stagger timing by default
            el.classList.add('stagger');
            el.dataset.splitInitialized = '1';
        });
    }
})();