/* ═══════════════════════════════════════════════════════════════
   VAL'S DREAMSCAPE — 星空粒子 + 旅程镜头系统
   ═══════════════════════════════════════════════════════════════ */

(function() {
    'use strict';

    const bodyEl = document.body;
    const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const canvas = document.getElementById('starfield');

    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    let width = 0;
    let height = 0;
    let stars = [];
    let nebulas = [];
    let animationId = null;

    function resize() {
        width = canvas.width = window.innerWidth;
        height = canvas.height = window.innerHeight;
    }

    function createStars() {
        const density = reduceMotion ? 14000 : 8500;
        const count = Math.floor((width * height) / density);

        stars = [];
        for (let i = 0; i < count; i++) {
            stars.push({
                x: Math.random() * width,
                y: Math.random() * height,
                size: Math.random() * 1.35 + 0.45,
                speed: reduceMotion ? 0.03 : Math.random() * 0.24 + 0.08,
                opacity: Math.random() * 0.76 + 0.2,
                twinkle: Math.random() * Math.PI * 2,
                color: Math.random() > 0.68
                    ? `hsl(${205 + Math.random() * 70}, 72%, 82%)`
                    : '#ffffff'
            });
        }
    }

    function createNebulas() {
        nebulas = [
            { x: width * 0.18, y: height * 0.25, r: Math.max(width * 0.22, 160), color: 'rgba(123,104,238,0.035)' },
            { x: width * 0.78, y: height * 0.68, r: Math.max(width * 0.26, 180), color: 'rgba(34,211,238,0.03)' },
            { x: width * 0.48, y: height * 0.52, r: Math.max(width * 0.31, 220), color: 'rgba(74,144,217,0.026)' }
        ];
    }

    function drawNebulas() {
        nebulas.forEach((n) => {
            const gradient = ctx.createRadialGradient(n.x, n.y, 0, n.x, n.y, n.r);
            gradient.addColorStop(0, n.color);
            gradient.addColorStop(1, 'transparent');
            ctx.fillStyle = gradient;
            ctx.beginPath();
            ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
            ctx.fill();
        });
    }

    function drawStars() {
        stars.forEach((star) => {
            if (!reduceMotion) star.twinkle += 0.02;
            const twinkleFactor = reduceMotion ? 0.72 : (0.5 + Math.sin(star.twinkle) * 0.5);
            const currentOpacity = star.opacity * twinkleFactor;

            ctx.beginPath();
            ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
            ctx.fillStyle = star.color;
            ctx.globalAlpha = currentOpacity;
            ctx.fill();
            ctx.globalAlpha = 1;

            star.y += star.speed;
            if (star.y > height + 10) {
                star.y = -10;
                star.x = Math.random() * width;
            }
        });
    }

    function animate() {
        ctx.fillStyle = reduceMotion ? 'rgba(3,3,8,0.88)' : 'rgba(3,3,8,0.12)';
        ctx.fillRect(0, 0, width, height);

        drawNebulas();
        drawStars();

        animationId = requestAnimationFrame(animate);
    }

    function startSky() {
        resize();
        createStars();
        createNebulas();
        if (!animationId) animate();
    }

    function stopSky() {
        if (animationId) {
            cancelAnimationFrame(animationId);
            animationId = null;
        }
    }

    function setupReveal() {
        const reveals = document.querySelectorAll('.reveal');
        if (!reveals.length) return;

        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) entry.target.classList.add('visible');
            });
        }, {
            threshold: 0.12,
            rootMargin: '0px 0px -52px 0px'
        });

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

    function setupParallax() {
        const hero = document.querySelector('.hero');
        if (!hero || reduceMotion) return;

        const onScroll = () => {
            const scrollY = window.scrollY;
            const opacity = Math.max(0, 1 - scrollY / 620);
            hero.style.opacity = opacity;
            hero.style.transform = `translateY(${scrollY * 0.28}px)`;
        };

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

    function setupGlow() {
        if (reduceMotion) return;

        const cards = document.querySelectorAll('.dream-card');
        cards.forEach((card) => {
            card.addEventListener('mousemove', (e) => {
                const rect = card.getBoundingClientRect();
                card.style.setProperty('--mouse-x', `${e.clientX - rect.left}px`);
                card.style.setProperty('--mouse-y', `${e.clientY - rect.top}px`);
            });
        });
    }

    function setupImmersiveNav() {
        if (!bodyEl.classList.contains('immersive-single')) return;

        const nav = document.querySelector('.nav');
        if (!nav) return;

        let lastY = window.scrollY;
        let ticking = false;

        const updateNav = () => {
            const currentY = window.scrollY;
            const delta = currentY - lastY;
            const hidden = currentY > 120 && delta > 4;

            nav.style.transform = hidden ? 'translateY(-110%)' : 'translateY(0)';
            nav.style.opacity = hidden ? '0.12' : '1';
            lastY = currentY;
            ticking = false;
        };

        window.addEventListener('scroll', () => {
            if (ticking) return;
            ticking = true;
            requestAnimationFrame(updateNav);
        }, { passive: true });
    }

    function setupStoryJourney() {
        const body = document.getElementById('storyBody');
        const progress = document.getElementById('storyProgress');
        const article = document.querySelector('.story-journey');
        if (!body || !progress) return;

        const scenes = Array.from(body.querySelectorAll(':scope > p'));
        if (!scenes.length) return;

        const sceneProfiles = [
            { key: 'starsea', keywords: ['星海', '光河', '星辰', '月亮', '星尘', '夜', '晨色'] },
            { key: 'crystal', keywords: ['水晶', '冰晶', '镜面', '镜谷', '峡壁', '黑曜石', '井'] },
            { key: 'calling', keywords: ['使命', '记录', '交还', '送回', '名字', '返程', '现实'] },
            { key: 'void', keywords: ['深渊', '平静', '雾', '无声', '遗忘', '道歉', '空白'] }
        ];

        const detectScene = (text) => {
            let matched = 'void';
            let best = -1;
            for (const profile of sceneProfiles) {
                let score = 0;
                for (const kw of profile.keywords) {
                    if (text.includes(kw)) score++;
                }
                if (score > best) {
                    best = score;
                    matched = profile.key;
                }
            }
            return matched;
        };

        let currentScene = '';
        let shiftTimer;
        let ticking = false;

        const onScrollFrame = () => {
            const rect = body.getBoundingClientRect();
            const total = Math.max(body.scrollHeight - window.innerHeight, 1);
            const scrolled = Math.min(Math.max(-rect.top, 0), total);
            const ratio = scrolled / total;
            progress.style.width = `${(ratio * 100).toFixed(2)}%`;

            let activeIndex = 0;
            let minDistance = Infinity;

            scenes.forEach((p, idx) => {
                const r = p.getBoundingClientRect();
                const distance = Math.abs(r.top - window.innerHeight * 0.36);
                if (distance < minDistance) {
                    minDistance = distance;
                    activeIndex = idx;
                }
            });

            scenes.forEach((p, idx) => p.classList.toggle('active-scene', idx === activeIndex));

            const activeText = scenes[activeIndex]?.innerText || '';
            const scene = detectScene(activeText);
            if (scene !== currentScene) {
                currentScene = scene;
                bodyEl.dataset.scene = scene;
                bodyEl.classList.add('scene-shift');
                clearTimeout(shiftTimer);
                shiftTimer = setTimeout(() => bodyEl.classList.remove('scene-shift'), 420);
            }

            if (article && !reduceMotion) {
                const camY = scrolled * 0.015;
                article.style.transform = `translate3d(0, ${camY}px, 0)`;
            }

            ticking = false;
        };

        window.addEventListener('scroll', () => {
            if (ticking) return;
            ticking = true;
            requestAnimationFrame(onScrollFrame);
        }, { passive: true });

        onScrollFrame();
    }

    function setupOrbsParallax() {
        if (reduceMotion) return;

        const orbs = document.querySelectorAll('.story-orb');
        if (!orbs.length) return;

        let ticking = false;

        const update = () => {
            const y = window.scrollY;
            orbs.forEach((orb, i) => {
                const factor = (i + 1) * 0.034;
                const xShift = Math.sin(y * 0.0018 + i) * 8;
                const yShift = y * factor;
                orb.style.transform = `translate(${xShift}px, ${yShift}px)`;
            });
            ticking = false;
        };

        window.addEventListener('scroll', () => {
            if (ticking) return;
            ticking = true;
            requestAnimationFrame(update);
        }, { passive: true });

        update();
    }

    function setupTitleCard() {
        if (!bodyEl.classList.contains('immersive-single')) return;
        if (reduceMotion) return;

        const card = document.getElementById('titleCard');
        if (!card) return;

        card.classList.add('show');
        setTimeout(() => {
            card.classList.add('fade');
        }, 1200);
    }

    function setupLifecycle() {
        window.addEventListener('resize', () => {
            resize();
            createStars();
            createNebulas();
        });

        document.addEventListener('visibilitychange', () => {
            if (document.hidden) stopSky();
            else startSky();
        });
    }

    document.addEventListener('DOMContentLoaded', () => {
        const storyRoot = document.querySelector('.story-journey');
        if (storyRoot) {
            const slug = storyRoot.getAttribute('data-story-slug') || '';
            if (slug === 'first-light') {
                bodyEl.classList.add('immersive-single');
            }
        }

        bodyEl.classList.add('js-ready');
        startSky();
        setupLifecycle();
        setupReveal();
        setupParallax();
        setupGlow();
        setupImmersiveNav();
        setupStoryJourney();
        setupOrbsParallax();
        setupTitleCard();
    });
})();
