/**
 * Store Interface
 * Handles item browsing, cart management, and purchases
 */

// Mock data
const mockData = {
    balance: 45750,
    items: [
        // Weapons
        { id: 1, name: "Assault Rifle", category: "weapons", icon: "🔫", description: "Standard military-grade rifle", price: 2500 },
        { id: 2, name: "Sniper Rifle", category: "weapons", icon: "🎯", description: "Long-range precision weapon", price: 4500 },
        { id: 3, name: "SMG", category: "weapons", icon: "🔫", description: "Close-quarters combat", price: 1800 },
        { id: 4, name: "Pistol", category: "weapons", icon: "🔫", description: "Sidearm backup weapon", price: 800 },
        { id: 5, name: "Shotgun", category: "weapons", icon: "🔫", description: "Close-range powerhouse", price: 1500 },
        { id: 6, name: "LMG", category: "weapons", icon: "🔫", description: "Heavy suppression weapon", price: 3500 },
        { id: 7, name: "Grenade Launcher", category: "weapons", icon: "💣", description: "Explosive ordnance", price: 5000 },
        { id: 8, name: "Rocket Launcher", category: "weapons", icon: "🚀", description: "Anti-vehicle weapon", price: 8000 },

        // Equipment
        { id: 9, name: "Body Armor", category: "equipment", icon: "🎽", description: "Ballistic protection", price: 3000 },
        { id: 10, name: "Helmet", category: "equipment", icon: "⛑️", description: "Head protection", price: 1200 },
        { id: 11, name: "Night Vision", category: "equipment", icon: "🕶️", description: "See in the dark", price: 2500 },
        { id: 12, name: "GPS Device", category: "equipment", icon: "📡", description: "Navigation system", price: 800 },
        { id: 13, name: "Radio", category: "equipment", icon: "📻", description: "Team communication", price: 600 },
        { id: 14, name: "Backpack", category: "equipment", icon: "🎒", description: "Extra storage capacity", price: 500 },

        // Medical
        { id: 15, name: "First Aid Kit", category: "medical", icon: "💊", description: "Basic medical supplies", price: 400 },
        { id: 16, name: "Med Kit", category: "medical", icon: "⚕️", description: "Advanced medical kit", price: 1000 },
        { id: 17, name: "Bandages", category: "medical", icon: "🩹", description: "Stop bleeding", price: 150 },
        { id: 18, name: "Morphine", category: "medical", icon: "💉", description: "Pain management", price: 300 },
        { id: 19, name: "Blood Bag", category: "medical", icon: "🩸", description: "Restore blood level", price: 500 },

        // Supplies
        { id: 20, name: "Ammunition Box", category: "supplies", icon: "📦", description: "Mixed ammunition", price: 800 },
        { id: 21, name: "Explosive Charges", category: "supplies", icon: "💣", description: "Demolition supplies", price: 1500 },
        { id: 22, name: "Toolkit", category: "supplies", icon: "🔧", description: "Repair equipment", price: 600 },
        { id: 23, name: "Food Rations", category: "supplies", icon: "🥫", description: "Emergency supplies", price: 200 },
        { id: 24, name: "Water Canteen", category: "supplies", icon: "🧃", description: "Hydration supply", price: 150 }
    ]
};

// State
let cart = [];
let selectedCategory = 'all';
let searchQuery = '';

// Initialize
function initStore() {
    console.log('Store interface initializing...');

    setupEventHandlers();
    renderItems();
    updateBalance();

    console.log('Store interface initialized');
}

// Event Handlers
function setupEventHandlers() {
    // Close button
    const closeBtn = document.querySelector('.close-btn');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            console.log('Closing store...');
            sendEvent('actor::close::store', {});
        });
    }

    // Cart toggle
    const cartToggle = document.getElementById('cartToggle');
    const cartPanel = document.getElementById('cartPanel');
    const storeContent = document.querySelector('.store-content');

    if (cartToggle && cartPanel) {
        cartToggle.addEventListener('click', () => {
            const isOpen = cartPanel.style.display !== 'none';
            cartPanel.style.display = isOpen ? 'none' : 'flex';
            storeContent.classList.toggle('cart-open', !isOpen);
        });
    }

    // Category filters
    const categoryItems = document.querySelectorAll('.category-item');
    categoryItems.forEach(item => {
        item.addEventListener('click', () => {
            categoryItems.forEach(c => c.classList.remove('active'));
            item.classList.add('active');
            selectedCategory = item.dataset.category;
            renderItems();
        });
    });

    // Search
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('input', (e) => {
            searchQuery = e.target.value.toLowerCase();
            renderItems();
        });
    }

    // Clear cart
    const clearCartBtn = document.getElementById('clearCart');
    if (clearCartBtn) {
        clearCartBtn.addEventListener('click', () => {
            if (confirm('Clear all items from cart?')) {
                cart = [];
                renderCart();
                updateCartCount();
            }
        });
    }

    // Checkout
    const checkoutBtn = document.getElementById('checkoutBtn');
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', handleCheckout);
    }
}

// Render items
function renderItems() {
    const itemsGrid = document.getElementById('itemsGrid');
    if (!itemsGrid) return;

    itemsGrid.innerHTML = '';

    // Filter items
    let filteredItems = mockData.items;

    if (selectedCategory !== 'all') {
        filteredItems = filteredItems.filter(item => item.category === selectedCategory);
    }

    if (searchQuery) {
        filteredItems = filteredItems.filter(item =>
            item.name.toLowerCase().includes(searchQuery) ||
            item.description.toLowerCase().includes(searchQuery)
        );
    }

    // Render filtered items
    filteredItems.forEach(item => {
        const card = document.createElement('div');
        card.className = 'item-card';

        card.innerHTML = `
            <div class="item-icon">${item.icon}</div>
            <div class="item-name">${item.name}</div>
            <div class="item-description">${item.description}</div>
            <div class="item-price">$${item.price.toLocaleString()}</div>
            <div class="item-actions">
                <button class="add-to-cart-btn" data-item-id="${item.id}">Add to Cart</button>
            </div>
        `;

        const addBtn = card.querySelector('.add-to-cart-btn');
        addBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            addToCart(item);
        });

        itemsGrid.appendChild(card);
    });

    console.log(`Rendered ${filteredItems.length} items`);
}

// Cart functions
function addToCart(item) {
    const existingItem = cart.find(c => c.id === item.id);

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

    renderCart();
    updateCartCount();

    // Show cart panel if not visible
    const cartPanel = document.getElementById('cartPanel');
    const storeContent = document.querySelector('.store-content');
    if (cartPanel.style.display === 'none') {
        cartPanel.style.display = 'flex';
        storeContent.classList.add('cart-open');
    }

    console.log('Added to cart:', item.name);
}

function removeFromCart(itemId) {
    cart = cart.filter(item => item.id !== itemId);
    renderCart();
    updateCartCount();
}

function renderCart() {
    const cartItems = document.getElementById('cartItems');
    if (!cartItems) return;

    cartItems.innerHTML = '';

    if (cart.length === 0) {
        cartItems.innerHTML = `
            <div class="empty-cart">
                <span class="empty-icon">🛒</span>
                <span class="empty-text">Your cart is empty</span>
            </div>
        `;
    } else {
        cart.forEach(item => {
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';

            cartItem.innerHTML = `
                <div class="cart-item-header">
                    <span class="cart-item-name">${item.name}</span>
                    <button class="cart-item-remove" data-item-id="${item.id}">Remove</button>
                </div>
                <div class="cart-item-details">
                    <span>Qty: ${item.quantity}</span>
                    <span class="cart-item-price">$${(item.price * item.quantity).toLocaleString()}</span>
                </div>
            `;

            const removeBtn = cartItem.querySelector('.cart-item-remove');
            removeBtn.addEventListener('click', () => removeFromCart(item.id));

            cartItems.appendChild(cartItem);
        });
    }

    updateCartSummary();
}

function updateCartCount() {
    const cartCount = document.querySelector('.cart-count');
    if (cartCount) {
        const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
        cartCount.textContent = totalItems;
    }
}

function updateCartSummary() {
    const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    const tax = subtotal * 0.05;
    const total = subtotal + tax;

    document.getElementById('cartSubtotal').textContent = `$${subtotal.toLocaleString()}`;
    document.getElementById('cartTax').textContent = `$${tax.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    document.getElementById('cartTotal').textContent = `$${total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

    const checkoutBtn = document.getElementById('checkoutBtn');
    if (checkoutBtn) {
        checkoutBtn.disabled = cart.length === 0 || total > mockData.balance;
    }
}

function handleCheckout() {
    const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    const tax = total * 0.05;
    const grandTotal = total + tax;

    if (grandTotal > mockData.balance) {
        alert('Insufficient funds!');
        return;
    }

    const purchaseData = {
        items: cart.map(item => ({
            id: item.id,
            name: item.name,
            quantity: item.quantity,
            price: item.price
        })),
        subtotal: total,
        tax: tax,
        total: grandTotal
    };

    console.log('Purchase request:', purchaseData);
    sendEvent('actor::store::purchase', purchaseData);

    // Clear cart after purchase
    cart = [];
    renderCart();
    updateCartCount();

    // Update balance (this would normally come from server)
    mockData.balance -= grandTotal;
    updateBalance();
}

function updateBalance() {
    const balanceAmount = document.querySelector('.balance-amount');
    if (balanceAmount) {
        balanceAmount.textContent = `$${mockData.balance.toLocaleString()}`;
    }
}

// Update store data from external source
function updateStoreData(data) {
    if (data.balance !== undefined) {
        mockData.balance = data.balance;
        updateBalance();
    }

    if (data.items) {
        mockData.items = data.items;
        renderItems();
    }
}

// Send event to Arma
function sendEvent(event, data) {
    if (typeof A3API !== 'undefined') {
        A3API.SendAlert(JSON.stringify({
            event: event,
            data: data
        }));
    } else {
        console.log('Event:', event, 'Data:', data);
    }
}

// Auto-initialize
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initStore);
} else {
    initStore();
}

// Expose functions globally
window.updateStoreData = updateStoreData;
window.addToCart = addToCart;
