/* ============================================
   SOCIAPI SOCIETY - Premium JavaScript
   Interactive Experience & Animations
   ============================================ */

// ============================================
// LOADING SCREEN
// ============================================
window.addEventListener('load', () => {
    const loadingScreen = document.getElementById('loading-screen');
    
    setTimeout(() => {
        loadingScreen.classList.add('hidden');
        initAnimations();
    }, 2500);
});

// ============================================
// CUSTOM CURSOR
// ============================================
const cursorWrapper = document.querySelector('.cursor-wrapper');
const cursorDot = document.querySelector('.cursor-dot');
const cursorCircle = document.querySelector('.cursor-circle');
const cursorGlow = document.querySelector('.cursor-glow');

let mouseX = 0, mouseY = 0;
let dotX = 0, dotY = 0;
let circleX = 0, circleY = 0;

// Check if not touch device
const isTouchDevice = window.matchMedia('(pointer: coarse)').matches;

if (!isTouchDevice && cursorWrapper) {
    document.addEventListener('mousemove', (e) => {
        mouseX = e.clientX;
        mouseY = e.clientY;
    });

    // Smooth cursor animation
    function animateCursor() {
        // Dot follows immediately
        dotX += (mouseX - dotX) * 0.2;
        dotY += (mouseY - dotY) * 0.2;
        
        // Circle follows with delay
        circleX += (mouseX - circleX) * 0.1;
        circleY += (mouseY - circleY) * 0.1;
        
        cursorDot.style.left = dotX + 'px';
        cursorDot.style.top = dotY + 'px';
        
        cursorCircle.style.left = circleX + 'px';
        cursorCircle.style.top = circleY + 'px';
        
        cursorGlow.style.left = circleX + 'px';
        cursorGlow.style.top = circleY + 'px';
        
        requestAnimationFrame(animateCursor);
    }
    
    animateCursor();

    // Hover effects
    const hoverElements = document.querySelectorAll('a, button, .glass-card, .tech-node, .member-card');
    hoverElements.forEach(el => {
        el.addEventListener('mouseenter', () => cursorWrapper.classList.add('hover'));
        el.addEventListener('mouseleave', () => cursorWrapper.classList.remove('hover'));
    });
}

// ============================================
// SCROLL PROGRESS
// ============================================
const scrollProgressBar = document.querySelector('.scroll-progress-bar');

window.addEventListener('scroll', () => {
    const scrollTop = window.scrollY;
    const docHeight = document.documentElement.scrollHeight - window.innerHeight;
    const scrollPercent = (scrollTop / docHeight) * 100;
    
    if (scrollProgressBar) {
        scrollProgressBar.style.width = scrollPercent + '%';
    }
});

// ============================================
// NAVIGATION
// ============================================
const mainNav = document.getElementById('mainNav');
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const mobileMenu = document.getElementById('mobileMenu');

// Scroll effect
window.addEventListener('scroll', () => {
    if (window.scrollY > 100) {
        mainNav.classList.add('scrolled');
    } else {
        mainNav.classList.remove('scrolled');
    }
});

// Mobile menu toggle
if (mobileMenuBtn && mobileMenu) {
    mobileMenuBtn.addEventListener('click', () => {
        mobileMenuBtn.classList.toggle('active');
        mobileMenu.classList.toggle('active');
    });

    // Close mobile menu on link click
    document.querySelectorAll('.mobile-link').forEach(link => {
        link.addEventListener('click', () => {
            mobileMenuBtn.classList.remove('active');
            mobileMenu.classList.remove('active');
        });
    });
}

// Active nav link on scroll
const sections = document.querySelectorAll('section[id]');
const navLinks = document.querySelectorAll('.nav-link');

window.addEventListener('scroll', () => {
    let current = '';
    
    sections.forEach(section => {
        const sectionTop = section.offsetTop;
        const sectionHeight = section.clientHeight;
        
        if (scrollY >= sectionTop - 200) {
            current = section.getAttribute('id');
        }
    });
    
    navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('href') === '#' + current) {
            link.classList.add('active');
        }
    });
});

// ============================================
// THREE.JS 3D GLOBE
// ============================================
function initGlobe() {
    const canvas = document.getElementById('globeCanvas');
    if (!canvas) return;

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
    const renderer = new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true });
    
    renderer.setSize(1000, 1000);
    renderer.setPixelRatio(window.devicePixelRatio);

    // Globe geometry
    const geometry = new THREE.IcosahedronGeometry(200, 2);
    
    // Wireframe material
    const material = new THREE.MeshBasicMaterial({
        color: 0x517642,
        wireframe: true,
        transparent: true,
        opacity: 0.6
    });
    
    const globe = new THREE.Mesh(geometry, material);
    scene.add(globe);

    // Inner glow sphere
    const glowGeometry = new THREE.IcosahedronGeometry(195, 1);
    const glowMaterial = new THREE.MeshBasicMaterial({
        color: 0x7bd355,
        transparent: true,
        opacity: 0.1
    });
    const glowSphere = new THREE.Mesh(glowGeometry, glowMaterial);
    scene.add(glowSphere);

    // Particles
    const particlesGeometry = new THREE.BufferGeometry();
    const particlesCount = 500;
    const posArray = new Float32Array(particlesCount * 3);
    
    for (let i = 0; i < particlesCount * 3; i++) {
        posArray[i] = (Math.random() - 0.5) * 800;
    }
    
    particlesGeometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
    
    const particlesMaterial = new THREE.PointsMaterial({
        size: 2,
        color: 0x7bd355,
        transparent: true,
        opacity: 0.8
    });
    
    const particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial);
    scene.add(particlesMesh);

    // Neural connections
    const connectionsGeometry = new THREE.BufferGeometry();
    const connectionsCount = 100;
    const connectionsArray = new Float32Array(connectionsCount * 6);
    
    for (let i = 0; i < connectionsCount * 6; i += 6) {
        const theta1 = Math.random() * Math.PI * 2;
        const phi1 = Math.acos(2 * Math.random() - 1);
        const r1 = 200;
        
        const theta2 = theta1 + (Math.random() - 0.5) * 0.5;
        const phi2 = phi1 + (Math.random() - 0.5) * 0.5;
        const r2 = 200;
        
        connectionsArray[i] = r1 * Math.sin(phi1) * Math.cos(theta1);
        connectionsArray[i + 1] = r1 * Math.sin(phi1) * Math.sin(theta1);
        connectionsArray[i + 2] = r1 * Math.cos(phi1);
        
        connectionsArray[i + 3] = r2 * Math.sin(phi2) * Math.cos(theta2);
        connectionsArray[i + 4] = r2 * Math.sin(phi2) * Math.sin(theta2);
        connectionsArray[i + 5] = r2 * Math.cos(phi2);
    }
    
    connectionsGeometry.setAttribute('position', new THREE.BufferAttribute(connectionsArray, 3));
    
    const connectionsMaterial = new THREE.LineBasicMaterial({
        color: 0x7bd355,
        transparent: true,
        opacity: 0.3
    });
    
    const connectionsMesh = new THREE.LineSegments(connectionsGeometry, connectionsMaterial);
    scene.add(connectionsMesh);

    camera.position.z = 500;

    // Mouse interaction
    let mouseX = 0;
    let mouseY = 0;
    let targetRotationX = 0;
    let targetRotationY = 0;

    document.addEventListener('mousemove', (e) => {
        mouseX = (e.clientX - window.innerWidth / 2) * 0.001;
        mouseY = (e.clientY - window.innerHeight / 2) * 0.001;
    });

    // Animation loop
    function animate() {
        requestAnimationFrame(animate);
        
        // Auto rotation
        globe.rotation.y += 0.002;
        glowSphere.rotation.y += 0.002;
        connectionsMesh.rotation.y += 0.002;
        
        // Mouse interaction
        targetRotationX = mouseY * 0.5;
        targetRotationY = mouseX * 0.5;
        
        globe.rotation.x += (targetRotationX - globe.rotation.x) * 0.05;
        globe.rotation.y += (targetRotationY - globe.rotation.y) * 0.05;
        
        glowSphere.rotation.x = globe.rotation.x;
        glowSphere.rotation.y = globe.rotation.y;
        connectionsMesh.rotation.x = globe.rotation.x;
        connectionsMesh.rotation.y = globe.rotation.y;
        
        // Particle animation
        particlesMesh.rotation.y += 0.0005;
        
        renderer.render(scene, camera);
    }
    
    animate();

    // Handle resize
    window.addEventListener('resize', () => {
        const size = Math.min(window.innerWidth, window.innerHeight, 1000);
        renderer.setSize(size, size);
    });
}

// ============================================
// GSAP ANIMATIONS
// ============================================
function initAnimations() {
    gsap.registerPlugin(ScrollTrigger);

    // Hero title animation
    gsap.from('.title-line-1', {
        y: 100,
        opacity: 0,
        duration: 1.2,
        ease: 'power4.out',
        delay: 0.3
    });

    gsap.from('.title-line-2', {
        y: 100,
        opacity: 0,
        duration: 1.2,
        ease: 'power4.out',
        delay: 0.5
    });

    // Hero subtitle
    gsap.from('.hero-subtitle', {
        y: 50,
        opacity: 0,
        duration: 1,
        ease: 'power3.out',
        delay: 0.8
    });

    // Hero buttons
    gsap.from('.hero-buttons .btn', {
        y: 30,
        opacity: 0,
        duration: 0.8,
        stagger: 0.1,
        ease: 'power3.out',
        delay: 1
    });

    // Hero stats counter animation
    const statNumbers = document.querySelectorAll('.stat-number');
    statNumbers.forEach(stat => {
        const target = parseInt(stat.getAttribute('data-target'));
        
        ScrollTrigger.create({
            trigger: stat,
            start: 'top 80%',
            onEnter: () => {
                gsap.to(stat, {
                    innerHTML: target,
                    duration: 2,
                    snap: { innerHTML: 1 },
                    ease: 'power2.out'
                });
            },
            once: true
        });
    });

    // Section headers
    gsap.utils.toArray('.section-header').forEach(header => {
        gsap.from(header, {
            scrollTrigger: {
                trigger: header,
                start: 'top 80%',
                toggleActions: 'play none none reverse'
            },
            y: 50,
            opacity: 0,
            duration: 0.8,
            ease: 'power3.out'
        });
    });

    // Mission cards
    gsap.from('.mission-card', {
        scrollTrigger: {
            trigger: '.about-mission',
            start: 'top 70%'
        },
        y: 60,
        opacity: 0,
        duration: 0.8,
        stagger: 0.2,
        ease: 'power3.out'
    });

    // Timeline items
    gsap.from('.timeline-item', {
        scrollTrigger: {
            trigger: '.timeline-container',
            start: 'top 70%'
        },
        x: (i) => i % 2 === 0 ? -50 : 50,
        opacity: 0,
        duration: 0.8,
        stagger: 0.3,
        ease: 'power3.out'
    });

    // Founder section
    gsap.from('.founder-photo-wrapper', {
        scrollTrigger: {
            trigger: '.founder-section',
            start: 'top 60%'
        },
        scale: 0.8,
        opacity: 0,
        duration: 1,
        ease: 'power3.out'
    });

    gsap.from('.founder-info', {
        scrollTrigger: {
            trigger: '.founder-section',
            start: 'top 60%'
        },
        x: 50,
        opacity: 0,
        duration: 1,
        delay: 0.3,
        ease: 'power3.out'
    });

    // Service cards
    gsap.from('.service-card', {
        scrollTrigger: {
            trigger: '.services-grid',
            start: 'top 70%'
        },
        y: 60,
        opacity: 0,
        duration: 0.8,
        stagger: 0.15,
        ease: 'power3.out'
    });

    // Event cards
    gsap.from('.featured-event', {
        scrollTrigger: {
            trigger: '.events-container',
            start: 'top 70%'
        },
        y: 60,
        opacity: 0,
        duration: 0.8,
        ease: 'power3.out'
    });

    gsap.from('.event-card', {
        scrollTrigger: {
            trigger: '.events-grid',
            start: 'top 70%'
        },
        y: 40,
        opacity: 0,
        duration: 0.6,
        stagger: 0.2,
        ease: 'power3.out'
    });

    // Gallery items
    gsap.from('.gallery-item', {
        scrollTrigger: {
            trigger: '.gallery-masonry',
            start: 'top 70%'
        },
        scale: 0.8,
        opacity: 0,
        duration: 0.6,
        stagger: 0.1,
        ease: 'power3.out'
    });

    // Product cards
    gsap.from('.product-card', {
        scrollTrigger: {
            trigger: '.shop-grid',
            start: 'top 70%'
        },
        y: 60,
        opacity: 0,
        duration: 0.8,
        stagger: 0.2,
        ease: 'power3.out'
    });

    // FAQ items
    gsap.from('.faq-item', {
        scrollTrigger: {
            trigger: '.faq-accordion',
            start: 'top 70%'
        },
        y: 30,
        opacity: 0,
        duration: 0.5,
        stagger: 0.1,
        ease: 'power3.out'
    });

    // Contact cards
    gsap.from('.contact-card', {
        scrollTrigger: {
            trigger: '.contact-info',
            start: 'top 70%'
        },
        y: 40,
        opacity: 0,
        duration: 0.6,
        stagger: 0.1,
        ease: 'power3.out'
    });

    gsap.from('.contact-form-wrapper', {
        scrollTrigger: {
            trigger: '.contact-container',
            start: 'top 70%'
        },
        x: 50,
        opacity: 0,
        duration: 0.8,
        delay: 0.3,
        ease: 'power3.out'
    });
}

// ============================================
// GALLERY
// ============================================
const galleryData = [
    { id: 1, title: 'Agentum 2026' },
    { id: 2, title: 'Mehfil AI 2026' },
    { id: 3, title: 'Workshop Session' },
    { id: 4, title: 'Team Meeting' },
    { id: 5, title: 'Hackathon' },
    { id: 6, title: 'Award Ceremony' },
    { id: 7, title: 'Networking Event' },
    { id: 8, title: 'Tech Talk' },
    { id: 9, title: 'Project Showcase' },
    { id: 10, title: 'Community Gathering' },
    { id: 11, title: 'AI Demo' },
    { id: 12, title: 'Robotics Lab' },
    { id: 13, title: 'Data Science Workshop' },
    { id: 14, title: 'Code Sprint' },
    { id: 15, title: 'Mentorship Session' },
    { id: 16, title: 'Industry Visit' },
    { id: 17, title: 'Panel Discussion' },
    { id: 18, title: 'Certificate Distribution' },
    { id: 19, title: 'Team Building' },
    { id: 20, title: 'Innovation Lab' },
    { id: 21, title: 'Research Presentation' },
    { id: 22, title: 'Graduation Ceremony' }
];

function initGallery() {
    const galleryMasonry = document.getElementById('galleryMasonry');
    if (!galleryMasonry) return;

    galleryData.forEach((item, index) => {
        const galleryItem = document.createElement('div');
        galleryItem.className = 'gallery-item';
        galleryItem.innerHTML = `
            <div class="gallery-placeholder">
                <i data-lucide="image"></i>
            </div>
            <div class="gallery-overlay">
                <span class="gallery-overlay-text">${item.title}</span>
            </div>
        `;
        galleryItem.addEventListener('click', () => openLightbox(index));
        galleryMasonry.appendChild(galleryItem);
    });

    // Re-initialize Lucide icons
    lucide.createIcons();
}

// Lightbox
let currentImageIndex = 0;
const lightbox = document.getElementById('lightbox');
const lightboxImage = document.getElementById('lightboxImage');

function openLightbox(index) {
    currentImageIndex = index;
    updateLightbox();
    lightbox.classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeLightbox() {
    lightbox.classList.remove('active');
    document.body.style.overflow = '';
}

function updateLightbox() {
    // In a real implementation, this would show actual images
    lightboxImage.src = ''; // Placeholder
    lightboxImage.alt = galleryData[currentImageIndex].title;
}

function nextImage() {
    currentImageIndex = (currentImageIndex + 1) % galleryData.length;
    updateLightbox();
}

function prevImage() {
    currentImageIndex = (currentImageIndex - 1 + galleryData.length) % galleryData.length;
    updateLightbox();
}

// Lightbox event listeners
document.getElementById('lightboxClose')?.addEventListener('click', closeLightbox);
document.getElementById('lightboxNext')?.addEventListener('click', nextImage);
document.getElementById('lightboxPrev')?.addEventListener('click', prevImage);

// Close on background click
lightbox?.addEventListener('click', (e) => {
    if (e.target === lightbox) closeLightbox();
});

// Keyboard navigation
document.addEventListener('keydown', (e) => {
    if (!lightbox?.classList.contains('active')) return;
    
    if (e.key === 'Escape') closeLightbox();
    if (e.key === 'ArrowRight') nextImage();
    if (e.key === 'ArrowLeft') prevImage();
});

// ============================================
// SHOP & CART
// ============================================
let cart = JSON.parse(localStorage.getItem('sociapiCart')) || [];

function updateCartCount() {
    const cartCount = document.getElementById('cartCount');
    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
    if (cartCount) {
        cartCount.textContent = totalItems;
        cartCount.style.display = totalItems > 0 ? 'flex' : 'none';
    }
}

function addToCart(product, size, quantity, price) {
    const existingItem = cart.find(item => item.product === product && item.size === size);
    
    if (existingItem) {
        existingItem.quantity += quantity;
    } else {
        cart.push({ product, size, quantity, price });
    }
    
    localStorage.setItem('sociapiCart', JSON.stringify(cart));
    updateCartCount();
    showToast('Added to cart!');
}

function removeFromCart(index) {
    cart.splice(index, 1);
    localStorage.setItem('sociapiCart', JSON.stringify(cart));
    updateCartCount();
    renderCart();
}

function renderCart() {
    const cartItems = document.getElementById('cartItems');
    const cartTotal = document.getElementById('cartTotal');
    
    if (!cartItems) return;
    
    cartItems.innerHTML = '';
    
    let total = 0;
    
    cart.forEach((item, index) => {
        const itemTotal = item.price * item.quantity;
        total += itemTotal;
        
        const cartItem = document.createElement('div');
        cartItem.className = 'cart-item';
        cartItem.innerHTML = `
            <div class="cart-item-image">
                <i data-lucide="shirt"></i>
            </div>
            <div class="cart-item-details">
                <h4>${item.product}</h4>
                <p>Size: ${item.size} | Qty: ${item.quantity}</p>
                <div class="cart-item-price">PKR ${itemTotal.toLocaleString()}</div>
            </div>
            <button class="remove-item" data-index="${index}">
                <i data-lucide="x"></i>
            </button>
        `;
        cartItems.appendChild(cartItem);
    });
    
    if (cartTotal) {
        cartTotal.textContent = 'PKR ' + total.toLocaleString();
    }
    
    // Re-initialize Lucide icons
    lucide.createIcons();
    
    // Add remove listeners
    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const index = parseInt(e.currentTarget.dataset.index);
            removeFromCart(index);
        });
    });
}

// Cart sidebar toggle
const cartFab = document.getElementById('cartFab');
const cartSidebar = document.getElementById('cartSidebar');
const cartOverlay = document.getElementById('cartOverlay');
const cartClose = document.getElementById('cartClose');

function openCart() {
    cartSidebar?.classList.add('active');
    cartOverlay?.classList.add('active');
    document.body.style.overflow = 'hidden';
    renderCart();
}

function closeCart() {
    cartSidebar?.classList.remove('active');
    cartOverlay?.classList.remove('active');
    document.body.style.overflow = '';
}

cartFab?.addEventListener('click', openCart);
cartClose?.addEventListener('click', closeCart);
cartOverlay?.addEventListener('click', closeCart);

// Checkout
document.getElementById('checkoutBtn')?.addEventListener('click', () => {
    if (cart.length === 0) {
        showToast('Your cart is empty!');
        return;
    }
    
    let message = 'Hello! I would like to order:\\n\\n';
    let total = 0;
    
    cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        total += itemTotal;
        message += `${item.product} (${item.size}) x${item.quantity} - PKR ${itemTotal.toLocaleString()}\\n`;
    });
    
    message += `\\nTotal: PKR ${total.toLocaleString()}`;
    
    const whatsappUrl = `https://wa.me/92XXXXXXXXXX?text=${encodeURIComponent(message)}`;
    window.open(whatsappUrl, '_blank');
});

// Product card interactions
document.querySelectorAll('.product-card').forEach(card => {
    const minusBtn = card.querySelector('.qty-btn.minus');
    const plusBtn = card.querySelector('.qty-btn.plus');
    const qtyValue = card.querySelector('.qty-value');
    const sizeBtns = card.querySelectorAll('.size-btn');
    const addToCartBtn = card.querySelector('.add-to-cart');
    
    let quantity = 1;
    let selectedSize = 'M';
    
    minusBtn?.addEventListener('click', () => {
        if (quantity > 1) {
            quantity--;
            qtyValue.textContent = quantity;
        }
    });
    
    plusBtn?.addEventListener('click', () => {
        if (quantity < 10) {
            quantity++;
            qtyValue.textContent = quantity;
        }
    });
    
    sizeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            sizeBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            selectedSize = btn.dataset.size;
        });
    });
    
    addToCartBtn?.addEventListener('click', () => {
        const productName = card.querySelector('h3').textContent;
        const priceText = card.querySelector('.product-price').textContent;
        const price = parseInt(priceText.replace(/[^0-9]/g, ''));
        
        addToCart(productName, selectedSize, quantity, price);
        quantity = 1;
        qtyValue.textContent = quantity;
    });
});

// ============================================
// REVIEWS CAROUSEL
// ============================================
const reviewCards = document.querySelectorAll('.review-card');
const reviewDots = document.querySelectorAll('.review-dots .dot');
let currentReview = 0;
let reviewInterval;

function showReview(index) {
    reviewCards.forEach((card, i) => {
        card.classList.remove('active');
        if (i === index) {
            card.classList.add('active');
        }
    });
    
    reviewDots.forEach((dot, i) => {
        dot.classList.remove('active');
        if (i === index) {
            dot.classList.add('active');
        }
    });
    
    currentReview = index;
}

function nextReview() {
    showReview((currentReview + 1) % reviewCards.length);
}

function prevReview() {
    showReview((currentReview - 1 + reviewCards.length) % reviewCards.length);
}

function startReviewAutoplay() {
    reviewInterval = setInterval(nextReview, 5000);
}

function stopReviewAutoplay() {
    clearInterval(reviewInterval);
}

document.getElementById('reviewNext')?.addEventListener('click', () => {
    stopReviewAutoplay();
    nextReview();
    startReviewAutoplay();
});

document.getElementById('reviewPrev')?.addEventListener('click', () => {
    stopReviewAutoplay();
    prevReview();
    startReviewAutoplay();
});

reviewDots.forEach((dot, index) => {
    dot.addEventListener('click', () => {
        stopReviewAutoplay();
        showReview(index);
        startReviewAutoplay();
    });
});

// ============================================
// FAQ ACCORDION
// ============================================
const faqQuestions = document.querySelectorAll('.faq-question');

faqQuestions.forEach(question => {
    question.addEventListener('click', () => {
        const answer = question.nextElementSibling;
        const isActive = question.classList.contains('active');
        
        // Close all others
        faqQuestions.forEach(q => {
            q.classList.remove('active');
            q.nextElementSibling.classList.remove('active');
        });
        
        // Toggle current
        if (!isActive) {
            question.classList.add('active');
            answer.classList.add('active');
        }
    });
});

// FAQ Search
const faqSearch = document.getElementById('faqSearch');
const faqItems = document.querySelectorAll('.faq-item');

faqSearch?.addEventListener('input', (e) => {
    const searchTerm = e.target.value.toLowerCase();
    
    faqItems.forEach(item => {
        const question = item.querySelector('.faq-question span').textContent.toLowerCase();
        const answer = item.querySelector('.faq-answer p').textContent.toLowerCase();
        
        if (question.includes(searchTerm) || answer.includes(searchTerm)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
});

// FAQ Categories
const faqCatBtns = document.querySelectorAll('.faq-cat-btn');

faqCatBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        faqCatBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        
        const category = btn.dataset.category;
        
        faqItems.forEach(item => {
            if (category === 'all' || item.dataset.category === category) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
});

// ============================================
// CONTACT FORM
// ============================================
const contactForm = document.getElementById('contactForm');

contactForm?.addEventListener('submit', (e) => {
    e.preventDefault();
    
    const formData = new FormData(contactForm);
    const data = Object.fromEntries(formData);
    
    // Simulate form submission
    showToast('Message sent successfully!');
    contactForm.reset();
});

// ============================================
// NEWSLETTER
// ============================================
const newsletterForm = document.getElementById('newsletterForm');

newsletterForm?.addEventListener('submit', (e) => {
    e.preventDefault();
    showToast('Subscribed successfully!');
    newsletterForm.reset();
});

// ============================================
// TOAST NOTIFICATION
// ============================================
function showToast(message) {
    const toast = document.getElementById('toast');
    const toastMessage = toast.querySelector('.toast-message');
    
    toastMessage.textContent = message;
    toast.classList.add('active');
    
    setTimeout(() => {
        toast.classList.remove('active');
    }, 3000);
}

// ============================================
// SMOOTH SCROLL
// ============================================
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        
        if (target) {
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// ============================================
// PARALLAX EFFECTS
// ============================================
window.addEventListener('scroll', () => {
    const scrolled = window.scrollY;
    
    // Parallax for hero elements
    const heroVideo = document.querySelector('.hero-video');
    if (heroVideo) {
        heroVideo.style.transform = `translateY(${scrolled * 0.5}px)`;
    }
    
    // Parallax for tech nodes
    const techNodes = document.querySelector('.tech-nodes-container');
    if (techNodes) {
        techNodes.style.transform = `translate(-50%, -50%) rotate(${scrolled * 0.02}deg)`;
    }
});

// ============================================
// INITIALIZATION
// ============================================
document.addEventListener('DOMContentLoaded', () => {
    // Initialize Lucide icons
    lucide.createIcons();
    
    // Initialize 3D Globe
    initGlobe();
    
    // Initialize Gallery
    initGallery();
    
    // Update cart count
    updateCartCount();
    
    // Start review autoplay
    if (reviewCards.length > 0) {
        startReviewAutoplay();
    }
    
    // Join Community button
    document.getElementById('joinBtn')?.addEventListener('click', () => {
        document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' });
    });
    
    document.getElementById('heroJoinBtn')?.addEventListener('click', () => {
        document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' });
    });
    
    // Explore button
    document.getElementById('exploreBtn')?.addEventListener('click', () => {
        document.getElementById('services')?.scrollIntoView({ behavior: 'smooth' });
    });
    
    // Watch Journey button
    document.getElementById('watchBtn')?.addEventListener('click', () => {
        showToast('Video coming soon!');
    });
});

// Re-initialize icons after dynamic content
window.addEventListener('load', () => {
    lucide.createIcons();
});