<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }} - Database Demo</title>
    <link rel="icon" type="image/x-icon" href="{{ url_for('static', path='/favicon.ico') }}">
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- HTMX CDN -->
    <script src="https://unpkg.com/htmx.org@2.0.6"></script>
    
    <!-- Alpine.js CDN -->
    <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
    
    <!-- Chart.js for beautiful charts -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- Custom Tailwind Config -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'ai-blue': '#3B82F6',
                        'ai-purple': '#8B5CF6',
                        'ai-gradient': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50" x-data="dashboardData()">
    {% include 'partials/header.html' %}

    <!-- Database Demo Header -->
    <div class="bg-gradient-to-r from-ai-blue to-ai-purple text-white py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold mb-2">Database Demo</h1>
                    <p class="text-blue-100">Real-time insights for marketing managers</p>
                </div>
                
                <!-- Refresh Button -->
                <button @click="loadData()" 
                        class="bg-white bg-opacity-20 hover:bg-opacity-30 text-white px-6 py-2 rounded-lg font-semibold transition-all duration-200 flex items-center space-x-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    <span>Refresh Data</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Loading State -->
    <div x-show="loading" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white p-8 rounded-lg shadow-xl">
            <div class="flex items-center space-x-4">
                <svg class="animate-spin h-8 w-8 text-ai-blue" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="text-lg font-semibold">Loading database data...</span>
            </div>
        </div>
    </div>

    <!-- Database Demo Content -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Key Metrics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Total Products -->
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-ai-blue">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Products</p>
                        <p class="text-3xl font-bold text-gray-900" x-text="stats.total_products || 0">0</p>
                    </div>
                    <div class="w-12 h-12 bg-ai-blue bg-opacity-10 rounded-lg flex items-center justify-center">
                        <svg class="w-6 h-6 text-ai-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Average Price -->
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Average Price</p>
                        <p class="text-3xl font-bold text-gray-900" x-text="'$' + (stats.avg_price || 0).toFixed(2)">$0.00</p>
                    </div>
                    <div class="w-12 h-12 bg-green-500 bg-opacity-10 rounded-lg flex items-center justify-center">
                        <svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- In Stock -->
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">In Stock</p>
                        <p class="text-3xl font-bold text-gray-900" x-text="stock.in_stock || 0">0</p>
                    </div>
                    <div class="w-12 h-12 bg-green-500 bg-opacity-10 rounded-lg flex items-center justify-center">
                        <svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Out of Stock -->
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Out of Stock</p>
                        <p class="text-3xl font-bold text-gray-900" x-text="stock.out_of_stock || 0">0</p>
                    </div>
                    <div class="w-12 h-12 bg-red-500 bg-opacity-10 rounded-lg flex items-center justify-center">
                        <svg class="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts and Tables Section -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Category Distribution Chart -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Category Distribution</h3>
                <div class="h-64">
                    <canvas id="categoryChart"></canvas>
                </div>
            </div>

            <!-- Price Range Chart -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Price Distribution</h3>
                <div class="h-64">
                    <canvas id="priceChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Products Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-900">Product Inventory</h3>
                    
                    <!-- Search and Filter -->
                    <div class="flex items-center space-x-4">
                        <div class="relative">
                            <input type="text" 
                                   x-model="searchTerm"
                                   placeholder="Search products..." 
                                   class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ai-blue focus:border-transparent">
                            <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                        </div>
                        
                        <select x-model="selectedCategory" 
                                class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-ai-blue focus:border-transparent">
                            <option value="">All Categories</option>
                            <template x-for="category in categories" :key="category.category">
                                <option :value="category.category" x-text="category.category"></option>
                            </template>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Product</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Category</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stock</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Added</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <template x-for="product in filteredProducts" :key="product.id">
                            <tr class="hover:bg-gray-50 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div>
                                        <div class="text-sm font-medium text-gray-900" x-text="product.name"></div>
                                        <div class="text-sm text-gray-500" x-text="product.description || 'No description'"></div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                                          :class="getCategoryColor(product.category)"
                                          x-text="product.category || 'Uncategorized'"></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="'$' + product.price.toFixed(2)"></td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                                          :class="product.in_stock ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
                                        <span x-text="product.in_stock ? 'In Stock' : 'Out of Stock'"></span>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500" x-text="formatDate(product.created_at)"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <div class="bg-white px-6 py-3 border-t border-gray-200">
                <div class="flex items-center justify-between">
                    <div class="text-sm text-gray-700">
                        Showing <span x-text="filteredProducts.length"></span> of <span x-text="products.length"></span> products
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    {% include 'partials/footer.html' %}


    <script>
        function dashboardData() {
            return {
                loading: true,
                products: [],
                categories: [],
                stats: {},
                stock: {},
                searchTerm: '',
                selectedCategory: '',
                categoryChart: null,
                priceChart: null,
                
                init() {
                    this.loadData();
                },
                
                async loadData() {
                    this.loading = true;
                    try {
                        const response = await fetch('/api/products');
                        const data = await response.json();
                        
                        this.products = data.products;
                        this.categories = data.categories;
                        this.stats = data.stats;
                        this.stock = data.stock;
                        
                        // Check if database is unavailable
                        if (!data.database_available) {
                            this.showDatabaseUnavailableMessage(data.error || 'Database is currently unavailable');
                        }
                        
                        this.$nextTick(() => {
                            this.initCharts();
                        });
                    } catch (error) {
                        console.error('Error loading data:', error);
                        this.showDatabaseUnavailableMessage('Failed to connect to database');
                    } finally {
                        this.loading = false;
                    }
                },
                
                showDatabaseUnavailableMessage(error) {
                    // Show a user-friendly message when database is unavailable
                    const message = `
                        <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-6">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm text-yellow-700">
                                        <strong>Database Unavailable:</strong> ${error}. This demo requires a properly configured database connection.
                                    </p>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    // Insert the message at the top of the content
                    const contentDiv = document.querySelector('.max-w-7xl.mx-auto.px-4');
                    if (contentDiv) {
                        contentDiv.insertAdjacentHTML('afterbegin', message);
                    }
                },
                
                get filteredProducts() {
                    return this.products.filter(product => {
                        const matchesSearch = !this.searchTerm || 
                            product.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
                            (product.description && product.description.toLowerCase().includes(this.searchTerm.toLowerCase()));
                        
                        const matchesCategory = !this.selectedCategory || product.category === this.selectedCategory;
                        
                        return matchesSearch && matchesCategory;
                    });
                },
                
                getCategoryColor(category) {
                    const colors = {
                        'Electronics': 'bg-blue-100 text-blue-800',
                        'Clothing': 'bg-green-100 text-green-800',
                        'Home & Kitchen': 'bg-purple-100 text-purple-800',
                        'Books': 'bg-yellow-100 text-yellow-800',
                        'Sports': 'bg-red-100 text-red-800'
                    };
                    return colors[category] || 'bg-gray-100 text-gray-800';
                },
                
                formatDate(dateString) {
                    const date = new Date(dateString);
                    return date.toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric'
                    });
                },
                
                initCharts() {
                    // Category Chart
                    const categoryCtx = document.getElementById('categoryChart');
                    if (categoryCtx && this.categoryChart) {
                        this.categoryChart.destroy();
                    }
                    
                    if (categoryCtx) {
                        this.categoryChart = new Chart(categoryCtx, {
                            type: 'doughnut',
                            data: {
                                labels: this.categories.map(cat => cat.category),
                                datasets: [{
                                    data: this.categories.map(cat => cat.count),
                                    backgroundColor: [
                                        '#3B82F6', '#10B981', '#8B5CF6', '#F59E0B', '#EF4444',
                                        '#06B6D4', '#84CC16', '#F97316', '#EC4899', '#6366F1'
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                    legend: {
                                        position: 'bottom'
                                    }
                                }
                            }
                        });
                    }
                    
                    // Price Chart
                    const priceCtx = document.getElementById('priceChart');
                    if (priceCtx && this.priceChart) {
                        this.priceChart.destroy();
                    }
                    
                    if (priceCtx) {
                        const priceRanges = this.getPriceRanges();
                        this.priceChart = new Chart(priceCtx, {
                            type: 'bar',
                            data: {
                                labels: priceRanges.map(range => range.label),
                                datasets: [{
                                    label: 'Products',
                                    data: priceRanges.map(range => range.count),
                                    backgroundColor: '#3B82F6'
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                    legend: {
                                        display: false
                                    }
                                },
                                scales: {
                                    y: {
                                        beginAtZero: true,
                                        ticks: {
                                            stepSize: 1
                                        }
                                    }
                                }
                            }
                        });
                    }
                },
                
                getPriceRanges() {
                    const ranges = [
                        { min: 0, max: 25, label: '$0 - $25' },
                        { min: 25, max: 50, label: '$25 - $50' },
                        { min: 50, max: 100, label: '$50 - $100' },
                        { min: 100, max: 500, label: '$100 - $500' },
                        { min: 500, max: Infinity, label: '$500+' }
                    ];
                    
                    return ranges.map(range => ({
                        ...range,
                        count: this.products.filter(product => 
                            product.price >= range.min && product.price < range.max
                        ).length
                    }));
                }
            }
        }
    </script>
</body>
</html> 