// Advanced Features for Builder Bee Projects Website
// Enhanced functionality inspired by Blotato.com

class AdvancedWebsiteFeatures {
    constructor() {
        this.init();
    }

    init() {
        this.setupAdvancedAnimations();
        this.setupParallaxEffects();
        this.setupAdvancedNavigation();
        this.setupImageLazyLoading();
        this.setupAdvancedAnalytics();
        this.setupPerformanceOptimizations();
    }

    setupAdvancedAnimations() {
        // Intersection Observer for scroll animations
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate-in');
                }
            });
        }, observerOptions);

        // Observe all animatable elements
        document.querySelectorAll('.service-card, .portfolio-item, .review-card, .stat-item').forEach(el => {
            observer.observe(el);
        });

        // Advanced hover effects
        document.querySelectorAll('.service-card').forEach(card => {
            card.addEventListener('mouseenter', () => {
                card.style.transform = 'translateY(-15px) scale(1.02)';
                card.style.boxShadow = '0 25px 50px rgba(0, 0, 0, 0.4)';
            });
            
            card.addEventListener('mouseleave', () => {
                card.style.transform = 'translateY(0) scale(1)';
                card.style.boxShadow = '0 10px 30px rgba(0, 0, 0, 0.3)';
            });
        });
    }

    setupParallaxEffects() {
        let ticking = false;

        function updateParallax() {
            const scrolled = window.pageYOffset;
            const parallaxElements = document.querySelectorAll('.parallax-element');
            
            parallaxElements.forEach(element => {
                const speed = element.dataset.speed || 0.5;
                const yPos = -(scrolled * speed);
                element.style.transform = `translateY(${yPos}px)`;
            });
            
            ticking = false;
        }

        function requestTick() {
            if (!ticking) {
                requestAnimationFrame(updateParallax);
                ticking = true;
            }
        }

        window.addEventListener('scroll', requestTick);
    }

    setupAdvancedNavigation() {
        // Smart navigation hiding/showing
        let lastScrollTop = 0;
        const header = document.querySelector('.header');
        const scrollThreshold = 100;

        window.addEventListener('scroll', () => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            if (scrollTop > scrollThreshold) {
                if (scrollTop > lastScrollTop) {
                    // Scrolling down
                    header.classList.add('nav-hidden');
                } else {
                    // Scrolling up
                    header.classList.remove('nav-hidden');
                }
            }
            
            lastScrollTop = scrollTop;
        });

        // Active section highlighting
        const sections = document.querySelectorAll('section[id]');
        const navLinks = document.querySelectorAll('.nav-link[href^="#"]');

        window.addEventListener('scroll', () => {
            let current = '';
            sections.forEach(section => {
                const sectionTop = section.offsetTop;
                const sectionHeight = section.clientHeight;
                if (pageYOffset >= sectionTop - 200) {
                    current = section.getAttribute('id');
                }
            });

            navLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href') === `#${current}`) {
                    link.classList.add('active');
                }
            });
        });
    }

    setupImageLazyLoading() {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    imageObserver.unobserve(img);
                }
            });
        });

        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }

    setupAdvancedAnalytics() {
        // Track user interactions
        this.trackEvent = (eventName, data = {}) => {
            if (typeof gtag !== 'undefined') {
                gtag('event', eventName, {
                    event_category: 'website_interaction',
                    event_label: 'builder_bee_website',
                    ...data
                });
            }
        };

        // Track button clicks
        document.querySelectorAll('button, .cta-button, .service-btn').forEach(button => {
            button.addEventListener('click', () => {
                this.trackEvent('button_click', {
                    button_text: button.textContent.trim(),
                    button_location: this.getElementLocation(button)
                });
            });
        });

        // Track scroll depth
        let maxScroll = 0;
        window.addEventListener('scroll', () => {
            const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
            if (scrollPercent > maxScroll) {
                maxScroll = scrollPercent;
                if (maxScroll % 25 === 0) { // Track at 25%, 50%, 75%, 100%
                    this.trackEvent('scroll_depth', { percent: maxScroll });
                }
            }
        });

        // Track time on page
        const startTime = Date.now();
        window.addEventListener('beforeunload', () => {
            const timeOnPage = Math.round((Date.now() - startTime) / 1000);
            this.trackEvent('time_on_page', { seconds: timeOnPage });
        });
    }

    setupPerformanceOptimizations() {
        // Preload critical resources
        const preloadLinks = [
            { href: 'css/styles.css', as: 'style' },
            { href: 'js/main.js', as: 'script' },
            { href: 'js/chat.js', as: 'script' }
        ];

        preloadLinks.forEach(link => {
            const preloadLink = document.createElement('link');
            preloadLink.rel = 'preload';
            preloadLink.href = link.href;
            preloadLink.as = link.as;
            document.head.appendChild(preloadLink);
        });

        // Optimize images
        this.optimizeImages();

        // Service Worker for caching (if supported)
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js').catch(() => {
                // Service worker registration failed, continue without it
            });
        }
    }

    optimizeImages() {
        // Convert images to WebP if supported
        const supportsWebP = () => {
            const canvas = document.createElement('canvas');
            return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
        };

        if (supportsWebP()) {
            document.querySelectorAll('img').forEach(img => {
                const webpSrc = img.src.replace(/\.(jpg|jpeg|png)$/i, '.webp');
                // Check if WebP version exists
                const testImg = new Image();
                testImg.onload = () => {
                    img.src = webpSrc;
                };
                testImg.src = webpSrc;
            });
        }
    }

    getElementLocation(element) {
        const rect = element.getBoundingClientRect();
        return {
            x: Math.round(rect.left),
            y: Math.round(rect.top),
            section: this.getCurrentSection(element)
        };
    }

    getCurrentSection(element) {
        const sections = ['hero', 'services', 'portfolio', 'reviews', 'about', 'contact'];
        for (const section of sections) {
            const sectionElement = document.getElementById(section);
            if (sectionElement && sectionElement.contains(element)) {
                return section;
            }
        }
        return 'unknown';
    }
}

// Advanced CSS animations
const advancedStyles = `
    .animate-in {
        animation: slideInUp 0.8s cubic-bezier(0.4, 0, 0.2, 1) forwards;
    }

    @keyframes slideInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .nav-hidden {
        transform: translateY(-100%);
        transition: transform 0.3s ease-in-out;
    }

    .nav-link.active {
        background: linear-gradient(135deg, #ed8936, #dd6b20) !important;
        transform: scale(1.05);
    }

    .lazy {
        opacity: 0;
        transition: opacity 0.3s;
    }

    .parallax-element {
        will-change: transform;
    }

    /* Advanced hover effects */
    .service-card {
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .portfolio-item {
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    /* Performance optimizations */
    * {
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
    }

    img {
        image-rendering: -webkit-optimize-contrast;
        image-rendering: crisp-edges;
    }
`;

// Inject advanced styles
const styleSheet = document.createElement('style');
styleSheet.textContent = advancedStyles;
document.head.appendChild(styleSheet);

// Initialize advanced features when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new AdvancedWebsiteFeatures();
    console.log('Advanced website features initialized 🚀');
});

// Export for use in other modules
window.AdvancedWebsiteFeatures = AdvancedWebsiteFeatures;

