// Product Data
const products = [
    {
        id: 1,
        name: "Velocity Pro Runner",
        brand: "Velocity",
        category: "running",
        price: 129.99,
        originalPrice: 159.99,
        rating: 4.8,
        reviews: 124,
        image: "https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=600&h=600&fit=crop",
        colors: ["#E85D2C", "#ef4444", "#1e293b"],
        sizes: [7, 8, 9, 10, 11, 12],
        isBestSeller: true,
        newest: false,
        popularity: 98
    },
    {
        id: 2,
        name: "Urban Glide Sneaker",
        brand: "Urban",
        category: "casual",
        price: 89.99,
        originalPrice: null,
        rating: 4.5,
        reviews: 86,
        image: "https://images.unsplash.com/photo-1549298916-b41d501d3772?w=600&h=600&fit=crop",
        colors: ["#64748b", "#1e293b"],
        sizes: [8, 9, 10, 11],
        isBestSeller: true,
        newest: true,
        popularity: 85
    },
    {
        id: 3,
        name: "SkyJump Basketball Elite",
        brand: "SkyJump",
        category: "basketball",
        price: 149.99,
        originalPrice: 179.99,
        rating: 4.9,
        reviews: 52,
        image: "https://images.unsplash.com/photo-1595950653106-6c9ebd614d3a?w=600&h=600&fit=crop",
        colors: ["#f59e0b", "#1e293b", "#ffffff"],
        sizes: [9, 10, 11, 12, 13],
        isBestSeller: false,
        newest: true,
        popularity: 92
    },
    {
        id: 4,
        name: "CloudWalk Lifestyle",
        brand: "CloudWalk",
        category: "lifestyle",
        price: 110.00,
        originalPrice: null,
        rating: 4.7,
        reviews: 210,
        image: "https://images.unsplash.com/photo-1600185365926-3a2ce3cdb9eb?w=600&h=600&fit=crop",
        colors: ["#ffffff", "#e2e8f0"],
        sizes: [7, 8, 9, 10, 11],
        isBestSeller: true,
        newest: false,
        popularity: 95
    }
];

// State Management
let cart = JSON.parse(localStorage.getItem('stride_cart')) || [];
let wishlist = JSON.parse(localStorage.getItem('stride_wishlist')) || [];
let currentFilters = {
    category: 'all',
    size: null,
    brand: 'all',
    priceRange: [0, 500]
};
let currentSort = 'popularity';

// DOM Elements
const cartBtn = document.getElementById('cartBtn');
const cartOverlay = document.getElementById('cartOverlay');
const cartModal = document.getElementById('cartModal');
const cartClose = document.getElementById('cartClose');
const cartItemsContainer = document.getElementById('cartItems');
const cartBadge = document.getElementById('cartBadge');
const cartTotal = document.getElementById('cartSubtotal');
const menuToggle = document.getElementById('menuToggle');
const mobileNav = document.getElementById('mobileNav');
const header = document.getElementById('header');
const bestSellersGrid = document.getElementById('bestSellersGrid');
const allProductsGrid = document.getElementById('allProductsGrid');
const searchInput = document.getElementById('searchInput');

// Initialize
document.addEventListener('DOMContentLoaded', () => {

// Hide preloader after page load
window.addEventListener('load', () => {
  setTimeout(() => {
    const preloader = document.getElementById('preloader');
    if (preloader) preloader.classList.add('hidden');
  }, 1400);
});

    lucide.createIcons();
    renderProducts();
    updateCartUI();
    updateWishlistBadge();
    initScrollReveal();
    setupEventListeners();
    setupCategoryTabs();
    registerServiceWorker();
});

// PWA Service Worker Registration
function registerServiceWorker() {
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register('/sw.js')
                .then(reg => console.log('SW registered'))
                .catch(err => console.log('SW registration failed', err));
        });
    }
}

// Navigation Logic
function navigateTo(pageId) {
    document.querySelectorAll('.page').forEach(page => {
        page.classList.remove('active');
    });
    const targetPage = document.getElementById(pageId);
    if (targetPage) targetPage.classList.add('active');

    document.querySelectorAll('.nav-link, .mobile-nav-link').forEach(link => {
        if (link.dataset.page === pageId) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });

    if (mobileNav && mobileNav.classList.contains('open')) {
        toggleMobileNav();
    }

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

// Mobile Nav Toggle
function toggleMobileNav() {
    mobileNav.classList.toggle('open');
    const spans = menuToggle.querySelectorAll('span');
    if (mobileNav.classList.contains('open')) {
        spans[0].style.transform = 'rotate(45deg) translate(5px, 5px)';
        spans[1].style.opacity = '0';
        spans[2].style.transform = 'rotate(-45deg) translate(5px, -5px)';
    } else {
        spans[0].style.transform = 'none';
        spans[1].style.opacity = '1';
        spans[2].style.transform = 'none';
    }
}

// Cart Logic
function toggleCart() {
    cartOverlay.classList.toggle('open');
    cartModal.classList.toggle('open');
}

function addToCart(productId) {
    const product = products.find(p => p.id === productId);
    const existingItem = cart.find(item => item.id === productId);

    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({ ...product, quantity: 1 });
    }

    saveCart();
    updateCartUI();
    initScrollReveal();
    showToast(`${product.name} added to cart!`);
}

function removeFromCart(productId) {
    cart = cart.filter(item => item.id !== productId);
    saveCart();
    updateCartUI();
    initScrollReveal();
}

function updateQuantity(productId, delta) {
    const item = cart.find(item => item.id === productId);
    if (item) {
        item.quantity += delta;
        if (item.quantity <= 0) {
            removeFromCart(productId);
        } else {
            saveCart();
            updateCartUI();
    initScrollReveal();
        }
    }
}

function saveCart() {
    localStorage.setItem('stride_cart', JSON.stringify(cart));
}

function updateCartUI() {
    if (!cartBadge || !cartItemsContainer || !cartTotal) return;

    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
    cartBadge.textContent = totalItems;
    cartBadge.classList.toggle('show', totalItems > 0);

    if (cart.length === 0) {
        cartItemsContainer.innerHTML = `
            <div class="cart-empty">
                <i data-lucide="shopping-bag"></i>
                <p>Your cart is empty</p>
                <button class="btn btn-outline" onclick="toggleCart(); navigateTo('products')">Start Shopping</button>
            </div>
        `;
    } else {
        cartItemsContainer.innerHTML = cart.map(item => `
            <div class="cart-item">
                <div class="cart-item-image">
                    <img src="${item.image}" alt="${item.name}">
                </div>
                <div class="cart-item-details">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-meta">Size: 10 | Color: Standard</div>
                    <div class="cart-item-price">$${item.price.toFixed(2)}</div>
                    <div class="cart-item-qty">
                        <button class="cart-qty-btn" onclick="updateQuantity(${item.id}, -1)">-</button>
                        <span>${item.quantity}</span>
                        <button class="cart-qty-btn" onclick="updateQuantity(${item.id}, 1)">+</button>
                    </div>
                </div>
                <button class="cart-item-remove" onclick="removeFromCart(${item.id})">
                    <i data-lucide="trash-2" style="width:18px;height:18px;"></i>
                </button>
            </div>
        `).join('');
    }

    const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    cartTotal.textContent = `$${total.toFixed(2)}`;
    lucide.createIcons();
}

// Product Rendering & Filtering
function renderProducts() {
    if (bestSellersGrid) {
        const bestSellers = products.filter(p => p.isBestSeller);
        bestSellersGrid.innerHTML = bestSellers.map(p => createProductCard(p)).join('');
    }

    if (allProductsGrid) {
        let filtered = products.filter(p => {
            const matchesCategory = currentFilters.category === 'all' || p.category === currentFilters.category;
            const matchesBrand = currentFilters.brand === 'all' || p.brand.toLowerCase() === currentFilters.brand;
            const matchesPrice = p.price >= currentFilters.priceRange[0] && p.price <= currentFilters.priceRange[1];
            const matchesSearch = !searchInput || p.name.toLowerCase().includes(searchInput.value.toLowerCase());
            return matchesCategory && matchesBrand && matchesPrice && matchesSearch;
        });

        filtered.sort((a, b) => {
            if (currentSort === 'price-low') return a.price - b.price;
            if (currentSort === 'price-high') return b.price - a.price;
            if (currentSort === 'newest') return (b.newest ? 1 : 0) - (a.newest ? 1 : 0);
            return b.popularity - a.popularity;
        });

        allProductsGrid.innerHTML = filtered.map(p => createProductCard(p)).join('');
    }
    lucide.createIcons();
}

function createProductCard(product) {
    return `
        <div class="product-card">
            <div class="product-image">
                <img src="${product.image}" alt="${product.name}" loading="lazy">
                ${product.isBestSeller ? '<span class="product-badge">Best Seller</span>' : ''}
                <div class="product-actions">
                    <button class="product-action-btn" aria-label="Add to Wishlist"><i data-lucide="heart" style="width:18px;height:18px;"></i></button>
                </div>
                <button class="quick-add" onclick="addToCart(${product.id})">Quick Add</button>
            </div>
            <div class="product-info">
                <div class="product-brand">${product.brand}</div>
                <h3 class="product-name"><a href="product-detail.html?id=${product.id}">${product.name}</a></h3>
                <div class="product-rating">
                    <div class="stars">
                        ${Array(5).fill(0).map((_, i) => `<i data-lucide="star" style="width:12px;height:12px;${i < Math.floor(product.rating) ? 'fill:currentColor;' : ''}"></i>`).join('')}
                    </div>
                    <span class="rating-count">(${product.reviews})</span>
                </div>
                <div class="product-price">
                    <span class="current-price">$${product.price.toFixed(2)}</span>
                    ${product.originalPrice ? `<span class="original-price">$${product.originalPrice.toFixed(2)}</span>` : ''}
                </div>
            </div>
        </div>
    `;
}

// Event Listeners
function setupEventListeners() {
    window.addEventListener('scroll', () => {
        if (header) header.classList.toggle('scrolled', window.scrollY > 50);
        updateActiveLink();
    });

    if (cartBtn) cartBtn.onclick = toggleCart;
    if (cartClose) cartClose.onclick = toggleCart;
    if (cartOverlay) cartOverlay.onclick = toggleCart;
    if (menuToggle) menuToggle.onclick = toggleMobileNav;

    document.querySelectorAll('.filter-option').forEach(option => {
        option.onclick = () => {
            const filter = option.dataset.filter;
            const value = option.dataset.value;

            document.querySelectorAll(`.filter-option[data-filter="${filter}"]`).forEach(opt => opt.classList.remove('active'));
            option.classList.add('active');

            currentFilters[filter] = value;
            renderProducts();
        };
    });

    const sortSelect = document.querySelector('.sort-select');
    if (sortSelect) {
        sortSelect.onchange = (e) => {
            currentSort = e.target.value;
            renderProducts();
        };
    }

    if (searchInput) {
        searchInput.oninput = renderProducts;
    }

    // Smooth scroll for anchors
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
                // If it's a page link, also navigateTo
                if (this.dataset.page) {
                    navigateTo(targetId);
                }
            }
        });
    });
}

function updateActiveLink() {
    const sections = document.querySelectorAll('section[id], .page[id]');
    let current = 'home';

    sections.forEach(section => {
        const sectionTop = section.offsetTop;
        if (window.scrollY >= sectionTop - 150) {
            current = section.getAttribute('id');
        }
    });

    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.toggle('active', link.dataset.page === current);
    });
}

// Form Handlers
function handleNewsletterSubmit(e) {
    e.preventDefault();
    const input = e.target.querySelector('input');
    if (validateEmail(input.value)) {
        showToast('Successfully subscribed to newsletter!');
        input.value = '';
    } else {
        showToast('Please enter a valid email address', true);
    }
}

function handleContactSubmit(e) {
    e.preventDefault();
    const form = e.target;
    let isValid = true;

    const inputs = form.querySelectorAll('input, textarea');
    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.parentElement.classList.add('error');
            isValid = false;
        } else {
            input.parentElement.classList.remove('error');
        }
    });

    if (isValid) {
        showToast('Message sent successfully!');
        form.reset();
    } else {
        showToast('Please fill in all fields', true);
    }
}

function validateEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// Utils
function showToast(message, isError = false) {
    const container = document.querySelector('.toast-container');
    if (!container) return;

    const toast = document.createElement('div');
    toast.className = `toast ${isError ? 'error' : ''}`;
    toast.innerHTML = `
        <i data-lucide="${isError ? 'alert-circle' : 'check-circle'}" style="width:20px;height:20px;"></i>
        <span>${message}</span>
    `;
    container.appendChild(toast);

    setTimeout(() => toast.classList.add('show'), 10);
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
    lucide.createIcons();
}

// Search Modal
function openSearch() {
    showToast('Search feature coming soon!');
}

// Wishlist Functions
function openWishlist() {
    const wishlistBadge = document.getElementById('wishlistBadge');
    const count = wishlist.length;
    
    if (count === 0) {
        showToast('Your wishlist is empty');
        return;
    }
    
    showToast(`You have ${count} item${count > 1 ? 's' : ''} in wishlist`);
}

function addToWishlist(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) return;
    
    const exists = wishlist.find(item => item.id === productId);
    
    if (exists) {
        wishlist = wishlist.filter(item => item.id !== productId);
        showToast(`${product.name} removed from wishlist`);
    } else {
        wishlist.push(product);
        showToast(`${product.name} added to wishlist!`);
    }
    
    localStorage.setItem('stride_wishlist', JSON.stringify(wishlist));
    updateWishlistBadge();
}

function updateWishlistBadge() {
    const wishlistBadge = document.getElementById('wishlistBadge');
    if (wishlistBadge) {
        wishlistBadge.textContent = wishlist.length;
        wishlistBadge.classList.toggle('show', wishlist.length > 0);
    }
}

// Theme Toggle
function toggleTheme() {
    const current = document.documentElement.getAttribute('data-theme');
    const next = current === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    localStorage.setItem('stride_theme', next);
    showToast(`${next === 'dark' ? '🌙 Dark' : '☀️ Light'} mode activated`);
}

// Category Tabs
function setupCategoryTabs() {
    const tabs = document.querySelectorAll('.vercel-tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            tabs.forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            
            const category = tab.dataset.category;
            currentFilters.category = category;
            renderProducts();
        });
    });
}


// === SCROLL REVEAL ANIMATIONS ===
function initScrollReveal() {
  const revealElements = document.querySelectorAll(
    '.section-header, .product-card, .collection-card, .testimonial-card, .story-feature, .value-card, .timeline-item, .contact-info-card, .hero-text, .hero-image, .story-text, .story-image'
  );

  const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        entry.target.classList.add('revealed');
        revealObserver.unobserve(entry.target);
      }
    });
  }, { threshold: 0.15, rootMargin: '0px 0px -50px 0px' });

  revealElements.forEach((el, index) => {
    el.classList.add('reveal-element');
    el.style.transitionDelay = `${(index % 6) * 0.1}s`;
    revealObserver.observe(el);
  });
}
