// Store data will be loaded from JSON
let categories = null;
let currentCategory = null;
let currentSubcategory = null;
let selectedPaymentMethod = null;

function initializePaymentMethods() {
    const paymentSelect = document.getElementById('paymentMethod');
    paymentSelect.innerHTML = `
        <option value="" disabled ${!selectedPaymentMethod ? 'selected' : ''}>Select Payment Method</option>
        ${categories.paymentMethods.map(method => `
            <option value="${method.id}" ${method.id === selectedPaymentMethod ? 'selected' : ''}>
                ${method.icon} ${method.name}
            </option>
        `).join('')}
    `;
    paymentSelect.addEventListener('change', (e) => {
        selectedPaymentMethod = e.target.value;
        updateBuyButtons();
    });
}

function updateBuyButtons() {
    const buyButtons = document.querySelectorAll('.buy-btn');
    buyButtons.forEach(button => {
        button.disabled = !selectedPaymentMethod;
    });
}

function handleQuantityChange(productId, change, quantityDisplay) {
    const currentQty = parseInt(quantityDisplay.textContent);
    const newQty = Math.max(1, currentQty + change);
    quantityDisplay.textContent = newQty;
}

function handlePurchase(product, quantity) {
    if (!selectedPaymentMethod) {
        alert('Please select a payment method first');
        return;
    }
    
    const total = product.price * quantity;
    alert(`Purchase Summary:
Product: ${product.name}
Quantity: ${quantity}
Total: $${total.toLocaleString()}
Payment Method: ${categories.paymentMethods.find(m => m.id === selectedPaymentMethod).name}`);
    // Here you would typically integrate with your game's purchasing system
}

function showMainCategories() {
    const mainContent = document.querySelector('main');
    currentCategory = null;
    currentSubcategory = null;

    mainContent.innerHTML = `
        <div class="categories-grid"></div>
    `;

    const categoriesGrid = document.querySelector('.categories-grid');
      Object.entries(categories)
        .filter(([key]) => key !== 'paymentMethods')
        .forEach(([categoryName, categoryData]) => {
            const categoryTile = document.createElement('button');
            categoryTile.className = 'category-tile';
            categoryTile.innerHTML = `
                <span class="icon">${categoryData.icon}</span>
                <span class="name">${categoryName}</span>
            `;
            categoryTile.addEventListener('click', () => showSubcategories(categoryName));
            categoriesGrid.appendChild(categoryTile);
        });
}

function showSubcategories(categoryName) {
    const mainContent = document.querySelector('main');
    currentCategory = categoryName;
    currentSubcategory = null;

    mainContent.innerHTML = `
        <button class="back-button">← Back to Categories</button>
        <h2>${categoryName}</h2>
        <div class="subcategories-grid"></div>
    `;

    const subcategoriesGrid = document.querySelector('.subcategories-grid');
    const backButton = document.querySelector('.back-button');
    backButton.addEventListener('click', showMainCategories);

    Object.entries(categories[categoryName].subcategories).forEach(([subCategoryName, subCategoryData]) => {
        const subCategoryTile = document.createElement('button');
        subCategoryTile.className = 'subcategory-tile';
        subCategoryTile.innerHTML = `
            <span class="icon">${subCategoryData.icon}</span>
            <span class="name">${subCategoryName}</span>
        `;
        subCategoryTile.addEventListener('click', () => showProducts(categoryName, subCategoryName));
        subcategoriesGrid.appendChild(subCategoryTile);
    });
}

function showProducts(categoryName, subCategoryName) {
    const mainContent = document.querySelector('main');
    currentSubcategory = subCategoryName;

    mainContent.innerHTML = `
        <button class="back-button">← Back to ${categoryName}</button>
        <h2>${categoryName} > ${subCategoryName}</h2>
        <div class="products-grid"></div>
    `;

    const productsGrid = document.querySelector('.products-grid');
    const backButton = document.querySelector('.back-button');
    backButton.addEventListener('click', () => showSubcategories(categoryName));

    const products = categories[categoryName].subcategories[subCategoryName].products;
    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            <div class="product-image"></div>
            <div class="product-info">
                <h3 class="product-name">${product.name}</h3>
                <p class="product-price">$${product.price.toLocaleString()}</p>
                <div class="product-controls">
                    <div class="quantity-controls">
                        <button class="quantity-btn minus">-</button>
                        <span class="quantity-display">1</span>
                        <button class="quantity-btn plus">+</button>
                    </div>
                    <button class="buy-btn" ${!selectedPaymentMethod ? 'disabled' : ''}>
                        Buy Now
                    </button>
                </div>
            </div>
        `;

        const quantityDisplay = productCard.querySelector('.quantity-display');
        const minusBtn = productCard.querySelector('.quantity-btn.minus');
        const plusBtn = productCard.querySelector('.quantity-btn.plus');
        const buyBtn = productCard.querySelector('.buy-btn');

        minusBtn.addEventListener('click', () => handleQuantityChange(product.id, -1, quantityDisplay));
        plusBtn.addEventListener('click', () => handleQuantityChange(product.id, 1, quantityDisplay));
        buyBtn.addEventListener('click', () => handlePurchase(product, parseInt(quantityDisplay.textContent)));

        productsGrid.appendChild(productCard);
    });
}

// Initialize the store
async function initializeStore() {
    try {
        const response = await fetch('http://localhost:8000/data/categories.json');
        if (!response.ok) {
            throw new Error('Failed to load store data');
        }
        categories = await response.json();
        initializePaymentMethods();
        showMainCategories();
    } catch (error) {
        console.error('Error loading store data:', error);
        document.querySelector('main').innerHTML = `
            <div class="error-message">
                <h2>Error Loading Store Data</h2>
                <p>Please try again later.</p>
            </div>
        `;
    }
}

document.addEventListener('DOMContentLoaded', () => {
    initializeStore();
});
