(function () {

    /* ---- RHYTHMIC MONTAGE SPLASH LOGIC ---- */
    function initMontageSplash() {
        var splash = document.getElementById('montageSplash');
        var container = document.getElementById('montageImages');
        if (!splash || !container) return;

        document.body.style.overflow = 'hidden';
        window.scrollTo(0, 0);

        var images = [
            'https://images.unsplash.com/photo-1519741497674-611481863552?w=1000',
            'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?w=1000',
            'https://images.unsplash.com/photo-1529636798458-92182e662485?w=1000',
            'https://images.unsplash.com/photo-1554080353-a576cf803bda?w=1000',
            'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=1000',
            'https://images.unsplash.com/photo-1510076857177-7408093cc788?w=1000'
        ];

        // Inject images
        images.forEach((src) => {
            var img = document.createElement('img');
            img.src = src;
            img.className = 'montage-img';
            container.appendChild(img);
        });

        var montageItems = document.querySelectorAll('.montage-img');
        var current = 0;

        // Rapid-fire sequence (200ms cuts)
        var shuffleInterval = setInterval(() => {
            montageItems.forEach(img => img.classList.remove('active'));
            montageItems[current].classList.add('active');
            current = (current + 1) % montageItems.length;
        }, 200);

        // Exit sequence after 3 seconds
        setTimeout(() => {
            clearInterval(shuffleInterval);
            splash.classList.add('outro');

            setTimeout(() => {
                document.body.style.overflow = '';
                setTimeout(() => splash.style.display = 'none', 1000);
            }, 200);

        }, 3000);
    }
    initMontageSplash();

    /* ---- CONSTANTS ---- */
    var NAVBAR_H = 90;
    var NAVBAR_SCROLLED_H = 72;
    var VF_PADDING = 30;

    /* ---- CURSOR REMOVED ---- */

    /* ---- VIEWFINDER ELEMENTS ---- */
    var vfFrame = document.getElementById('vfFrame');
    var vfHist = document.getElementById('vfHist');
    var vfCenterTarget = document.getElementById('vfCenterTarget');
    var corners = document.querySelectorAll('.vf-corner');

    function checkFocus(x, y) {
        if (!vfFrame) return;
        var d = Math.hypot(x - window.innerWidth / 2, y - window.innerHeight / 2);
        if (d < 160) vfFrame.classList.add('focused');
        else vfFrame.classList.remove('focused');
    }

    /* Histogram (Reactive to Scroll) */
    if (vfHist) {
        for (var i = 0; i < 28; i++) {
            var hb = document.createElement('div');
            hb.className = 'vf-hbar';
            hb.style.height = (Math.random() * 80 + 20) + '%';
            vfHist.appendChild(hb);
        }
        window.addEventListener('scroll', function() {
            var bars = vfHist.querySelectorAll('.vf-hbar');
            bars.forEach(function(b) {
                b.style.height = (Math.random() * 60 + 20) + '%';
            });
        });
    }

    /* Exposure Meter */
    var vfExp = document.getElementById('vfExp');
    if (vfExp) {
        for (var i = 0; i < 12; i++) {
            var eb = document.createElement('div');
            eb.className = 'vf-ebar';
            vfExp.appendChild(eb);
        }
        var edot = document.createElement('div');
        edot.className = 'vf-edot';
        vfExp.insertBefore(edot, vfExp.children[6]);
        setInterval(function () {
            var bars = vfExp.querySelectorAll('.vf-ebar');
            var al = Math.floor(Math.random() * 4) + 5;
            bars.forEach(function (b, i) {
                b.classList.remove('on', 'hot');
                if (i < al) b.classList.add('on');
                if (i > 9) b.classList.add('hot');
            });
        }, 1600);
    }

    /* Level bubble (hidden via CSS) */
    var vfBub = document.getElementById('vfBub');
    function updateLevel(x) {
        if (vfBub) vfBub.style.left = 'calc(50% + ' + ((x / window.innerWidth - .5) * 36) + 'px)';
    }

    /* Camera Info */
    function randOf(a) { return a[Math.floor(Math.random() * a.length)]; }
    function updateCam() {
        var ie = document.getElementById('vISO');
        var ae = document.getElementById('vAP');
        var se = document.getElementById('vSH');
        var fe = document.getElementById('vFR');
        if (ie) ie.textContent = randOf([100, 200, 400, 800, 1600]);
        if (ae) ae.textContent = randOf(['1.4', '2.0', '2.8', '4.0', '5.6']);
        if (se) se.textContent = randOf([60, 125, 250, 500, 1000]);
        if (fe) fe.textContent = (parseInt(fe.textContent, 10) + 1).toString().padStart(4, '0');
    }
    updateCam();
    setInterval(updateCam, 5200);

    /* ---- HERO SLIDER LOGIC ---- */
    function initHeroSlider() {
        var slider = document.getElementById('heroSlider');
        var slides = document.querySelectorAll('.hero-slide');
        var currLabel = document.getElementById('heroCurr');
        var bar = document.getElementById('heroBar');
        var prevBtn = document.getElementById('heroPrev');
        var nextBtn = document.getElementById('heroNext');

        if (!slider || slides.length === 0) return;

        if (!slider || slides.length === 0) return;

        var currentIndex = 0;
        var totalSlides = slides.length;
        var slideDuration = 6000; // 6 seconds per scene
        var timer = null;
        var startTime = null;

        function updateSlide(newIndex) {
            slides.forEach(s => s.classList.remove('active'));
            slides[newIndex].classList.add('active');

            currentIndex = newIndex;
            if (currLabel) currLabel.textContent = (currentIndex + 1).toString().padStart(2, '0');

            resetProgress();

            // Optional: Trigger shutter flash on slider change for "Photo Session" feel
            if (window.triggerShutter) window.triggerShutter();
        }

        function resetProgress() {
            if (bar) bar.style.width = '0%';
            startTime = Date.now();
            if (timer) clearInterval(timer);

            timer = setInterval(() => {
                var elapsed = Date.now() - startTime;
                var progress = (elapsed / slideDuration) * 100;

                if (bar) bar.style.width = Math.min(progress, 100) + '%';

                if (progress >= 100) {
                    nextSlide();
                }
            }, 50);
        }

        function nextSlide() {
            var nextIndex = (currentIndex + 1) % totalSlides;
            updateSlide(nextIndex);
        }

        function prevSlide() {
            var prevIndex = (currentIndex - 1 + totalSlides) % totalSlides;
            updateSlide(prevIndex);
        }

        if (nextBtn) nextBtn.addEventListener('click', nextSlide);
        if (prevBtn) prevBtn.addEventListener('click', prevSlide);

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

        // Initialize first slide
        updateSlide(0);
    }
    initHeroSlider();

    /* ---- SHUTTER & FLASH ---- */
    var shutter = document.getElementById('shutter');
    var flash = document.getElementById('flash');

    function triggerShutter() {
        if (shutter) shutter.classList.add('snap');
        setTimeout(function () {
            if (shutter) {
                shutter.classList.remove('snap');
                shutter.classList.add('shut');
            }
            if (flash) flash.classList.add('pop');
            setTimeout(function () {
                if (shutter) shutter.classList.remove('shut');
                if (flash) flash.classList.remove('pop');
                updateCam();
            }, 130);
        }, 90);
        var ll = document.getElementById('lightLeak');
        if (ll) {
            ll.style.background = 'radial-gradient(ellipse at ' +
                (Math.random() * 100) + '% ' + (Math.random() * 100) +
                '%, rgba(0, 136, 255, 0.07), transparent 54%)';
            ll.classList.add('show');
            setTimeout(function () { ll.classList.remove('show'); }, 1800);
        }
    }
    window.triggerShutter = triggerShutter;

    var hsb = document.getElementById('heroShutterBtn');
    if (hsb) hsb.addEventListener('click', function () {
        var g = document.getElementById('about');
        if (g) g.scrollIntoView({ behavior: 'smooth' });
    });

    /* ---- BOKEH ---- */
    var bw = document.getElementById('bokehWrap');
    if (bw) {
        for (var i = 0; i < 10; i++) {
            var bk = document.createElement('div');
            bk.className = 'bokeh';
            bk.style.cssText =
                'left:' + (Math.random() * 100) + '%;' +
                'top:' + (Math.random() * 100) + '%;' +
                'width:' + (Math.random() * 55 + 12) + 'px;' +
                'height:' + (Math.random() * 55 + 12) + 'px;' +
                'animation-delay:' + (Math.random() * 18) + 's;' +
                'opacity:' + (Math.random() * .11 + .03) + ';';
            bw.appendChild(bk);
        }
    }

    /* ---- TICKER ---- */
    var tItems = [
        'logo/logoipsum-343.png',
        'logo/logoipsum-382.png',
        'logo/logoipsum-385.png',
        'logo/logoipsum-391.png',
        'logo/logoipsum-393.png',
        'logo/logoipsum-402.png',
        'logo/logoipsum-404.png',
        'logo/logoipsum-410.png',
        'logo/logoipsum-412.png',
        'logo/logoipsum-414.png',
        'logo/logoipsum-416.png',
        'logo/logoipsum-423.png'
    ];
    var tt = document.getElementById('tickerTrack');
    if (tt) {
        for (var j = 0; j < 5; j++) {
            tItems.forEach(function (t) {
                var d = document.createElement('div');
                d.className = 'ticker-item';
                d.innerHTML = '<img src="' + t + '" alt="Brand Logo">';
                tt.appendChild(d);
            });
        }
        var tp = 0;
        (function animTicker() {
            tp -= .5;
            if (Math.abs(tp) >= tt.scrollWidth / 3) tp = 0;
            tt.style.transform = 'translateX(' + tp + 'px)';
            requestAnimationFrame(animTicker);
        })();
    }

    /* ---- FILMSTRIP ---- */
    var fImgs = [
        'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=400',
        'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?w=400',
        'https://images.unsplash.com/photo-1519741497674-611481863552?w=400',
        'https://images.unsplash.com/photo-1529636798458-92182e662485?w=400',
        'https://images.unsplash.com/photo-1554080353-a576cf803bda?w=400',
        'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400'
    ];
    var fs = document.getElementById('filmstrip');
    if (fs) {
        for (var s = 0; s < 2; s++) {
            fImgs.forEach(function (img, idx) {
                var fr = document.createElement('div');
                fr.className = 'film-frame';
                fr.innerHTML =
                    '<div class="film-frame-image"><img src="' + img + '" alt="" loading="lazy"></div>' +
                    '<span class="film-frame-number">' +
                    (idx + 1 + s * fImgs.length).toString().padStart(2, '0') + '</span>';
                fs.appendChild(fr);
            });
        }
        var fp = 0;
        (function animFilm() {
            fp -= .28;
            if (Math.abs(fp) >= 212 * fImgs.length) fp = 0;
            fs.style.transform = 'translateX(' + fp + 'px)';
            requestAnimationFrame(animFilm);
        })();
    }

    /* ---- DISCOVERY IMAGES ---- */
    var dImgs = [
        'https://images.unsplash.com/photo-1542038784456-1ea8e935640e?w=400',
        'https://images.unsplash.com/photo-1519741497674-611481863552?w=400',
        'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=400',
        'https://images.unsplash.com/photo-1522673607200-1648832cee98?w=400',
        'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=400',
        'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?w=400',
        'https://images.unsplash.com/photo-1554080353-a576cf803bda?w=400',
        'https://images.unsplash.com/photo-1529636798458-92182e662485?w=400',
        'https://images.unsplash.com/photo-1505236858219-8359eb29e329?w=400',
        'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=400',
        'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400',
        'https://images.unsplash.com/photo-1508614589041-895b88991e3e?w=400',
        'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400',
        'https://images.unsplash.com/photo-1498050108023-c5249f4df085?w=400',
        'https://images.unsplash.com/photo-1517694712202-14dd9538aa97?w=400',
        'https://images.unsplash.com/photo-1551633512-9c36394a5009?w=400',
        'https://images.unsplash.com/photo-1506947411487-a56738267384?w=400',
        'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=400',
        'https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=400',
        'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=400',
        'https://images.unsplash.com/photo-1511671782779-c97d3d27a1d4?w=400',
        'https://images.unsplash.com/photo-1506157786151-b8491531f063?w=400',
        'https://images.unsplash.com/photo-1470225620780-dba8ba36b745?w=400',
        'https://images.unsplash.com/photo-1526218626217-dc65a29bb444?w=400'
    ];
    var dc = document.getElementById('discoveryImages');
    if (dc) {
        for (var c = 0; c < 3; c++) {
            var col = document.createElement('div');
            col.className = 'discovery-col';
            var inn = document.createElement('div');
            inn.className = 'discovery-col-inner';
            
            // To ensure 100% seamless loop:
            // 1. Create a shuffled or offset version of the full pool for each column
            var columnPool = [...dImgs];
            // Rotate the pool for each column so they don't look identical
            for(var i=0; i<c*3; i++) columnPool.push(columnPool.shift());

            // 2. Add the full pool twice (to facilitate -50% loop)
            for (var r = 0; r < 2; r++) {
                columnPool.forEach(src => {
                    var dv = document.createElement('div');
                    dv.className = 'discovery-img';
                    dv.innerHTML = '<img src="' + src + '" alt="" loading="lazy">';
                    inn.appendChild(dv);
                });
            }
            col.appendChild(inn);
            dc.appendChild(col);
        }
    }

    /* ---- PORTFOLIO SWITCHER ---- */
    var pcs = document.querySelectorAll('#portfolioCategories li');
    var pi = document.getElementById('portfolioImg');
    var ptEl = document.getElementById('portfolioTitle');
    var pdEl = document.getElementById('portfolioDesc');

    pcs.forEach(function (cat) {
        cat.addEventListener('mouseenter', function () {
            if (cat.classList.contains('active')) return;
            pcs.forEach(function (c) { c.classList.remove('active'); });
            cat.classList.add('active');
            
            var pbi = document.getElementById('portfolioBTSImg');
            
            if (pi) {
                pi.style.opacity = '0';
                pi.style.transform = 'scale(1.04) rotate(1deg)';
                if(pbi) pbi.style.opacity = '0';
                
                setTimeout(function () {
                    pi.src = cat.dataset.img;
                    if(pbi) {
                        // Use a generic placeholder or relative BTS image if available
                        pbi.src = 'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=900';
                        pbi.style.opacity = '1';
                    }
                    if (ptEl) ptEl.textContent = cat.dataset.title;
                    if (pdEl) pdEl.textContent = cat.dataset.desc;
                    
                    var pflash = document.createElement('div');
                    pflash.className = 'portfolio-flash';
                    pi.parentElement.appendChild(pflash);
                    setTimeout(() => pflash.remove(), 400);
                }, 200);
            }
        });
    });
    if (pi) pi.addEventListener('load', function () {
        pi.style.opacity = '1';
        pi.style.transform = 'scale(1)';
    });

    /* ---- GEAR TOOLKIT LOGIC ---- */
    const gearData = {
        'camera': {
            title: 'Sony Alpha a7S III',
            desc: 'The master of low light and cinematography. Captures 4K 120p with 10-bit depth.',
            img: 'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=600',
            specs: ['4K 120p', 'Dual ISO']
        },
        'lens85': {
            title: '85mm f/1.4 G-Master',
            desc: 'Our primary portrait weapon. Razor-sharp with creamy, cinematic bokeh.',
            img: 'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=600',
            specs: ['f/1.4 Aperture', 'Portrait King']
        },
        'lens2470': {
            title: '24-70mm f/2.8',
            desc: 'The essential workhorse for events and high-stakes wedding coverage.',
            img: 'https://images.unsplash.com/photo-1519741497674-611481863552?w=600',
            specs: ['f/2.8 Constant', 'Versatility']
        },
        'drone': {
            title: 'DJI Mavic 3 Cine',
            desc: 'Breathtaking 5.1K aerial perspectives with Hasselblad optics.',
            img: 'https://images.unsplash.com/photo-1506947411487-a56738267384?w=600',
            specs: ['5.1K ProRes', '46-min Flight']
        },
        'gimbal': {
            title: 'DJI RS 3 Pro',
            desc: 'Rock-solid stabilization for those silky-smooth cinematic tracking shots.',
            img: 'https://images.unsplash.com/photo-1529636798458-92182e662485?w=600',
            specs: ['4.5kg Payload', 'LiDAR Focus']
        }
    };

    const bagWrap = document.getElementById('bagWrap');
    const previewPopup = document.getElementById('previewPopup');
    const previewImg = document.getElementById('previewImg');
    const previewTitle = document.getElementById('previewTitle');
    const previewDesc = document.getElementById('previewDesc');
    const gearMainContainer = document.getElementById('gearContainer');

    if (previewImg) {
        previewImg.onload = () => previewImg.classList.add('loaded');
        previewImg.onerror = () => previewImg.classList.remove('loaded');
    }

    function toggleBag() {
        if (!bagWrap) return;
        bagWrap.classList.toggle('open');
        if (bagWrap.classList.contains('open')) {
            if (window.triggerShutter) window.triggerShutter();
        }
    }
    window.toggleBag = toggleBag;

    function showPreview(key, el) {
        const data = gearData[key];
        if (!data) return;
        if (previewImg) {
            previewImg.classList.remove('loaded');
            previewImg.src = data.img;
        }
        if (previewTitle) previewTitle.textContent = data.title;
        if (previewDesc) previewDesc.textContent = data.desc;
        
        const s1 = document.getElementById('spec1');
        const s2 = document.getElementById('spec2');
        if (s1 && s2) {
            s1.textContent = data.specs[0];
            s2.textContent = data.specs[1];
        }
        
        if (previewPopup) previewPopup.classList.add('active');
        if (gearMainContainer) gearMainContainer.classList.add('focus-active');
        el.classList.add('active-focus');
    }
    window.showPreview = showPreview;

    function hidePreview(el) {
        if (previewPopup) previewPopup.classList.remove('active');
        if (gearMainContainer) gearMainContainer.classList.remove('focus-active');
        el.classList.remove('active-focus');
        
        const img = el.querySelector('img');
        if (img) img.style.transform = 'rotateX(0deg) rotateY(0deg)';
    }
    window.hidePreview = hidePreview;

    // 3D Tilt Logic for Gear Items
    document.addEventListener('mousemove', (e) => {
        const activeItem = document.querySelector('.gear-item.active-focus');
        if (activeItem) {
            const rect = activeItem.getBoundingClientRect();
            const centerX = rect.left + rect.width / 2;
            const centerY = rect.top + rect.height / 2;
            const mouseX = e.clientX - centerX;
            const mouseY = e.clientY - centerY;
            
            const rotateX = (mouseY / (rect.height / 2)) * -20; 
            const rotateY = (mouseX / (rect.width / 2)) * 20;
            
            const img = activeItem.querySelector('img');
            if (img) img.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale(1.15) translateZ(60px)`;
        }
    });

    /* ---- REVEAL ON SCROLL ---- */
    var ro = new IntersectionObserver(function (en) {
        en.forEach(function (e) {
            if (e.isIntersecting) {
                e.target.classList.add('visible');
                ro.unobserve(e.target);
            }
        });
    }, { threshold: .1, rootMargin: '0px 0px -8% 0px' });
    document.querySelectorAll('.reveal').forEach(function (el) { ro.observe(el); });

    /* ---- POLAROID DEVELOP ---- */
    var po = new IntersectionObserver(function (en) {
        en.forEach(function (e) {
            if (e.isIntersecting) {
                setTimeout(function () { e.target.classList.remove('developing'); }, 320);
                po.unobserve(e.target);
            }
        });
    }, { threshold: .45 });
    document.querySelectorAll('.polaroid').forEach(function (p) { po.observe(p); });

    /* ---- COUNTER ANIMATION ---- */
    var co = new IntersectionObserver(function (en) {
        en.forEach(function (e) {
            if (e.isIntersecting && !e.target.dataset.done) {
                var tgt = parseInt(e.target.dataset.count);
                var cur = 0;
                var inc = tgt / 60;
                var t = setInterval(function () {
                    cur += inc;
                    if (cur >= tgt) { cur = tgt; clearInterval(t); }
                    e.target.textContent = Math.floor(cur) + '+';
                }, 22);
                e.target.dataset.done = '1';
                co.unobserve(e.target);
            }
        });
    }, { threshold: .5 });
    document.querySelectorAll('[data-count]').forEach(function (el) { co.observe(el); });

    /* ---- NAVBAR & HUD SCROLL ---- */
    var navbar = document.getElementById('navbar');
    var hudBrand = document.getElementById('hudBrand');
    var hudBat = document.getElementById('hudBat');
    var ticking = false;

    function applyScrollState(scrolled) {
        if (scrolled) {
            if (navbar) {
                navbar.classList.add('scrolled');
            }
        } else {
            if (navbar) {
                navbar.classList.remove('scrolled');
            }
        }
        updateBattery();
    }

    /* Run once on load */
    applyScrollState(window.scrollY > 85);

    window.addEventListener('scroll', function () {
        if (!ticking) {
            requestAnimationFrame(function () {
                applyScrollState(window.scrollY > 85);
                ticking = false;
            });
            ticking = true;
        }
    }, { passive: true });

    window.addEventListener('resize', function () {
        applyScrollState(window.scrollY > 85);
    }, { passive: true });

    /* ---- BATTERY (scroll progress) ---- */
    var batFill = document.getElementById('batFill');
    var batPct = document.getElementById('batPct');

    function updateBattery() {
        var st = window.pageYOffset || document.documentElement.scrollTop;
        var sh = document.documentElement.scrollHeight - window.innerHeight;
        var pct = sh > 0 ? Math.max(1, Math.round(100 - (st / sh) * 100)) : 100;
        if (batFill) {
            batFill.style.width = pct + '%';
            batFill.classList.remove('mid', 'low');
            if (pct <= 20) batFill.classList.add('low');
            else if (pct <= 50) batFill.classList.add('mid');
        }
        if (batPct) batPct.textContent = pct + '%';

        // Hide specific central HUD target after Hero
        // Central HUD target and scan are persistently visible for cinematic feel as requested
        const centerTarget = document.getElementById('vfCenterTarget');
        const vfScan = document.querySelector('.vf-scan');
        if (centerTarget) centerTarget.style.opacity = '1';
        if (vfScan) vfScan.style.opacity = '0.3';
    }
    updateBattery();

    /* ---- SESSION TIMER ---- */
    var timerEl = document.getElementById('hudTimer');
    var ps = 0;
    setInterval(function () {
        ps++;
        if (timerEl) {
            timerEl.textContent =
                String(Math.floor(ps / 3600)).padStart(2, '0') + ':' +
                String(Math.floor((ps % 3600) / 60)).padStart(2, '0') + ':' +
                String(ps % 60).padStart(2, '0');
        }
    }, 1000);

    /* ---- HAMBURGER / MOBILE MENU ---- */
    var ham = document.getElementById('hamburger');
    var mob = document.getElementById('mobileMenu');
    if (ham && mob) {
        ham.addEventListener('click', function () {
            ham.classList.toggle('active');
            mob.classList.toggle('active');
            document.body.style.overflow = mob.classList.contains('active') ? 'hidden' : '';
        });
    }

    /* ---- SMOOTH SCROLL ANCHORS ---- */
    document.querySelectorAll('a[href^="#"]').forEach(function (l) {
        l.addEventListener('click', function (e) {
            var t = document.querySelector(l.getAttribute('href'));
            if (t && l.getAttribute('href') !== '#') {
                e.preventDefault();
                t.scrollIntoView({ behavior: 'smooth' });
                closeMobile();
            }
        });
    });

    /* ---- ACTIVE NAV LINK ON SCROLL ---- */
    var secs = document.querySelectorAll('section[id]');
    var nls = document.querySelectorAll('.nav-menu a');
    var no = new IntersectionObserver(function (en) {
        en.forEach(function (e) {
            if (e.isIntersecting) {
                var id = e.target.id;
                nls.forEach(function (l) {
                    l.classList.toggle('active', l.getAttribute('href') === '#' + id);
                });
            }
        });
    }, { threshold: .3 });
    secs.forEach(function (s) { no.observe(s); });



    var horizon = document.getElementById('vfHorizon');
    document.addEventListener('mousemove', function (e) {
        if (horizon) {
            var tilt = (e.clientX / window.innerWidth - 0.5) * 6;
            horizon.style.transform = 'rotate(' + tilt + 'deg)';
        }

        // Focusing logic
        var ct = document.getElementById('vfCenterTarget');
        if (ct) {
            var dx = e.clientX - window.innerWidth / 2;
            var dy = e.clientY - window.innerHeight * 0.55;
            if (Math.abs(dx) < 140 && Math.abs(dy) < 90) ct.classList.add('active');
            else ct.classList.remove('active');
        }
    });

    /* ---- RANDOM LIGHT LEAKS ---- */
    setInterval(function () {
        if (Math.random() > .65) {
            var ll = document.getElementById('lightLeak');
            if (ll) {
                ll.style.background = 'radial-gradient(ellipse at ' +
                    (Math.random() * 100) + '% ' + (Math.random() * 100) +
                    '%, rgba(79,138,255,0.06), transparent 52%)';
                ll.classList.add('show');
                setTimeout(function () { ll.classList.remove('show'); }, 2200);
            }
        }
    }, 7000);


    /* ---- APYB KNOWLEDGE BASE ---- */
    var APYB_INFO = {
        name: "As Per Your Beat Studio",
        founded: "2015",
        experience: "9+ Years of visual storytelling",
        location: "42, Creative Hub, Bandra West, Mumbai",
        contact: {
            phone: "+91 98765 43210",
            email: "hello@asperyourbeat.com",
            web: "www.asperyourbeat.com"
        },
        services: [
            "Wedding Photography (Royal, Traditional, Destination)",
            "Cinematic Videography (4K, Same-Day Edit)",
            "Portrait Sessions (Studio & Outdoor)",
            "Corporate Events",
            "Maternity & Baby Shoots",
            "Drone & Aerial Photography",
            "Live Streaming Services"
        ],
        stats: "500+ Projects completed in 24+ cities across India.",
        packages: [
            "Cinematic Collection: Ideal for highlight films and artistic portraits.",
            "Gold Collection: Full coverage with premium photo albums.",
            "Platinum Collection: Luxury coverage including 4K drone and multi-cam setups."
        ],
        moodboards: {
            royal: [
                'https://images.unsplash.com/photo-1519741497674-611481863552?w=400',
                'https://images.unsplash.com/photo-1511285560929-80b456fea0bc?w=400',
                'https://images.unsplash.com/photo-1529636798458-92182e662485?w=400'
            ],
            vintage: [
                'https://images.unsplash.com/photo-1532712938310-34cb3982ef74?w=400',
                'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400',
                'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=400'
            ],
            modern: [
                'https://images.unsplash.com/photo-1492691527719-9d1e07e534b4?w=400',
                'https://images.unsplash.com/photo-1520854221256-17451cc331bf?w=400',
                'https://images.unsplash.com/photo-1554080353-a576cf803bda?w=400'
            ]
        }
    };

    /* ---- APYB CHATBOT LOGIC ---- */
    var launchBtn = document.getElementById('chatbotLauncher');
    var widget = document.getElementById('chatWidget');
    var closeBtn = document.getElementById('chatClose');
    var sendBtn = document.getElementById('chatSend');
    var chatInput = document.getElementById('chatInput');
    var chatBody = document.getElementById('chatBody');
    var quickReplies = document.querySelectorAll('.quick-reply');

    function toggleChat() {
        widget.classList.toggle('active');
        if (widget.classList.contains('active')) {
            setTimeout(() => chatInput.focus(), 600);
        }
    }

    if (launchBtn) launchBtn.addEventListener('click', toggleChat);
    if (closeBtn) closeBtn.addEventListener('click', toggleChat);

    function addMessage(text, side, type = 'text') {
        var msg = document.createElement('div');
        msg.className = 'message ' + (side === 'bot' ? 'bot-msg' : 'user-msg');

        if (type === 'moodboard' && Array.isArray(text)) {
            msg.className += ' moodboard-msg';
            msg.innerHTML = '<div class="moodboard-grid">' +
                text.map(src => `<img src="${src}" alt="Moodboard" onclick="window.open('${src}', '_blank')">`).join('') +
                '</div><p class="moodboard-caption">SCENE: Visual Inspiration Captured.</p>';
        } else {
            msg.textContent = text;
        }

        chatBody.appendChild(msg);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function botResponse(text, type = 'text') {
        var typing = document.createElement('div');
        typing.className = 'message bot-msg typing';
        typing.innerHTML = '<span class="status">PROCESSING_INTENT...</span><div class="scan-bar"></div>';
        chatBody.appendChild(typing);
        chatBody.scrollTop = chatBody.scrollHeight;

        setTimeout(() => {
            typing.remove();
            addMessage(text, 'bot', type);
        }, 1200);
    }

    function getSmartResponse(input) {
        var q = input.toLowerCase();

        // MOODBOARD DETECTION
        if (q.includes('royal') || q.includes('king') || q.includes('regal')) {
            botResponse(APYB_INFO.moodboards.royal, 'moodboard');
            return "SCENE 2: The Royal Treatment. Here is a moodboard of our grandest wedding captures. Does this align with your vision?";
        }
        if (q.includes('vintage') || q.includes('classic') || q.includes('old')) {
            botResponse(APYB_INFO.moodboards.vintage, 'moodboard');
            return "SCENE 2: Timeless Aesthetics. I've compiled our best vintage-style frames for you. Notice the warm grain and soft focus.";
        }
        if (q.includes('modern') || q.includes('clean') || q.includes('tech')) {
            botResponse(APYB_INFO.moodboards.modern, 'moodboard');
            return "SCENE 2: The Modern Edge. High-contrast, sharp, and cinematic. Here is how we script the contemporary look.";
        }

        if (q.includes('price') || q.includes('cost') || q.includes('package') || q.includes('rate')) {
            return "SCENE 3: The Production Budget. We offer 3 primary packages. Cinematic (₹80k+), Gold (₹1.5L+), and Platinum (₹2.5L+). Shall we discuss the deliverables?";
        }
        if (q.includes('service') || q.includes('what you do') || q.includes('offer')) {
            return "SCENE 1: The Script. We provide " + APYB_INFO.services[0] + ", Cinematic Films, and Drone Coverage. We are your visual directors.";
        }
        if (q.includes('location') || q.includes('where') || q.includes('address') || q.includes('studio')) {
            return "SCENE: On Location. Our lead studio is in Bandra, Mumbai. However, we've filmed across 24+ cities. Where is your shoot planned?";
        }
        if (q.includes('contact') || q.includes('call') || q.includes('phone') || q.includes('email')) {
            return "SCENE: Direct Line. Dial " + APYB_INFO.contact.phone + " for the Producer. We are standing by.";
        }
        if (q.includes('hi') || q.includes('hello') || q.includes('hey')) {
            return "Scene 1: Initial Discovery. [REC] Active. I am the As Per Your Beat Creative Director. How shall we script your story today?";
        }

        return "SCENE: Improv. I'm currently scanning your request. While I process, would you like to see a Royal, Vintage, or Modern moodboard for your project?";
    }

    function handleSend() {
        var val = chatInput.value.trim();
        if (!val) return;
        addMessage(val, 'user');
        chatInput.value = '';
        var resp = getSmartResponse(val);
        if (resp) botResponse(resp);
    }

    if (sendBtn) sendBtn.addEventListener('click', handleSend);
    if (chatInput) chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') handleSend();
    });

    quickReplies.forEach(btn => {
        btn.addEventListener('click', () => {
            var text = btn.textContent;
            addMessage(text, 'user');
            if (text === 'Book a Shoot') botResponse("SCENE: The Call Sheet. Are you looking for a wedding, pre-wedding, or casual session? I can check our production schedule.");
            else if (text === 'View Packages') botResponse("SCENE 3: Executive Summary. We have Cinematic, Gold, and Platinum collections. The Gold collection is our most requested script!");
            else if (text === 'Gallery') botResponse("SCENE 2: The Portfolio Reveal. You can scroll up to view our full bodies of work across 500+ successful productions.");
        });
    });

})();

/* ---- GLOBAL HELPERS ---- */
function closeMobile() {
    var h = document.getElementById('hamburger');
    var m = document.getElementById('mobileMenu');
    if (h) h.classList.remove('active');
    if (m) m.classList.remove('active');
    // Also reset mobile dropdowns
    document.querySelectorAll('.mobile-dropdown').forEach(d => d.classList.remove('active'));
    document.body.style.overflow = '';
}

function toggleMobileDropdown() {
    const dropdown = document.querySelector('.mobile-dropdown');
    dropdown.classList.toggle('active');
}

function handleSubmit(e) {
    e.preventDefault();
    if (window.triggerShutter) triggerShutter();
    setTimeout(function () {
        alert("Thank you! Your production request has been captured. We'll get back to you soon. 📸");
        e.target.reset();
    }, 480);
    return false;
}

function toggleBTS(btn) {
    const card = btn.closest('.bts-flipper');
    if (card) {
        card.classList.toggle('flipped');
        // Play a small focus sound effect via playTone if available
        if (window.playTone) playTone(600, 'sine', 0.1, 0.05);
    }
}

/* ---- ELITE INTERACTIVE ANIMATIONS ---- */
document.addEventListener('DOMContentLoaded', function() {
    // Magnetic Buttons
    const magnets = document.querySelectorAll('.btn-primary, .btn-outline, .nav-cta-pill, .service-link, .bts-toggle');
    magnets.forEach((m) => {
        m.addEventListener('mousemove', function(e) {
            const pos = m.getBoundingClientRect();
            const x = e.clientX - pos.left;
            const y = e.clientY - pos.top;
            m.style.transform = 'translate(' + (x - pos.width/2) * 0.35 + 'px, ' + (y - pos.height/2) * 0.35 + 'px)';
        });
        m.addEventListener('mouseleave', function() {
            m.style.transform = 'translate(0, 0)';
        });
    });

    // 3D Card Tilt
    const cards = document.querySelectorAll('.service-card, .gallery-item, .testi-reveal-card');
    cards.forEach(card => {
        card.addEventListener('mousemove', e => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            const centerX = rect.width / 2;
            const centerY = rect.height / 2;
            const rotateX = (y - centerY) / 8;
            const rotateY = (centerX - x) / 8;
            card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.02, 1.02, 1.02)`;
        });
        card.addEventListener('mouseleave', () => {
            card.style.transform = 'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)';
        });
    });
});
