/**
 * Handles rendering of all UI components related to shops.
 */
class ShopUI {
    constructor(mainContentElement) {
        this.mainContent = mainContentElement;
    }

    renderShopDetailPage(shop, isOwner) {
        const shopHTML = `
            <div class="shop-detail-page">
                <div class="shop-header">
                    <div class="shop-hero">
                        <img src="${shop.image || 'https://images.unsplash.com/photo-1563016767-50f6d53a1d0b?ixlib=rb-4.0.3&auto=format&fit=crop&w=1000&q=80'}" alt="${shop.name}">
                        <div class="shop-info">
                            <h1>${shop.name}</h1>
                            <p class="shop-location">
                                <i class="fas fa-map-marker-alt"></i>
                                ${shop.location}
                            </p>
                            <p class="shop-description">${shop.description}</p>
                            ${isOwner ? `
                                <button class="btn-primary" id="manage-shop-btn">
                                    <i class="fas fa-cog"></i> Manage Shop
                                </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
                <div class="shop-content">
                    <div class="products-section">
                        <div class="section-title">
                            <h2>Products</h2>
                            ${isOwner ? `
                                <button class="btn-primary" id="add-product-btn">
                                    <i class="fas fa-plus"></i> Add Product
                                </button>
                            ` : ''}
                        </div>
                        <div class="products-grid" id="products-grid">
                            <div class="loading">Loading products...</div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        this.mainContent.innerHTML = shopHTML;
    }

    renderProductGrid(products) {
        const productsGrid = document.getElementById('products-grid');
        if (!productsGrid) return;

        const availableProducts = products.filter(p => p.is_available);
        if (availableProducts.length > 0) {
            productsGrid.innerHTML = availableProducts.map(product => `
                <div class="product-card" data-product-id="${product.id}">
                    <div class="product-image">
                        <img src="${product.image || 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&auto=format&fit=crop&w=500&q=80'}" alt="${product.name}">
                    </div>
                    <div class="product-info">
                        <h3>${product.name}</h3>
                        <p class="product-description">${product.description || 'No description'}</p>
                        <div class="product-price">$${parseFloat(product.price).toFixed(2)}</div>
                        <div class="product-actions">
                            <button class="btn-primary add-to-cart-btn"><i class="fas fa-shopping-cart"></i> Add to Cart</button>
                        </div>
                    </div>
                </div>
            `).join('');
        } else {
            productsGrid.innerHTML = '<p>No products available in this shop at the moment.</p>';
        }
    }

    renderManagementProducts(products) {
        const container = document.getElementById('management-products');
        if (!container) return;

        container.innerHTML = products.length > 0 ? products.map(product => `
            <div class="management-product-item" data-product-id="${product.id}">
                <div class="product-image">
                    <img src="${product.image || 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-4.0.3&auto=format&fit=crop&w=100&q=80'}" alt="${product.name}">
                </div>
                <div class="product-details">
                    <h4>${product.name}</h4>
                    <p>${product.description || 'No description'}</p>
                    <div class="product-meta">
                        <span class="price">$${parseFloat(product.price).toFixed(2)}</span>
                        <span class="category">${product.category}</span>
                    </div>
                </div>
                <div class="product-actions">
                    <label class="availability-toggle">
                        <input type="checkbox" class="availability-toggle-checkbox" data-product-id="${product.id}" ${product.is_available ? 'checked' : ''}>
                        <span class="availability-toggle-slider"></span>
                    </label>
                    <button class="btn-secondary edit-product" data-product-id="${product.id}">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-danger delete-product" data-product-id="${product.id}">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `).join('') : '<p>No products found. Add one to get started!</p>';
    }

    renderShopOrders(orders) {
        const container = document.getElementById('orders-tab');
        if (!container) return;

        container.dataset.loaded = 'true'; // Mark as loaded
        if (orders.length > 0) {
            const statuses = ['pending', 'confirmed', 'preparing', 'ready', 'picked_up', 'delivered', 'cancelled'];
            container.innerHTML = orders.map(order => {
                const statusOptions = statuses.map(s =>
                    `<option value="${s}" ${order.status === s ? 'selected' : ''}>${s.charAt(0).toUpperCase() + s.slice(1)}</option>`
                ).join('');

                return `
                    <div class="delivery-card">
                        <div class="delivery-info">
                            <h4>Order #${order.id}</h4>
                            <p><strong>Customer:</strong> ${order.customer_name}</p>
                            <p><strong>Date:</strong> ${new Date(order.created_at).toLocaleDateString()}</p>
                            <p><strong>Total:</strong> $${parseFloat(order.total_amount).toFixed(2)}</p>
                        </div>
                        <div class="delivery-actions">
                            <select class="order-status-select status-select" data-order-id="${order.id}">
                                ${statusOptions}
                            </select>
                        </div>
                    </div>
                `;
            }).join('');
        } else {
            container.innerHTML = '<p>No orders found for this shop.</p>';
        }
    }

    getCreateShopModalContent() {
        return `
            <form id="create-shop-form">
                <div class="form-group"><label for="shop-name">Shop Name</label><input type="text" id="shop-name" name="name" required></div>
                <div class="form-group"><label for="shop-description">Description</label><textarea id="shop-description" name="description" rows="3"></textarea></div>
                <div class="form-group"><label for="shop-location">Location</label><input type="text" id="shop-location" name="location" required></div>
                <div class="form-group"><label for="shop-image">Shop Image</label><input type="file" id="shop-image" name="image" accept="image/*"></div>
                <div class="form-actions"><button type="button" class="btn-secondary" data-action="cancel">Cancel</button><button type="submit" class="btn-primary">Create Shop</button></div>
            </form>
        `;
    }

    getAddProductModalContent(productId = null) {
        return `
            <form id="add-product-form">
                <input type="hidden" name="product_id" value="${productId || ''}">
                <div class="form-group"><label>Product Name</label><input type="text" name="name" required></div>
                <div class="form-group"><label>Description</label><textarea name="description" rows="3"></textarea></div>
                <div class="form-group"><label>Price ($)</label><input type="number" name="price" step="0.01" min="0" required></div>
                <div class="form-group"><label>Category</label><select name="category"><option value="General">General</option><option value="Electronics">Electronics</option><option value="Food">Food</option><option value="Clothing">Clothing</option><option value="Home">Home & Garden</option><option value="Other">Other</option></select></div>
                <div class="form-group">
                    <label>Product Image</label>
                    <div id="current-product-image-container" style="display: none; margin-bottom: 10px;">
                        <img id="current-product-image" src="" alt="Current Image" style="max-width: 100px; max-height: 100px; border-radius: 8px;">
                    </div>
                    <input type="file" name="image" accept="image/*">
                </div>
                <div class="form-actions"><button type="button" class="btn-secondary" data-action="cancel">Cancel</button><button type="submit" class="btn-primary">${productId ? 'Save Changes' : 'Add Product'}</button></div>
            </form>
        `;
    }

    getShopManagementModalContent(shop) {
        return `
            <div class="management-tabs">
                <div class="tab-nav">
                    <button class="tab-btn active" data-tab="products">Products</button>
                    <button class="tab-btn" data-tab="orders">Orders</button>
                    <button class="tab-btn" data-tab="settings">Settings</button>
                </div>
                <div class="tab-content">
                    <div class="tab-pane active" id="products-tab">
                        <div class="tab-header">
                            <h4>Product Management</h4>
                            <button class="btn-primary" id="modal-add-product"><i class="fas fa-plus"></i> Add Product</button>
                        </div>
                        <div id="management-products"><div class="loading">Loading products...</div></div>
                    </div>
                    <div class="tab-pane" id="orders-tab"><div class="loading">Loading orders...</div></div>
                    <div class="tab-pane" id="settings-tab">
                        <h4>Shop Settings</h4>
                        <form id="shop-settings-form">
                            <div class="form-group"><label>Shop Name</label><input type="text" name="name" value="${shop.name}" required></div>
                            <div class="form-group"><label>Description</label><textarea name="description" rows="3">${shop.description || ''}</textarea></div>
                            <div class="form-group"><label>Location</label><input type="text" name="location" value="${shop.location}" required></div>
                            <div class="form-group"><label>New Shop Image (Optional)</label><input type="file" name="image" accept="image/*"></div>
                            <button type="submit" class="btn-primary">Save Changes</button>
                        </form>
                    </div>
                </div>
            </div>
        `;
    }

    fillProductForm(form, product) {
        form.elements['name'].value = product.name;
        form.elements['description'].value = product.description;
        form.elements['price'].value = product.price;
        form.elements['category'].value = product.category;
        form.elements['image'].value = product.image;
    }
}