/* ============================================
   Lumina Vesper Creative Portfolio
   Custom JavaScript
   ============================================ */

(function() {
    'use strict';

    // ─────────────────────────────────────────────
    // Typewriter Effect
    // ─────────────────────────────────────────────
    function initTypewriter() {
        const typewriterEl = document.querySelector('.lv-typewriter');
        if (!typewriterEl) return;

        // Respect reduced motion preference
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            return;
        }

        const phrases = JSON.parse(typewriterEl.getAttribute('data-phrases') || '[]');
        if (phrases.length === 0) return;

        let phraseIndex = 0;
        let charIndex = 0;
        let isDeleting = false;
        let typingSpeed = 100;

        function type() {
            const currentPhrase = phrases[phraseIndex];

            if (isDeleting) {
                typewriterEl.textContent = currentPhrase.substring(0, charIndex - 1);
                charIndex--;
                typingSpeed = 50;
            } else {
                typewriterEl.textContent = currentPhrase.substring(0, charIndex + 1);
                charIndex++;
                typingSpeed = 100;
            }

            if (!isDeleting && charIndex === currentPhrase.length) {
                // Pause at end of phrase
                typingSpeed = 2000;
                isDeleting = true;
            } else if (isDeleting && charIndex === 0) {
                isDeleting = false;
                phraseIndex = (phraseIndex + 1) % phrases.length;
                typingSpeed = 500;
            }

            setTimeout(type, typingSpeed);
        }

        // Start after a short delay
        setTimeout(type, 1000);
    }

    // ─────────────────────────────────────────────
    // Smooth Scroll for Anchor Links
    // ─────────────────────────────────────────────
    function initSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                const targetId = this.getAttribute('href');
                if (targetId === '#') return;

                const targetEl = document.querySelector(targetId);
                if (!targetEl) return;

                e.preventDefault();

                const navHeight = document.querySelector('.lv-navbar')?.offsetHeight || 0;
                const targetPosition = targetEl.getBoundingClientRect().top + window.pageYOffset - navHeight - 20;

                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });

                // Update URL without scrolling
                history.pushState(null, null, targetId);
            });
        });
    }

    // ─────────────────────────────────────────────
    // Scroll Animations (fallback if RSL animate-on-scroll not loaded)
    // ─────────────────────────────────────────────
    function initScrollAnimations() {
        // Check if RSL's animate-on-scroll is available
        if (window.RSL && window.RSL.AnimateOnScroll) {
            // RSL handles it
            return;
        }

        // Respect reduced motion
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            document.querySelectorAll('[data-animate]').forEach(el => {
                el.classList.add('animated');
            });
            return;
        }

        const animatedElements = document.querySelectorAll('[data-animate]');

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const delay = entry.target.getAttribute('data-animate-delay') || 0;
                    setTimeout(() => {
                        entry.target.classList.add('animated');
                    }, parseInt(delay));
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        });

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

    // ─────────────────────────────────────────────
    // Navbar Background on Scroll
    // ─────────────────────────────────────────────
    function initNavbarScroll() {
        const navbar = document.querySelector('.lv-navbar');
        if (!navbar) return;

        let lastScroll = 0;

        window.addEventListener('scroll', () => {
            const currentScroll = window.pageYOffset;

            if (currentScroll > 100) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }

            lastScroll = currentScroll;
        }, { passive: true });
    }

    // ─────────────────────────────────────────────
    // Back to Top Button
    // ─────────────────────────────────────────────
    function initBackToTop() {
        const backToTop = document.querySelector('.lv-back-to-top');
        if (!backToTop) return;

        backToTop.addEventListener('click', (e) => {
            e.preventDefault();
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }

    // ─────────────────────────────────────────────
    // Form Submission Handler (Demo)
    // ─────────────────────────────────────────────
    function initContactForm() {
        const form = document.querySelector('.lv-contact-form');
        if (!form) return;

        form.addEventListener('submit', (e) => {
            e.preventDefault();

            // In a real implementation, you would send the form data to a server
            const submitBtn = form.querySelector('.lv-btn-submit');
            const originalText = submitBtn.innerHTML;

            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
            submitBtn.disabled = true;

            // Simulate form submission
            setTimeout(() => {
                submitBtn.innerHTML = '<i class="fas fa-check"></i> Message Sent!';
                submitBtn.style.background = 'linear-gradient(135deg, #4ECDC4 0%, #3DBDB5 100%)';

                // Reset form
                form.reset();

                // Reset button after delay
                setTimeout(() => {
                    submitBtn.innerHTML = originalText;
                    submitBtn.style.background = '';
                    submitBtn.disabled = false;
                }, 3000);
            }, 1500);
        });
    }

    // ─────────────────────────────────────────────
    // Initialize Custom Accordion Behavior
    // ─────────────────────────────────────────────
    function initCustomAccordion() {
        // The RSL accordion.js handles the core functionality
        // This adds visual enhancements specific to this template
        const accordionTitles = document.querySelectorAll('.lv-accordion-title');

        accordionTitles.forEach(title => {
            // Update icon on state change
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.attributeName === 'aria-expanded') {
                        const isExpanded = title.getAttribute('aria-expanded') === 'true';
                        const icon = title.querySelector('.lv-accordion-icon i');
                        if (icon) {
                            icon.className = isExpanded ? 'fas fa-minus' : 'fas fa-plus';
                        }
                    }
                });
            });

            observer.observe(title, { attributes: true });
        });
    }

    // ─────────────────────────────────────────────
    // Initialize Everything
    // ─────────────────────────────────────────────
    function init() {
        initTypewriter();
        initSmoothScroll();
        initScrollAnimations();
        initNavbarScroll();
        initBackToTop();
        initContactForm();
        initCustomAccordion();

        // Initialize RSL components if available
        if (window.RSL) {
            if (window.RSL.Navbar) RSL.Navbar.init();
            if (window.RSL.Accordion) RSL.Accordion.init();
            if (window.RSL.Thumbnail) RSL.Thumbnail.init();
            if (window.RSL.Testimonial) RSL.Testimonial.init();
            if (window.RSL.StarRating) RSL.StarRating.init();
            if (window.RSL.FormValidation) RSL.FormValidation.init();
        }
    }

    // Run on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
