<!-- HTML -->
<div id="product-system">
    <div class="header">
        <h1>Product System</h1>
        <button id="adminLoginBtn" class="btn">Admin Login</button>
    </div>

    <div class="city-selection">
        <label>Select City:</label>
        <select id="citySelect">
            <option value="">Choose city</option>
        </select>
    </div>

    <div id="employeeNameSection" style="display: none;">
        <label>Employee Name:</label>
        <input type="text" id="employeeName" placeholder="Enter your name">
    </div>

    <div id="productsList"></div>
    <div id="orderSummary" style="display: none;"></div>
</div>

<!-- CSS -->
<style>
#product-system {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: -apple-system, system-ui, sans-serif;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.btn {
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.card {
    border: 1px solid #ddd;
    padding: 15px;
    margin: 10px 0;
    border-radius: 8px;
    background: white;
}

.product-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

input, select {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin: 5px;
}
</style>

<!-- JavaScript -->
<script>
// State management
let state = {
    cityProducts: JSON.parse(localStorage.getItem('cityProducts')) || {
        'Melbourne': [
            { id: 1, name: 'Merlin 105', price: 372, itemId: 'M105' },
            { id: 2, name: 'Merlin 855', price: 372, itemId: 'M855' }
        ],
        // ... other cities
    },
    cities: ['Melbourne', 'Sydney', 'Adelaide', 'Brisbane'],
    isAdmin: false,
    adminCode: '1234',
    selectedCity: '',
    employeeName: '',
    quantities: {}
};

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    initializeCitySelect();
    attachEventListeners();
    loadFromLocalStorage();
});

function initializeCitySelect() {
    const select = document.getElementById('citySelect');
    state.cities.forEach(city => {
        const option = document.createElement('option');
        option.value = city;
        option.textContent = city;
        select.appendChild(option);
    });
}

function attachEventListeners() {
    // City selection
    document.getElementById('citySelect').addEventListener('change', function(e) {
        state.selectedCity = e.target.value;
        if (state.selectedCity) {
            document.getElementById('employeeNameSection').style.display = 'block';
            renderProducts();
        }
    });

    // Admin login
    document.getElementById('adminLoginBtn').addEventListener('click', function() {
        const code = prompt('Enter admin code:');
        if (code === state.adminCode) {
            state.isAdmin = true;
            alert('Logged in as admin');
            renderProducts();
        }
    });
}

function renderProducts() {
    const productsDiv = document.getElementById('productsList');
    productsDiv.innerHTML = '';

    const products = state.cityProducts[state.selectedCity] || [];
    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'card';
        productCard.innerHTML = `
            <div class="product-item">
                <div>
                    <span class="product-name">${product.name}</span>
                    <span class="product-id">#${product.itemId}</span>
                    <span class="product-price">$${product.price}</span>
                </div>
                <div>
                    <input type="number" min="0" placeholder="Quantity" 
                           class="quantity-input" data-id="${product.id}"
                           value="${state.quantities[product.id] || ''}">
                    ${state.isAdmin ? `<button onclick="deleteProduct(${product.id})" class="btn">Delete</button>` : ''}
                </div>
            </div>
        `;
        productsDiv.appendChild(productCard);
    });

    // Add order button if products exist
    if (products.length > 0) {
        const orderBtn = document.createElement('button');
        orderBtn.className = 'btn';
        orderBtn.style.marginTop = '20px';
        orderBtn.textContent = 'Show Order Summary';
        orderBtn.onclick = showOrderConfirmation;
        productsDiv.appendChild(orderBtn);
    }
}

function showOrderConfirmation() {
    const employeeName = document.getElementById('employeeName').value;
    if (!employeeName) {
        alert('Please enter employee name first');
        return;
    }

    const confirmation = confirm(`⚠️ Important Notice:

This order will update our warehouse inventory. 
Please carefully review the order details and quantities to prevent discrepancies between the system and actual stock.

Are you sure you want to proceed with this order?`);

    if (confirmation) {
        showOrderSummary();
    }
}

function showOrderSummary() {
    const summaryDiv = document.getElementById('orderSummary');
    summaryDiv.style.display = 'block';
    
    let total = 0;
    let summaryText = `Order Summary - ${state.selectedCity}\n`;
    summaryText += `Employee: ${document.getElementById('employeeName').value}\n\n`;

    state.cityProducts[state.selectedCity].forEach(product => {
        const quantity = state.quantities[product.id] || 0;
        if (quantity > 0) {
            const subtotal = product.price * quantity;
            summaryText += `${product.name} (${product.itemId}) x${quantity} = $${subtotal}\n`;
            total += subtotal;
        }
    });

    summaryText += `\nTotal: $${total}`;

    const textarea = document.createElement('textarea');
    textarea.readOnly = true;
    textarea.value = summaryText;
    textarea.style.width = '100%';
    textarea.style.height = '200px';
    textarea.style.marginTop = '10px';
    
    summaryDiv.innerHTML = '';
    summaryDiv.appendChild(textarea);
}

// Save to localStorage whenever state changes
function saveToLocalStorage() {
    localStorage.setItem('cityProducts', JSON.stringify(state.cityProducts));
}

// Load from localStorage on startup
function loadFromLocalStorage() {
    const savedProducts = localStorage.getItem('cityProducts');
    if (savedProducts) {
        state.cityProducts = JSON.parse(savedProducts);
        renderProducts();
    }
}
</script>