// Configuration
const PRODUCTS_PER_PAGE = 10;

// Local products data
const ALL_PRODUCTS = [
  {
    "id": 0,
    "title": "EchoPulse",
    "price": 249.0,
    "description": "Wireless headphones with ANC tech.",
    "category": "Electronics",
    "image": "images/EchoPulse-60641a51d0588eb322d2a22952e4564f7f3952dec1a605ec0650cda71f4d01b2.png"
  },
  {
    "id": 1,
    "title": "NovaBeam",
    "price": 799.0,
    "description": "Ultra-slim 4K smart projector.",
    "category": "Electronics",
    "image": "images/NovaBeam-0d5d73a16eb2c48535c3e6517085f0bf6806bcd9a0e53f8b0c9b35b5f5b8cf32.png"
  },
  {
    "id": 2,
    "title": "ZenithFlex",
    "price": 1499.0,
    "description": "Foldable OLED laptop, lightweight.",
    "category": "Electronics",
    "image": "images/ZenithFlex-792e8405917c10005cadd747087fac97403c6c563c3439f295eaf30b75862c12.png"
  },
  {
    "id": 3,
    "title": "PixelWave",
    "price": 999.0,
    "description": "Smartphone with holographic display.",
    "category": "Electronics",
    "image": "images/PixelWave-c93c71f1c8eafcbce69932b8726dcad9d65ab949eacc5569c1fa99279be057e1.png"
  },
  {
    "id": 20,
    "title": "Lumina Loft",
    "price": 49.99,
    "description": "Elegant LED wall sconces.",
    "category": "Home & Kitchen",
    "image": "images/Lumina Loft-1cf308af6ea5b08af48702d694c2c9de783bd9ed29b521b5e0f1984a9b10235a.png"
  },
  {
    "id": 21,
    "title": "Zenith Couch",
    "price": 799.0,
    "description": "Modern modular sofa design.",
    "category": "Home & Kitchen",
    "image": "images/Zenith Couch-0b94e8e661fc6ebd592deac0211b4acde7b30a8226937369bd2d44c86c325141.png"
  },
  {
    "id": 22,
    "title": "AquaBlend Mixer",
    "price": 129.95,
    "description": "Smart mixer with app control.",
    "category": "Home & Kitchen",
    "image": "images/AquaBlend Mixer-a82c4e580c3c86976d5ca13c5f903536dcec2108ff10d3affeae99edf19b64bb.png"
  },
  {
    "id": 23,
    "title": "EcoVase Set",
    "price": 34.5,
    "description": "Sustainable bamboo vases trio.",
    "category": "Home & Kitchen",
    "image": "images/EcoVase Set-15ed83c48c3927c3341688622eab7abd1b358c2690987b21861db4c4e7a4d122.png"
  },
  {
    "id": 24,
    "title": "NeonBar Cart",
    "price": 249.0,
    "description": "Sleek bar trolley with lights.",
    "category": "Home & Kitchen",
    "image": "images/NeonBar Cart-effc2b8ee848cc7edd56fb8492332a0c9cf0f05ebad3074c212630ce2c8d1a15.png"
  },
  {
    "id": 30,
    "title": "GlowFuse Elixir",
    "price": 35.0,
    "description": "Illuminate skin with natural extracts.",
    "category": "Beauty & Personal Care",
    "image": "images/GlowFuse Elixir-49ed87163f0d8529e81675ebe7aca757a6f9a2fcb15c4eccc9ccf2a8abf820d2.png"
  },
  {
    "id": 31,
    "title": "SilkLock Curls",
    "price": 22.0,
    "description": "Define curls effortlessly all day.",
    "category": "Beauty & Personal Care",
    "image": "images/SilkLock Curls-ccc259cb9196365971022c40f7c2160f3f5871463f84abac26d9af8eb6693601.png"
  },
  {
    "id": 32,
    "title": "VelvetMist Spray",
    "price": 28.0,
    "description": "Set makeup with a silky finish.",
    "category": "Beauty & Personal Care",
    "image": "images/VelvetMist Spray-2d1977e8bf1bde862b609f806208e668216035680c2ca8acfd87dfa3add53488.png"
  },
  {
    "id": 33,
    "title": "PureZen Mask",
    "price": 19.0,
    "description": "Deep clean and rejuvenate skin.",
    "category": "Beauty & Personal Care",
    "image": "images/PureZen Mask-3e535bc3bc59ee5b07ebd12a89338a374da47cbeff09134205f261258ef47537.png"
  },
  {
    "id": 34,
    "title": "RadiantGlow Tint",
    "price": 24.0,
    "description": "Sheer tint for a natural flush.",
    "category": "Beauty & Personal Care",
    "image": "images/RadiantGlow Tint-d77ce064994d5b9810920b34875caa8dff33ae3f4544acee26f537ecf79dae74.png"
  },
  {
    "id": 40,
    "title": "ZenSpray",
    "price": 14.99,
    "description": "Instant calm in a spray bottle.",
    "category": "Health & Household",
    "image": "images/ZenSpray-b3ac3a681025e49194a9fa8b67e93c34d2fbb85a76e43ff37fe455f124aee9ac.png"
  },
  {
    "id": 41,
    "title": "PureHush",
    "price": 29.95,
    "description": "White noise machine for infants.",
    "category": "Health & Household",
    "image": "images/PureHush-c1eda73b66a25e096e1c45360d378650caf8e126461bb7517466ab8a09995172.png"
  },
  {
    "id": 42,
    "title": "EcoScrub",
    "price": 4.75,
    "description": "Biodegradable sponge for dishes.",
    "category": "Health & Household",
    "image": "images/EcoScrub-e9dcd8e93f9ce2f05f6f9de7cacdae34bff30e9ef03016297e37a9021088828c.png"
  },
  {
    "id": 43,
    "title": "GlowBand",
    "price": 19.5,
    "description": "UV light sanitizer bracelet.",
    "category": "Health & Household",
    "image": "images/GlowBand-49f731904a6d5ca6611b66a90a1dba0209070540f5645f365cbda987982d3096.png"
  },
  {
    "id": 44,
    "title": "SoftNest",
    "price": 32.0,
    "description": "Organic cotton baby blanket.",
    "category": "Health & Household",
    "image": "images/SoftNest-67d2dd30eb1fd161e5ac79f67db1cd1b70560cf3662eb197fb6d938349fce643.png"
  },
  {
    "id": 50,
    "title": "ZenGlide",
    "price": 79.99,
    "description": "Revolutionary yoga mat technology.",
    "category": "Sports & Outdoors",
    "image": "images/ZenGlide-043cc1315ffddac9910931faf060e5a1e5e698f1b55fd20eed495d4ee4214f33.png"
  },
  {
    "id": 51,
    "title": "AquaStride",
    "price": 34.5,
    "description": "Compact water shoes for adventures.",
    "category": "Sports & Outdoors",
    "image": "images/AquaStride-3a328bb000a68a3dc387c7556a19324d426ac05efedf0045085d335564085216.png"
  },
  {
    "id": 52,
    "title": "AeroPeak",
    "price": 59.95,
    "description": "Lightweight hiking poles for pros.",
    "category": "Sports & Outdoors",
    "image": "images/AeroPeak-311616e387a6a4683d21c8a595fc898e432d09c0419cc810dedf5c59494c996f.png"
  },
  {
    "id": 53,
    "title": "FlexiRun",
    "price": 22.75,
    "description": "Dynamic resistance bands set.",
    "category": "Sports & Outdoors",
    "image": "images/FlexiRun-4012e6b2f59d739a083b8d723d85b863d38ec9f205ee45e33560c59e7f3f5a20.png"
  },
  {
    "id": 54,
    "title": "SkyBounce",
    "price": 349.0,
    "description": "High-performance trampoline for backyards.",
    "category": "Sports & Outdoors",
    "image": "images/SkyBounce-a2f6252826d51a0dcdabce964e67d4604789232e85a57f65cc9fce994e3a8573.png"
  },
  {
    "id": 60,
    "title": "StarQuest Puzzles",
    "price": 19.99,
    "description": "Solve cosmic mysteries piece-by-piece.",
    "category": "Toys & Games",
    "image": "images/StarQuest Puzzles-f1ec110f6705cf89316e5588e84d4b960d2c90b9d12ff9b7e0c0295e57a355a2.png"
  },
  {
    "id": 61,
    "title": "FlutterWings",
    "price": 24.95,
    "description": "Magical butterflies that light up!",
    "category": "Toys & Games",
    "image": "images/FlutterWings-a47e8eb285a943c1fa46b986122a4aeb49adcac5192b019a7349f85803f32c1e.png"
  },
  {
    "id": 65,
    "title": "RoboRacers",
    "price": 27.99,
    "description": "Speedy robots that zoom and glow.",
    "category": "Toys & Games",
    "image": "images/RoboRacers-b28dd67c71067a590fdb6523dc4f40ee4a946ecf55a488dfdff853640d217efa.png"
  },
  {
    "id": 66,
    "title": "AquaQuest",
    "price": 32.5,
    "description": "Dive into underwater treasure hunts.",
    "category": "Toys & Games",
    "image": "images/AquaQuest-7b5a967e587a395077e5e5203403c506f524fd6ead8d0c52ea0bee38e2a16b21.png"
  },
  {
    "id": 69,
    "title": "JungleJump",
    "price": 21.99,
    "description": "Swing through the jungle adventure.",
    "category": "Toys & Games",
    "image": "images/JungleJump-4465aebaafd359c51be6f3b159727e7001bfee53ffbfd0b5ccdb6b4166813ed4.png"
  },
  {
    "id": 70,
    "title": "TurboGlow",
    "price": 45.99,
    "description": "Illuminate your ride with style.",
    "category": "Automotive",
    "image": "images/TurboGlow-a146df0906cd161f83e7a4c7a304862f0cdeed8cdc73b561f745e32040911be3.png"
  },
  {
    "id": 71,
    "title": "EcoShield",
    "price": 129.95,
    "description": "Eco-friendly windshield for clarity.",
    "category": "Automotive",
    "image": "images/EcoShield-97c5cd20c048739cf09918538ac64758718bf20b68158c3c8d2861888a24dc71.png"
  },
  {
    "id": 72,
    "title": "NitroPulse",
    "price": 79.5,
    "description": "Boost performance instantly.",
    "category": "Automotive",
    "image": "images/NitroPulse-b7bd17a2e02afd5ecf134da907799b60629cae84c8629041773f9382e39cfd4c.png"
  },
  {
    "id": 73,
    "title": "SonicTread",
    "price": 199.0,
    "description": "High-traction tires for safety.",
    "category": "Automotive",
    "image": "images/SonicTread-eac591f6ee34eabf4f3bf1598fa8ce7f389f44174bcee8708d8fbcf8c3f15dab.png"
  },
  {
    "id": 74,
    "title": "AquaWax",
    "price": 29.99,
    "description": "Hydrophobic wax for shine.",
    "category": "Automotive",
    "image": "images/AquaWax-6eb278f26366b96ec5096ef73e8568f57fd66b312c5aaeb229e460d1d7fbedb9.png"
  },
  {
    "id": 80,
    "title": "DreamWeaver Tales",
    "price": 19.99,
    "description": "Stories that weave dreams.",
    "category": "Books",
    "image": "images/DreamWeaver Tales-e7800af71a77dfa6f15a15dfe9f0d7da300145b47e01844ea85e9d39cf179900.png"
  },
  {
    "id": 81,
    "title": "Quantum Minds",
    "price": 24.95,
    "description": "Exploring the universe's mysteries.",
    "category": "Books",
    "image": "images/Quantum Minds-0fcdb75d1a6a0c21191ffb68c32e6438152f4c4f7da1a543a3aa54c6135dea99.png"
  },
  {
    "id": 82,
    "title": "FutureScript",
    "price": 12.5,
    "description": "Tomorrow's stories, today's tech.",
    "category": "Books",
    "image": "images/FutureScript-41c28abd40d66b0a2f80eec9e632fdb6dc1e526b870a5eaff9b1c3dfb3210b8b.png"
  },
  {
    "id": 83,
    "title": "EchoVerse",
    "price": 17.85,
    "description": "Voices from alternate realities.",
    "category": "Books",
    "image": "images/EchoVerse-501cde6916f94b2208b3b81937db6d788a722f159894d50060bf994d07c3b580.png"
  },
  {
    "id": 84,
    "title": "MindMosaic",
    "price": 39.99,
    "description": "Pieces of psychology mastery.",
    "category": "Books",
    "image": "images/MindMosaic-04714219eab32d3706fc657b206609527aacb9183ecf42d216407d7193a26213.png"
  },
  {
    "id": 90,
    "title": "ZestBurst",
    "price": 3.49,
    "description": "Tangy citrus energy drink.",
    "category": "Grocery & Gourmet Food",
    "image": "images/ZestBurst-39884d064d73f4f9e2d6606c88edf7d36197c7b5f78d1515f05b36f6678a19fd.png"
  },
  {
    "id": 91,
    "title": "UmamiPop",
    "price": 5.99,
    "description": "Savory truffle popcorn mix.",
    "category": "Grocery & Gourmet Food",
    "image": "images/UmamiPop-29b6c9ee452f7face1bf4874bdefab467784f63f45f43beab132e5796e048737.png"
  },
  {
    "id": 92,
    "title": "VelvetBrew",
    "price": 4.75,
    "description": "Smooth cold brew coffee blend.",
    "category": "Grocery & Gourmet Food",
    "image": "images/VelvetBrew-ede4298cc6117e51f8a57ee70a03e7ed72b174db6db9f4074e62bf38abf065ff.png"
  },
  {
    "id": 93,
    "title": "FusionFizz",
    "price": 2.99,
    "description": "Spicy mango sparkling soda.",
    "category": "Grocery & Gourmet Food",
    "image": "images/FusionFizz-d07d4f21000c202e22f584337c39a0e14821fd84d102dcfd9071225a200e1518.png"
  },
  {
    "id": 94,
    "title": "HerbaTwist",
    "price": 6.5,
    "description": "Zesty basil pesto sauce.",
    "category": "Grocery & Gourmet Food",
    "image": "images/HerbaTwist-b3be3df91771689a5a3193785a702975cb8b6f6a955b5d19ecd6a3ff7c1ec42e.png"
  }
]

// State management
let totalPages = 1;
let currentSearch = '';
let productsData = [];

// DOM Elements
const productsGrid = document.getElementById('products-grid');
const prevPageBtn = document.getElementById('prev-page');
const nextPageBtn = document.getElementById('next-page');
const pageInfo = document.getElementById('page-info');
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');

// Event Listeners
document.addEventListener('DOMContentLoaded', () => {
    // Check URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const searchParam = urlParams.get('search');
    
    if (searchParam) {
        currentSearch = searchParam;
        searchInput.value = searchParam;
    }
    
    fetchProducts();
    
    prevPageBtn.addEventListener('click', () => {
        const currentPage = getCurrentPage();
        if (currentPage > 1) {
            navigateToPage(currentPage - 1);
        }
    });
    
    nextPageBtn.addEventListener('click', () => {
        const currentPage = getCurrentPage();
        navigateToPage(currentPage + 1);
    });
});

// Helper functions
function getCurrentPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const page = parseInt(urlParams.get('page')) || 1;
    return Math.max(1, page); // Ensure page is at least 1
}

function navigateToPage(page) {
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('page', page);
    window.location.href = `${window.location.pathname}?${urlParams.toString()}`;
}

// Get products from local data
function fetchProducts() {
    showLoading();
    
    try {
        // Start with all products
        productsData = [...ALL_PRODUCTS];
        
        // Filter by search term if present
        if (currentSearch) {
            productsData = productsData.filter(product => 
                product.title.toLowerCase().includes(currentSearch.toLowerCase()) || 
                product.description.toLowerCase().includes(currentSearch.toLowerCase())
            );
        }
        
        // Since we're selecting random products, we can have as many pages as we want
        // as long as there are at least PRODUCTS_PER_PAGE items available
        totalPages = productsData.length >= PRODUCTS_PER_PAGE ? Number.MAX_SAFE_INTEGER : 1;
        
        // Update UI
        updatePagination();
        renderProducts();
    } catch (error) {
        console.error('Error processing products:', error);
        productsGrid.innerHTML = `<div class="error">Failed to load products. Please try again later.</div>`;
    }
}

// Render products for current page
function renderProducts() {
    // Get random products for the current page
    const currentPageProducts = getRandomProducts(productsData, PRODUCTS_PER_PAGE);
    
    if (currentPageProducts.length === 0) {
        productsGrid.innerHTML = '<div class="no-products">No products found matching your criteria.</div>';
        return;
    }
    
    productsGrid.innerHTML = currentPageProducts.map(product => `
        <div class="product-card">
            <div class="product-image">
                <img src="${product.image}" alt="${product.title}">
            </div>
            <div class="product-info">
                <h3 class="product-title">${product.title}</h3>
                <p class="product-price">$${product.price.toFixed(2)}</p>
                <p class="product-description">${truncateText(product.description, 100)}</p>
            </div>
        </div>
    `).join('');
}

// Update pagination controls
function updatePagination() {
    const currentPage = getCurrentPage();
    const totalProducts = productsData.length;
    
    if (totalProducts >= PRODUCTS_PER_PAGE) {
        pageInfo.textContent = `Page ${currentPage} - Showing ${PRODUCTS_PER_PAGE} products out of ${totalProducts}`;
    } else {
        pageInfo.textContent = `Page ${currentPage} - Showing ${totalProducts} products`;
    }
    
    prevPageBtn.disabled = currentPage === 1;
    // Next button is never disabled as per requirements
}

// Helper functions
function getRandomProducts(products, count) {
    // Create a copy of the array to avoid modifying the original
    const availableProducts = [...products];
    const result = [];
    const numProducts = Math.min(count, availableProducts.length);

    // Select random products
    for (let i = 0; i < numProducts; i++) {
        const randomIndex = Math.floor(Math.random() * availableProducts.length);
        result.push(availableProducts.splice(randomIndex, 1)[0]);
    }

    return result;
}

function truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substr(0, maxLength) + '...';
}

function showLoading() {
    productsGrid.innerHTML = '<div class="loading">Loading products...</div>';
}