

<?php $__env->startSection('title', 'Ads Management'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">Ads Management</h1>
         <a href="<?php echo e(route('admin.ads.create')); ?>" class="btn btn-primary">
            <i class="fas fa-plus"></i> Create New Ad
        </a>
    </div>

    <!-- Overview Section -->
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ads Overview</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Comprehensive statistics and insights</div>
        </div>
        
        <div style="padding: 20px;">
            <!-- Enhanced Controls -->
            <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center; margin-bottom: 24px; padding: 16px; background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color);">
                <div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                    <label style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">View by:</label>
                    <select id="overviewLevel" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; min-width: 150px;">
                        <option value="all">All Locations</option>
                        <option value="country">By Country</option>
                        <option value="state">By State/Province</option>
                        <option value="city">By City</option>
                    </select>
                </div>
                
                <div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                    <label style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Status:</label>
                    <select id="overviewStatus" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; min-width: 120px;">
                        <option value="all">All Status</option>
                        <option value="active">Active Only</option>
                        <option value="pending">Pending Only</option>
                        <option value="sold">Sold Only</option>
                        <option value="expired">Expired Only</option>
                    </select>
                </div>
                
                <div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                    <label style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Type:</label>
                    <select id="overviewType" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; min-width: 120px;">
                        <option value="all">All Types</option>
                        <option value="featured">Featured Only</option>
                        <option value="regular">Regular Only</option>
                    </select>
                </div>
                
                <div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
                    <label style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Category:</label>
                    <select id="overviewCategory" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; min-width: 150px;">
                        <option value="all">All Categories</option>
                        <option value="electronics">Electronics</option>
                        <option value="vehicles">Vehicles</option>
                        <option value="real-estate">Real Estate</option>
                        <option value="fashion">Fashion</option>
                        <option value="home-garden">Home & Garden</option>
                    </select>
                </div>
            </div>

            <!-- Main Statistics Grid -->
            <div class="dashboard-grid">
                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Total Ads</div>
                            <div class="card-value" id="totalAdsCount"><?php echo e(number_format($stats['total'])); ?></div>
                        </div>
                        <div class="stat-icon">📊</div>
                    </div>
                    <div class="card-change">All ads across all locations</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Active Ads</div>
                            <div class="card-value" id="activeAdsCount"><?php echo e(number_format($stats['active'])); ?></div>
                        </div>
                        <div class="stat-icon">✅</div>
                    </div>
                    <div class="card-change">Currently active listings</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Featured Ads</div>
                            <div class="card-value" id="featuredAdsCount"><?php echo e(number_format($stats['featured'])); ?></div>
                        </div>
                        <div class="stat-icon">⭐</div>
                    </div>
                    <div class="card-change">Premium featured listings</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">By Country</div>
                            <div class="card-value" id="countryAdsCount"><?php echo e(number_format($locationCounts['countries'])); ?></div>
                        </div>
                        <div class="stat-icon">🌍</div>
                    </div>
                    <div class="card-change">Countries with ads</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">By State/Province</div>
                            <div class="card-value" id="stateAdsCount"><?php echo e(number_format($locationCounts['states'])); ?></div>
                        </div>
                        <div class="stat-icon">🗺️</div>
                    </div>
                    <div class="card-change">States/provinces with ads</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Pending Review</div>
                            <div class="card-value" id="pendingAdsCount"><?php echo e(number_format($stats['pending'])); ?></div>
                        </div>
                        <div class="stat-icon">⏳</div>
                    </div>
                    <div class="card-change">Needs admin attention</div>
                </div>
            </div>

            <!-- Charts Section -->
            <div style="margin-top: 24px;">
                <div class="dashboard-grid">
                    <!-- Location Distribution Chart -->
                    <div class="card" style="grid-column: span 2;">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1rem; color: var(--text-primary);">Location Distribution</h4>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Ads by geographic location</div>
                        </div>
                        <div style="padding: 16px;">
                            <div id="locationChart" style="height: 300px; position: relative;">
                                <!-- Chart will be rendered here -->
                            </div>
                            <div id="locationChartLegend" style="display: flex; flex-wrap: wrap; gap: 12px; margin-top: 12px; justify-content: center;"></div>
                        </div>
                    </div>

                    <!-- Status Distribution Chart -->
                    <div class="card">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1rem; color: var(--text-primary);">Status Distribution</h4>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Ads by status</div>
                        </div>
                        <div style="padding: 16px;">
                            <div id="statusChart" style="height: 200px; position: relative;">
                                <!-- Chart will be rendered here -->
                            </div>
                            <div id="statusChartLegend" style="display: flex; flex-direction: column; gap: 8px; margin-top: 12px;"></div>
                        </div>
                    </div>

                    <!-- Category Distribution Chart -->
                    <div class="card">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1rem; color: var(--text-primary);">Category Distribution</h4>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Ads by category</div>
                        </div>
                        <div style="padding: 16px;">
                            <div id="categoryChart" style="height: 200px; position: relative;">
                                <!-- Chart will be rendered here -->
                            </div>
                            <div id="categoryChartLegend" style="display: flex; flex-direction: column; gap: 8px; margin-top: 12px;"></div>
                        </div>
                    </div>

                    <!-- Featured vs Regular Chart -->
                    <div class="card">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1rem; color: var(--text-primary);">Featured vs Regular</h4>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Premium vs standard listings</div>
                        </div>
                        <div style="padding: 16px;">
                            <div id="featuredChart" style="height: 200px; position: relative;">
                                <!-- Chart will be rendered here -->
                            </div>
                            <div id="featuredChartLegend" style="display: flex; flex-direction: column; gap: 8px; margin-top: 12px;"></div>
                        </div>
                    </div>

                    <!-- Top Locations Table -->
                    <div class="card" style="grid-column: span 2;">
                        <div class="card-header">
                            <h4 style="margin: 0; font-size: 1rem; color: var(--text-primary);">Top Locations</h4>
                            <div style="font-size: 0.875rem; color: var(--text-secondary);">Locations with most ads</div>
                        </div>
                        <div style="padding: 16px;">
                            <div class="table-card" style="border: none; padding: 0;">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>Location</th>
                                            <th>Type</th>
                                            <th>Total Ads</th>
                                            <th>Active</th>
                                            <th>Featured</th>
                                            <th>Views</th>
                                        </tr>
                                    </thead>
                                    <tbody id="topLocationsTable">
                                        <!-- Table content will be loaded here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters and Controls -->
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ads Management</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Manage platform ads</div>
        </div>
        
        <div style="padding: 20px;">
            <form action="<?php echo e(route('admin.ads.index')); ?>" method="GET" style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center; margin-bottom: 20px;">
                <!-- Country Filter -->
                <div style="display: flex; gap: 8px; align-items: center;">
                    <label style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600;">Country:</label>
                    <select name="country" onchange="this.form.submit()" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        <option value="">All Countries</option>
                        <option value="USA" <?php echo e(request('country') == 'USA' ? 'selected' : ''); ?>>United States</option>
                        <option value="Canada" <?php echo e(request('country') == 'Canada' ? 'selected' : ''); ?>>Canada</option>
                        <option value="UK" <?php echo e(request('country') == 'UK' ? 'selected' : ''); ?>>United Kingdom</option>
                        <option value="Germany" <?php echo e(request('country') == 'Germany' ? 'selected' : ''); ?>>Germany</option>
                        <option value="Australia" <?php echo e(request('country') == 'Australia' ? 'selected' : ''); ?>>Australia</option>
                    </select>
                </div>

                <!-- Search -->
                <div style="position: relative; flex: 1; min-width: 250px;">
                    <input type="text" name="search" value="<?php echo e(request('search')); ?>" placeholder="Search ads by title, description, seller..." style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; width: 100%;">
                    <button type="submit" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-secondary); cursor: pointer;">🔍</button>
                </div>

                <!-- Category Filter -->
                <select name="category" onchange="this.form.submit()" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                    <option value="">All Categories</option>
                    <?php $__currentLoopData = \App\Models\Category::all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cat): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($cat->id); ?>" <?php echo e(request('category') == $cat->id ? 'selected' : ''); ?>><?php echo e($cat->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>

                <!-- Status Filter -->
                <select name="status" onchange="this.form.submit()" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                    <option value="">All Status</option>
                    <option value="Active" <?php echo e(request('status') == 'Active' ? 'selected' : ''); ?>>Active</option>
                    <option value="Pending" <?php echo e(request('status') == 'Pending' ? 'selected' : ''); ?>>Pending</option>
                    <option value="Rejected" <?php echo e(request('status') == 'Rejected' ? 'selected' : ''); ?>>Rejected</option>
                    <option value="Sold" <?php echo e(request('status') == 'Sold' ? 'selected' : ''); ?>>Sold</option>
                    <option value="Expired" <?php echo e(request('status') == 'Expired' ? 'selected' : ''); ?>>Expired</option>
                </select>

                <!-- Bulk Actions (Outside Form Logically, but placed here visually) -->
                <div style="display: flex; gap: 8px;">
                    <a href="<?php echo e(route('admin.ads.create')); ?>" class="btn btn-primary" style="padding: 8px 16px; border-radius: 6px; text-decoration: none;">
                         Add Ad
                    </a>
                </div>
            </form>
            
            <div class="table-card" style="border: none; padding: 0;">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 50px;">
                                <input type="checkbox" id="selectAll" style="width: 16px; height: 16px;">
                            </th>
                            <th>Ad</th>
                            <th>Category</th>
                            <th>Price</th>
                            <th>Status</th>
                            <th>Location</th>
                            <th>Views</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="adsTableBody">
                        <?php $__empty_1 = true; $__currentLoopData = $ads; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ad): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <tr style="vertical-align: middle;">
                            <td>
                                <input type="checkbox" class="ad-checkbox" value="<?php echo e($ad->id); ?>" style="width: 16px; height: 16px;">
                            </td>
                            <td style="min-width: 300px;">
                                <div style="display: flex; align-items: center; gap: 12px;">
                                    <div style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; border: 1px solid var(--border-color); flex-shrink: 0;">
                                        <?php if($ad->images && $ad->images->count() > 0): ?>
                                            <img src="<?php echo e($ad->images->first()->url ?? $ad->images->first()->path); ?>" style="width: 100%; height: 100%; object-fit: cover;" alt="<?php echo e($ad->title); ?>">
                                        <?php else: ?>
                                            <div style="width: 100%; height: 100%; background: #f1f5f9; display: flex; align-items: center; justify-content: center; color: #94a3b8;">
                                                📷
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <div style="font-weight: 600; display: flex; align-items: center; gap: 8px; color: var(--text-primary);">
                                            <?php echo e($ad->title); ?>

                                            <?php if($ad->is_featured): ?>
                                                <span style="background: #f3e8ff; color: #7c3aed; padding: 2px 6px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">Featured</span>
                                            <?php endif; ?>
                                        </div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary); max-width: 250px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                            <?php echo e(Str::limit($ad->description, 50)); ?>

                                        </div>
                                        <div style="font-size: 0.8rem; color: #64748b; margin-top: 4px;">
                                            Seller: <?php echo e(optional($ad->user)->name ?? 'Unknown'); ?>

                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <?php
                                    $catColor = match(strtolower(optional($ad->category)->name ?? '')) {
                                        'electronics' => ['bg' => '#dbeafe', 'text' => '#3b82f6'],
                                        'vehicles' => ['bg' => '#dcfce7', 'text' => '#10b981'],
                                        'real estate' => ['bg' => '#fef3c7', 'text' => '#f59e0b'],
                                        'fashion' => ['bg' => '#f3e8ff', 'text' => '#7c3aed'],
                                        default => ['bg' => '#f1f5f9', 'text' => '#64748b']
                                    };
                                ?>
                                <span style="background: <?php echo e($catColor['bg']); ?>; color: <?php echo e($catColor['text']); ?>; padding: 4px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 600;">
                                    <?php echo e(optional($ad->category)->name ?? 'N/A'); ?>

                                </span>
                            </td>
                            <td style="font-weight: 600; color: var(--primary-color);">
                                <?php echo e($ad->currency); ?> <?php echo e(number_format($ad->price, 2)); ?>

                            </td>
                            <td>
                                <?php
                                    $statusColor = match(strtolower($ad->status)) {
                                        'active' => ['bg' => '#dcfce7', 'text' => '#10b981'],
                                        'pending' => ['bg' => '#fef3c7', 'text' => '#f59e0b'],
                                        'sold' => ['bg' => '#fee2e2', 'text' => '#ef4444'],
                                        'expired' => ['bg' => '#f1f5f9', 'text' => '#64748b'],
                                        default => ['bg' => '#f1f5f9', 'text' => '#64748b']
                                    };
                                ?>
                                <span class="status-badge" style="background: <?php echo e($statusColor['bg']); ?>; color: <?php echo e($statusColor['text']); ?>;">
                                    <?php echo e($ad->status); ?>

                                </span>
                            </td>
                            <td>
                                <div style="font-weight: 600; color: var(--text-primary);"><?php echo e($ad->location_city ?? $ad->city ?? 'N/A'); ?></div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);"><?php echo e($ad->location_country ?? $ad->country ?? 'N/A'); ?></div>
                            </td>
                            <td style="font-weight: 600; color: var(--text-primary);"><?php echo e(number_format($ad->views ?? 0)); ?></td>
                            <td style="color: var(--text-secondary); font-size: 0.875rem;"><?php echo e($ad->created_at->format('M d, Y')); ?></td>
                            <td>
                                <div style="display: flex; gap: 4px; flex-wrap: wrap;">
                                    <button onclick="viewAd(<?php echo e($ad->id); ?>)" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">
                                        View
                                    </button>
                                    
                                    <a href="<?php echo e(route('admin.ads.edit', $ad->id)); ?>" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; text-decoration: none; display: inline-block;">
                                        Edit
                                    </a>

                                    <a href="<?php echo e(route('admin.analytics.individual_ad', $ad->id)); ?>" style="padding: 4px 8px; background: #7c3aed; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; text-decoration: none; display: inline-block;">
                                        📊
                                    </a>

                                    <form action="<?php echo e(route('admin.ads.destroy', $ad->id)); ?>" method="POST" style="display:inline;" onsubmit="return confirm('Delete this ad?');">
                                        <?php echo csrf_field(); ?>
                                        <?php echo method_field('DELETE'); ?>
                                        <button type="submit" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">
                                            🗑️
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="9" class="text-center" style="padding: 24px; color: #64748b;">
                                <div style="display: flex; flex-direction: column; align-items: center; gap: 12px;">
                                    <div style="font-size: 2rem;">🔍</div>
                                    <div>No ads found matching your criteria.</div>
                                    <a href="<?php echo e(route('admin.ads.index')); ?>" style="color: var(--primary-color);">Clear Filters</a>
                                </div>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <?php echo e($ads->withQueryString()->links('pagination::bootstrap-5')); ?>

            </div>
        </div>
    </div>

    <!-- Add Ad Modal -->
    <div id="addAdModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Add New Ad</h3>
                <button onclick="hideAddAdModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="addAdForm" style="padding: 20px;">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Title</label>
                        <input type="text" name="title" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category</label>
                        <select name="category" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="electronics">Electronics</option>
                            <option value="vehicles">Vehicles</option>
                            <option value="real-estate">Real Estate</option>
                            <option value="fashion">Fashion</option>
                            <option value="home-garden">Home & Garden</option>
                        </select>
                    </div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                    <textarea name="description" rows="4" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;"></textarea>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Price</label>
                        <input type="number" name="price" step="0.01" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Currency</label>
                        <select name="currency" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="USD">USD - US Dollar</option>
                            <option value="EUR">EUR - Euro</option>
                            <option value="GBP">GBP - British Pound</option>
                            <option value="INR">INR - Indian Rupee</option>
                        </select>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                        <select name="status" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="active">Active</option>
                            <option value="pending">Pending</option>
                            <option value="sold">Sold</option>
                            <option value="expired">Expired</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Featured</label>
                        <select name="is_featured" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Seller Name</label>
                        <input type="text" name="seller_name" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Seller Email</label>
                        <input type="email" name="seller_email" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <!-- Location Fields -->
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Country</label>
                        <select name="country" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="USA">United States</option>
                            <option value="Canada">Canada</option>
                            <option value="UK">United Kingdom</option>
                            <option value="Germany">Germany</option>
                            <option value="Australia">Australia</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">State/Province</label>
                        <input type="text" name="state" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;" placeholder="e.g., California, Ontario, London">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">City</label>
                        <input type="text" name="city" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;" placeholder="e.g., San Francisco, Toronto, Manchester">
                    </div>
                </div>

                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Images</label>
                    <input type="file" name="images" multiple accept="image/*" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 8px;">
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="hideAddAdModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Add Ad</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Ad Modal -->
    <div id="editAdModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Edit Ad</h3>
                <button onclick="hideEditAdModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="editAdForm" style="padding: 20px;">
                <input type="hidden" name="ad_id" id="editAdId">
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Title</label>
                        <input type="text" name="title" id="editAdTitle" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category</label>
                        <select name="category" id="editAdCategory" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="electronics">Electronics</option>
                            <option value="vehicles">Vehicles</option>
                            <option value="real-estate">Real Estate</option>
                            <option value="fashion">Fashion</option>
                            <option value="home-garden">Home & Garden</option>
                        </select>
                    </div>
                </div>
                
                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                    <textarea name="description" id="editAdDescription" rows="4" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;"></textarea>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Price</label>
                        <input type="number" name="price" id="editAdPrice" step="0.01" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Currency</label>
                        <select name="currency" id="editAdCurrency" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="USD">USD - US Dollar</option>
                            <option value="EUR">EUR - Euro</option>
                            <option value="GBP">GBP - British Pound</option>
                            <option value="INR">INR - Indian Rupee</option>
                        </select>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                        <select name="status" id="editAdStatus" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="active">Active</option>
                            <option value="pending">Pending</option>
                            <option value="sold">Sold</option>
                            <option value="expired">Expired</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Featured</label>
                        <select name="is_featured" id="editAdFeatured" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="0">No</option>
                            <option value="1">Yes</option>
                        </select>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Seller Name</label>
                        <input type="text" name="seller_name" id="editAdSellerName" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Seller Email</label>
                        <input type="email" name="seller_email" id="editAdSellerEmail" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <!-- Location Fields -->
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Country</label>
                        <select name="country" id="editAdCountry" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="USA">United States</option>
                            <option value="Canada">Canada</option>
                            <option value="UK">United Kingdom</option>
                            <option value="Germany">Germany</option>
                            <option value="Australia">Australia</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">State/Province</label>
                        <input type="text" name="state" id="editAdState" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">City</label>
                        <input type="text" name="city" id="editAdCity" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    </div>
                </div>

                <div style="margin-bottom: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600;">Images</label>
                    <input type="file" name="images" multiple accept="image/*" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 8px;">
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="hideEditAdModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Update Ad</button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Ad Modal -->
    <!-- Enhanced View Ad Modal with Image Gallery and User Management -->
    <div id="viewAdModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 1200px; height: 85vh;">
            <div class="modal-header">
                <div style="display: flex; align-items: center; gap: 16px; justify-content: space-between; width: 100%;">
                    <div style="display: flex; align-items: center; gap: 16px;">
                        <h3 style="margin: 0;">Ad Details</h3>
                        <span id="adStatusBadge" class="status-badge" style="padding: 4px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 600;"></span>
                    </div>
                    <div style="display: flex; gap: 8px; align-items: center;">
                        <button onclick="showUserDetails()" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 6px; font-size: 0.875rem; cursor: pointer;">👤 User Details</button>
                        <button onclick="showSafetyReports()" style="padding: 6px 12px; background: #ef4444; color: white; border: none; border-radius: 6px; font-size: 0.875rem; cursor: pointer;">🛡️ Safety Reports</button>
                        <button onclick="hideViewAdModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
                    </div>
                </div>
            </div>
            
            <!-- Modal Tabs -->
            <div style="border-bottom: 1px solid var(--border-color); padding: 0 20px;">
                <div style="display: flex; gap: 0; border-bottom: 2px solid #e5e7eb;">
                    <button onclick="switchTab('ad-info')" id="tab-ad-info" class="tab-button active" style="padding: 12px 20px; border: none; background: none; cursor: pointer; font-weight: 600; color: var(--text-primary); border-bottom: 2px solid var(--primary-color);">Ad Information</button>
                    <button onclick="switchTab('images')" id="tab-images" class="tab-button" style="padding: 12px 20px; border: none; background: none; cursor: pointer; font-weight: 600; color: var(--text-secondary);">Image Gallery</button>
                    <button onclick="switchTab('user-details')" id="tab-user-details" class="tab-button" style="padding: 12px 20px; border: none; background: none; cursor: pointer; font-weight: 600; color: var(--text-secondary);">User Management</button>
                    <button onclick="switchTab('safety')" id="tab-safety" class="tab-button" style="padding: 12px 20px; border: none; background: none; cursor: pointer; font-weight: 600; color: var(--text-secondary);">Safety & Actions</button>
                </div>
            </div>
            
            <!-- Tab Content -->
            <div style="flex: 1; overflow-y: auto; padding: 20px;">
                <!-- Ad Information Tab -->
                <div id="tab-content-ad-info" class="tab-content active">
                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 24px; align-items: start;">
                        <!-- Left Column: Ad Images -->
                        <div style="display: flex; flex-direction: column; gap: 16px;">
                            <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 16px;">
                                <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">Ad Images</div>
                                <div style="display: grid; grid-template-columns: 1fr; gap: 8px;">
                                    <div style="width: 100%; height: 200px; border-radius: 8px; overflow: hidden; border: 1px solid var(--border-color); position: relative;">
                                        <img id="mainImage" src="" style="width: 100%; height: 100%; object-fit: cover;" alt="Ad Image">
                                        <div style="position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.7); color: white; padding: 4px 8px; border-radius: 12px; font-size: 0.75rem;">Main Image</div>
                                    </div>
                                    <div id="imageThumbnails" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;">
                                        <!-- Thumbnails will be loaded here -->
                                    </div>
                                </div>
                            </div>
                            
                            <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 16px;">
                                <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">Ad Statistics</div>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                    <div style="background: white; padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);">
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Total Views</div>
                                        <div style="font-size: 1.125rem; font-weight: 700; color: var(--primary-color);" id="adViews">0</div>
                                    </div>
                                    <div style="background: white; padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);">
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Created</div>
                                        <div style="font-size: 1.125rem; font-weight: 700; color: var(--text-primary);" id="adCreated">-</div>
                                    </div>
                                    <div style="background: white; padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);">
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Location</div>
                                        <div style="font-size: 1.125rem; font-weight: 700; color: var(--text-primary);" id="adLocation">-</div>
                                    </div>
                                    <div style="background: white; padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);">
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Category</div>
                                        <div style="font-size: 1.125rem; font-weight: 700; color: var(--text-primary);" id="adCategory">-</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Right Column: Ad Details -->
                        <div style="display: flex; flex-direction: column; gap: 16px;">
                            <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                                <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">Ad Information</div>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Title</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adTitle">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Category</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adCategoryFull">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Price</div>
                                        <div style="font-weight: 600; color: var(--primary-color);" id="adPrice">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Status</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adStatus">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Featured</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adFeatured">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Currency</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adCurrency">-</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Location Information Section -->
                            <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                                <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">Location Information</div>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">City</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adCity">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">State/Province</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adState">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Country</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adCountry">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Full Address</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adFullAddress">-</div>
                                    </div>
                                </div>
                                <div style="margin-top: 16px; background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Location on Map</div>
                                    <div style="width: 100%; height: 200px; background: #e2e8f0; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: var(--text-secondary);">
                                        🗺️ Interactive map would be displayed here with ad's exact location
                                    </div>
                                </div>
                            </div>
                            
                            <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                                <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">Description</div>
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color); min-height: 120px;">
                                    <div style="color: var(--text-primary); line-height: 1.6;" id="adDescription">-</div>
                                </div>
                            </div>

                            <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                                <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">Seller Information</div>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Seller Name</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adSellerName">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Seller Email</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adSellerEmail">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Account Age</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adAccountAge">-</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 4px;">Trust Score</div>
                                        <div style="font-weight: 600; color: var(--text-primary);" id="adTrustScore">-</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Image Gallery Tab -->
                <div id="tab-content-images" class="tab-content" style="display: none;">
                    <div style="display: grid; grid-template-columns: 1fr 3fr; gap: 24px;">
                        <!-- Image Thumbnails -->
                        <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 16px;">
                            <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">Image Gallery</div>
                            <div id="galleryThumbnails" style="display: grid; grid-template-columns: 1fr; gap: 12px; max-height: 60vh; overflow-y: auto;">
                                <!-- Gallery thumbnails will be loaded here -->
                            </div>
                        </div>
                        
                        <!-- Main Image Viewer -->
                        <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 16px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                                <div style="font-weight: 600; color: var(--text-primary);">Main Image Viewer</div>
                                <div style="display: flex; gap: 8px;">
                                    <button onclick="prevImage()" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">← Previous</button>
                                    <button onclick="nextImage()" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">Next →</button>
                                </div>
                            </div>
                            <div style="width: 100%; height: 500px; background: #e5e7eb; border-radius: 8px; display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden;">
                                <img id="galleryMainImage" src="" style="max-width: 100%; max-height: 100%; object-fit: contain;" alt="Gallery Image">
                                <div style="position: absolute; top: 12px; right: 12px; background: rgba(0,0,0,0.7); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.875rem;" id="imageCounter">1 / 1</div>
                            </div>
                            <div style="margin-top: 12px; text-align: center; color: var(--text-secondary); font-size: 0.875rem;" id="imageCaption">Image description</div>
                        </div>
                    </div>
                </div>

                <!-- User Management Tab -->
                <div id="tab-content-user-details" class="tab-content" style="display: none;">
                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 24px;">
                        <!-- User Profile -->
                        <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                            <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">User Profile</div>
                            <div style="display: flex; flex-direction: column; gap: 16px;">
                                <div style="text-align: center;">
                                    <div style="width: 120px; height: 120px; border-radius: 50%; background: #e5e7eb; margin: 0 auto 12px; display: flex; align-items: center; justify-content: center; color: var(--text-secondary); font-size: 2rem;">👤</div>
                                    <div style="font-weight: 600; color: var(--text-primary);" id="userProfileName">-</div>
                                    <div style="font-size: 0.875rem; color: var(--text-secondary);" id="userProfileEmail">-</div>
                                </div>
                                
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">User Statistics</div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.875rem;">
                                        <div>Total Ads: <span id="userTotalAds" style="font-weight: 600; color: var(--primary-color);">0</span></div>
                                        <div>Active Ads: <span id="userActiveAds" style="font-weight: 600; color: #10b981;">0</span></div>
                                        <div>Featured Ads: <span id="userFeaturedAds" style="font-weight: 600; color: #7c3aed;">0</span></div>
                                        <div>Account Age: <span id="userAccountAge" style="font-weight: 600;">0 days</span></div>
                                    </div>
                                </div>

                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Trust & Safety</div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.875rem;">
                                        <div>Trust Score: <span id="userTrustScore" style="font-weight: 600; color: #10b981;">0/100</span></div>
                                        <div>Verified: <span id="userVerified" style="font-weight: 600; color: #10b981;">Yes</span></div>
                                        <div>Safety Reports: <span id="userSafetyReports" style="font-weight: 600; color: #ef4444;">0</span></div>
                                        <div>Appeals Pending: <span id="userAppealsPending" style="font-weight: 600; color: #f59e0b;">0</span></div>
                                    </div>
                                </div>

                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Account Status</div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.875rem;">
                                        <div>Is Banned: <span id="userIsBanned" style="font-weight: 600; color: #ef4444;">No</span></div>
                                        <div>Is Suspended: <span id="userIsSuspended" style="font-weight: 600; color: #f59e0b;">No</span></div>
                                        <div>Last Login: <span id="userLastLogin" style="font-weight: 600;">-</span></div>
                                        <div>Member Since: <span id="userMemberSince" style="font-weight: 600;">-</span></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- User Actions -->
                        <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                            <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">User Management Actions</div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                <!-- Ban/Suspend Actions -->
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">Account Actions</div>
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                                        <button onclick="banUser()" style="padding: 10px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🚫 Ban User</button>
                                        <button onclick="suspendUser()" style="padding: 10px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">⏸️ Suspend User</button>
                                        <button onclick="verifyUser()" style="padding: 10px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">✅ Verify User</button>
                                        <button onclick="contactUser()" style="padding: 10px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">📧 Contact User</button>
                                    </div>
                                </div>

                                <!-- User's Other Ads -->
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">User's Other Ads</div>
                                    <div id="userOtherAds" style="display: grid; grid-template-columns: 1fr; gap: 8px; max-height: 200px; overflow-y: auto;">
                                        <!-- User's other ads will be loaded here -->
                                    </div>
                                    <button onclick="viewAllUserAds()" style="margin-top: 12px; padding: 8px; background: #8b5cf6; color: white; border: none; border-radius: 6px; cursor: pointer; width: 100%; font-weight: 600;">View All Ads</button>
                                </div>

                                <!-- Quick Actions -->
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">Quick Actions</div>
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                                        <button onclick="resetUserPassword()" style="padding: 10px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🔑 Reset Password</button>
                                        <button onclick="changeUserEmail()" style="padding: 10px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">📧 Change Email</button>
                                        <button onclick="viewUserActivity()" style="padding: 10px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">📊 View Activity</button>
                                        <button onclick="exportUserReport()" style="padding: 10px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">📄 Export Report</button>
                                    </div>
                                </div>

                                <!-- Risk Assessment -->
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 12px; color: var(--text-primary);">Risk Assessment</div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.875rem;">
                                        <div>Risk Level: <span id="userRiskLevel" style="font-weight: 600; color: #ef4444;">High</span></div>
                                        <div>Suspicious Activity: <span id="userSuspiciousActivity" style="font-weight: 600; color: #f59e0b;">Yes</span></div>
                                        <div>Last Report: <span id="userLastReport" style="font-weight: 600;">-</span></div>
                                        <div>Warning Count: <span id="userWarningCount" style="font-weight: 600; color: #ef4444;">0</span></div>
                                    </div>
                                    <div style="margin-top: 12px; padding: 8px; background: #fee2e2; border: 1px solid #fecaca; border-radius: 6px; color: #991b1b; font-size: 0.875rem; text-align: center;">
                                        ⚠️ User flagged for suspicious activity
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Safety & Actions Tab -->
                <div id="tab-content-safety" class="tab-content" style="display: none;">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
                        <!-- Safety Reports -->
                        <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                            <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">Safety Reports</div>
                            <div id="safetyReportsList" style="display: grid; grid-template-columns: 1fr; gap: 12px;">
                                <!-- Safety reports will be loaded here -->
                            </div>
                            <button onclick="viewAllSafetyReports()" style="margin-top: 16px; padding: 10px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; width: 100%; font-weight: 600;">View All Reports</button>
                        </div>
                        
                        <!-- Ad Actions -->
                        <div style="background: #f8fafc; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px;">
                            <div style="font-weight: 600; margin-bottom: 16px; color: var(--text-primary); font-size: 1.1rem;">Ad Management Actions</div>
                            <div style="display: grid; grid-template-columns: 1fr; gap: 12px;">
                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Status Actions</div>
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                                        <button onclick="approveAdFromModal()" style="padding: 10px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">✅ Approve Ad</button>
                                        <button onclick="rejectAdFromModal()" style="padding: 10px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">❌ Reject Ad</button>
                                        <button onclick="deactivateAdFromModal()" style="padding: 10px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">⏸️ Deactivate Ad</button>
                                        <button onclick="reactivateAdFromModal()" style="padding: 10px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🔄 Reactivate Ad</button>
                                    </div>
                                </div>

                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Featured & Boost</div>
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                                        <button onclick="makeFeaturedFromModal()" style="padding: 10px; background: #7c3aed; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">⭐ Make Featured</button>
                                        <button onclick="removeFeaturedFromModal()" style="padding: 10px; background: #8b5cf6; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">❌ Remove Featured</button>
                                        <button onclick="boostAdFromModal()" style="padding: 10px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🚀 Boost Ad</button>
                                        <button onclick="unboostAdFromModal()" style="padding: 10px; background: #f97316; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">⬇️ Unboost Ad</button>
                                    </div>
                                </div>

                                <div style="background: white; padding: 16px; border-radius: 8px; border: 1px solid var(--border-color);">
                                    <div style="font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Danger Zone</div>
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                                        <button onclick="deleteAdFromModal()" style="padding: 10px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🗑️ Delete Ad</button>
                                        <button onclick="archiveAdFromModal()" style="padding: 10px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">📦 Archive Ad</button>
                                        <button onclick="flagAdFromModal()" style="padding: 10px; background: #dc2626; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🚩 Flag Ad</button>
                                        <button onclick="reportAdFromModal()" style="padding: 10px; background: #b91c1c; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🚨 Report Ad</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Confirmation Modal -->
    <div id="confirmModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h3 style="margin: 0;" id="confirmTitle">Confirm Action</h3>
                <button onclick="hideConfirmModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div style="padding: 20px;">
                <p id="confirmMessage">Are you sure you want to perform this action?</p>
                <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
                    <button onclick="hideConfirmModal()" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button id="confirmActionBtn" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Confirm</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bulk Actions Modal -->
    <div id="bulkActionsModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Bulk Actions</h3>
                <button onclick="document.getElementById('bulkActionsModal').style.display='none'" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div style="padding: 20px;">
                <p>You have selected <span id="selectedCount" style="font-weight: bold;">0</span> ads.</p>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 20px;">
                    <button onclick="bulkApprove()" style="padding: 12px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Approve Selected</button>
                    <button onclick="bulkReject()" style="padding: 12px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer;">Reject Selected</button>
                    <button onclick="bulkDeactivate()" style="padding: 12px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer;">Deactivate Selected</button>
                    <button onclick="document.getElementById('bulkActionsModal').style.display='none'" style="padding: 12px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Approval Settings Modal -->
    <div id="approvalSettingsModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3 style="margin: 0;">Approval Settings</h3>
                <button onclick="document.getElementById('approvalSettingsModal').style.display='none'" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <form id="approvalSettingsForm" style="padding: 20px;">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Auto Approval</label>
                        <select name="auto_approve_ads" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                            <option value="1">Enabled</option>
                            <option value="0">Disabled</option>
                        </select>
                        <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">When enabled, new ads are automatically approved</div>
                    </div>
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Default Ad Validity (Days)</label>
                        <input type="number" name="default_ad_validity_days" min="1" max="365" value="30" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">Default number of days ads remain active</div>
                    </div>
                </div>
                <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
                    <button type="button" onclick="document.getElementById('approvalSettingsModal').style.display='none'" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer;">Cancel</button>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Save Settings</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Server-side data injected from PHP
        const serverStats = {
            total: <?php echo e($stats['total']); ?>,
            active: <?php echo e($stats['active']); ?>,
            pending: <?php echo e($stats['pending']); ?>,
            expired: <?php echo e($stats['expired'] ?? 0); ?>,
            sold: <?php echo e($stats['sold'] ?? 0); ?>,
            featured: <?php echo e($stats['featured']); ?>

        };

        const statusDistribution = <?php echo json_encode($statusDistribution, 15, 512) ?>;
        const categoryDistribution = <?php echo json_encode($categoryDistribution, 15, 512) ?>;
        const locationDistribution = <?php echo json_encode($locationDistribution, 15, 512) ?>;
        const locationCounts = <?php echo json_encode($locationCounts, 15, 512) ?>;

        // State management
        let ads = [];
        let filteredAds = [];
        let currentPage = 1;
        let pageSize = 25;
        let totalAds = serverStats.total;

        // Initialize with server data
        function initializeCharts() {
            // Populate charts with server data
            renderStatusChart(statusDistribution);
            renderCategoryChart(categoryDistribution);
            renderLocationChart(locationDistribution);
            renderTopLocationsTable(locationDistribution);
        }

        // Initialize with real data from server
        async function initializeAds() {
            try {
                // Load ads from server-side data
                const serverAds = <?php echo json_encode($ads->items(), 15, 512) ?>;
                
                // Transform server ads to match expected format
                ads = serverAds.map(ad => ({
                    id: ad.id,
                    title: ad.title,
                    description: ad.description,
                    category: ad.category ? ad.category.name.toLowerCase().replace(/ /g, '-') : 'other',
                    price: parseFloat(ad.price),
                    currency: ad.currency || 'INR',
                    status: ad.status ? ad.status.toLowerCase() : 'active',
                    isFeatured: ad.is_featured || false,
                    sellerName: ad.user ? ad.user.name : 'Unknown',
                    sellerEmail: ad.user ? ad.user.email : 'unknown@example.com',
                    views: ad.view_count || 0,
                    created: ad.created_at ? ad.created_at.split(' ')[0] : new Date().toISOString().split('T')[0],
                    images: ad.images && ad.images.length > 0 
                        ? ad.images.map(img => img.path || img.url) 
                        : ['https://via.placeholder.com/300?text=No+Image'],
                    location: {
                        city: ad.location_city || ad.city || 'Unknown',
                        state: ad.location_state || ad.state || 'Unknown',
                        country: ad.location_country || ad.country || 'Unknown'
                    }
                }));
                
                // Use server-side stats
                totalAds = serverStats.total;
                
                filteredAds = [...ads];
                renderAds();
                updatePagination();
                updateOverviewStats();
                updateCharts();
            } catch (error) {
                console.error('Error loading data:', error);
                // Fallback to sample data if transformation fails
                loadSampleData();
            }
        }

        // Fallback sample data function
        function loadSampleData() {
            ads = [
                { 
                    id: 1, 
                    title: 'iPhone 15 Pro Max', 
                    category: 'electronics', 
                    price: 1199.99, 
                    currency: 'USD', 
                    status: 'active', 
                    isFeatured: true,
                    sellerName: 'Tech Store',
                    sellerEmail: 'sales@techstore.com',
                    views: 1234,
                    created: '2024-01-15',
                    images: ['https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=300&h=300&fit=crop'],
                    location: { city: 'San Francisco', state: 'California', country: 'USA' }
                },
                { 
                    id: 2, 
                    title: '2023 Tesla Model Y', 
                    category: 'vehicles', 
                    price: 52990.00, 
                    currency: 'USD', 
                    status: 'pending', 
                    isFeatured: false,
                    sellerName: 'Auto Dealership',
                    sellerEmail: 'sales@autodealer.com',
                    views: 892,
                    created: '2024-01-14',
                    images: ['https://images.unsplash.com/photo-1580273916550-e323be2ae537?w=300&h=300&fit=crop'],
                    location: { city: 'Los Angeles', state: 'California', country: 'USA' }
                },
                { 
                    id: 3, 
                    title: 'Designer Watch Collection', 
                    category: 'fashion', 
                    price: 2999.50, 
                    currency: 'USD', 
                    status: 'sold', 
                    isFeatured: true,
                    sellerName: 'Luxury Boutique',
                    sellerEmail: 'info@luxuryboutique.com',
                    views: 1567,
                    created: '2024-01-13',
                    images: ['https://images.unsplash.com/photo-1524805444758-089113d48a6d?w=300&h=300&fit=crop'],
                    location: { city: 'New York', state: 'New York', country: 'USA' }
                },
                { 
                    id: 4, 
                    title: 'Modern Sofa Set', 
                    category: 'home-garden', 
                    price: 1299.00, 
                    currency: 'USD', 
                    status: 'active', 
                    isFeatured: false,
                    sellerName: 'Home Decor',
                    sellerEmail: 'sales@homedecor.com',
                    views: 456,
                    created: '2024-01-12',
                    images: ['https://images.unsplash.com/photo-1519710164239-da123dc03ef4?w=300&h=300&fit=crop'],
                    location: { city: 'Chicago', state: 'Illinois', country: 'USA' }
                },
                { 
                    id: 5, 
                    title: '1 Bedroom Apartment', 
                    category: 'real-estate', 
                    price: 250000.00, 
                    currency: 'USD', 
                    status: 'active', 
                    isFeatured: true,
                    sellerName: 'Real Estate Agent',
                    sellerEmail: 'agent@realestate.com',
                    views: 2156,
                    created: '2024-01-11',
                    images: ['https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=300&h=300&fit=crop'],
                    location: { city: 'Miami', state: 'Florida', country: 'USA' }
                },
                { 
                    id: 6, 
                    title: 'Gaming Laptop RTX 4080', 
                    category: 'electronics', 
                    price: 2499.99, 
                    currency: 'USD', 
                    status: 'expired', 
                    isFeatured: false,
                    sellerName: 'Gaming Store',
                    sellerEmail: 'support@gamingstore.com',
                    views: 891,
                    created: '2024-01-10',
                    images: ['https://images.unsplash.com/photo-1496181133206-80ce9b88a853?w=300&h=300&fit=crop'],
                    location: { city: 'Seattle', state: 'Washington', country: 'USA' }
                },
                { 
                    id: 7, 
                    title: 'Vintage Guitar', 
                    category: 'fashion', 
                    price: 899.00, 
                    currency: 'USD', 
                    status: 'active', 
                    isFeatured: false,
                    sellerName: 'Music Shop',
                    sellerEmail: 'info@musicshop.com',
                    views: 342,
                    created: '2024-01-09',
                    images: ['https://images.unsplash.com/photo-1517457373958-b7bdd4587205?w=300&h=300&fit=crop'],
                    location: { city: 'Austin', state: 'Texas', country: 'USA' }
                },
                { 
                    id: 8, 
                    title: 'Family Car SUV', 
                    category: 'vehicles', 
                    price: 32000.00, 
                    currency: 'USD', 
                    status: 'pending', 
                    isFeatured: true,
                    sellerName: 'Car Dealership',
                    sellerEmail: 'sales@cardealer.com',
                    views: 1123,
                    created: '2024-01-08',
                    images: ['https://images.unsplash.com/photo-1549317665-b5cda722d186?w=300&h=300&fit=crop'],
                    location: { city: 'Denver', state: 'Colorado', country: 'USA' }
                },
                { 
                    id: 9, 
                    title: 'Smart Home Security System', 
                    category: 'electronics', 
                    price: 499.99, 
                    currency: 'USD', 
                    status: 'active', 
                    isFeatured: false,
                    sellerName: 'Tech Solutions',
                    sellerEmail: 'support@techsolutions.com',
                    views: 678,
                    created: '2024-01-07',
                    images: ['https://images.unsplash.com/photo-1581091012217-3c332b9b989c?w=300&h=300&fit=crop'],
                    location: { city: 'Boston', state: 'Massachusetts', country: 'USA' }
                },
                { 
                    id: 10, 
                    title: 'Office Desk Chair', 
                    category: 'home-garden', 
                    price: 299.50, 
                    currency: 'USD', 
                    status: 'active', 
                    isFeatured: false,
                    sellerName: 'Office Supplies',
                    sellerEmail: 'sales@officesupplies.com',
                    views: 234,
                    created: '2024-01-06',
                    images: ['https://images.unsplash.com/photo-1519710164239-da123dc03ef4?w=300&h=300&fit=crop'],
                    location: { city: 'Philadelphia', state: 'Pennsylvania', country: 'USA' }
                },
                { 
                    id: 11, 
                    title: 'Designer Handbag', 
                    category: 'fashion', 
                    price: 1299.00, 
                    currency: 'EUR', 
                    status: 'active', 
                    isFeatured: true,
                    sellerName: 'Boutique Paris',
                    sellerEmail: 'contact@boutiqueparis.com',
                    views: 567,
                    created: '2024-01-05',
                    images: ['https://images.unsplash.com/photo-1548126032-079a0fb0099d?w=300&h=300&fit=crop'],
                    location: { city: 'Paris', state: 'Île-de-France', country: 'France' }
                },
                { 
                    id: 12, 
                    title: 'Mountain Bike', 
                    category: 'vehicles', 
                    price: 899.99, 
                    currency: 'GBP', 
                    status: 'pending', 
                    isFeatured: false,
                    sellerName: 'Cycle Shop',
                    sellerEmail: 'info@cycleshop.co.uk',
                    views: 432,
                    created: '2024-01-04',
                    images: ['https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300&h=300&fit=crop'],
                    location: { city: 'London', state: 'England', country: 'UK' }
                },
                { 
                    id: 13, 
                    title: 'Smartphone Samsung Galaxy', 
                    category: 'electronics', 
                    price: 899.00, 
                    currency: 'INR', 
                    status: 'active', 
                    isFeatured: false,
                    sellerName: 'Tech India',
                    sellerEmail: 'sales@techindia.com',
                    views: 789,
                    created: '2024-01-03',
                    images: ['https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=300&h=300&fit=crop'],
                    location: { city: 'Mumbai', state: 'Maharashtra', country: 'India' }
                },
                { 
                    id: 14, 
                    title: 'Designer Sunglasses', 
                    category: 'fashion', 
                    price: 299.00, 
                    currency: 'CAD', 
                    status: 'sold', 
                    isFeatured: true,
                    sellerName: 'Style Canada',
                    sellerEmail: 'hello@stylecanada.ca',
                    views: 321,
                    created: '2024-01-02',
                    images: ['https://images.unsplash.com/photo-1528605248644-14dd04022da1?w=300&h=300&fit=crop'],
                    location: { city: 'Toronto', state: 'Ontario', country: 'Canada' }
                },
                { 
                    id: 15, 
                    title: 'Coffee Maker', 
                    category: 'home-garden', 
                    price: 199.99, 
                    currency: 'AUD', 
                    status: 'active', 
                    isFeatured: false,
                    sellerName: 'Home Australia',
                    sellerEmail: 'support@homeaustralia.com.au',
                    views: 256,
                    created: '2024-01-01',
                    images: ['https://images.unsplash.com/photo-1595508184132-9d7e47be0deb?w=300&h=300&fit=crop'],
                    location: { city: 'Sydney', state: 'New South Wales', country: 'Australia' }
                }
            ];
            totalAds = ads.length;
            filteredAds = [...ads];
            renderAds();
            updatePagination();
            updateOverviewStats();
            updateCharts();
        }

        // Filtering and Search
        function searchAds() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const categoryFilter = document.getElementById('categoryFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            const countryFilter = document.getElementById('countryFilter').value;

            filteredAds = ads.filter(ad => {
                const matchesSearch = ad.title.toLowerCase().includes(searchTerm) || 
                                     ad.description?.toLowerCase().includes(searchTerm) ||
                                     ad.sellerName.toLowerCase().includes(searchTerm) ||
                                     ad.sellerEmail.toLowerCase().includes(searchTerm);
                const matchesCategory = !categoryFilter || ad.category === categoryFilter;
                const matchesStatus = !statusFilter || ad.status === statusFilter;
                const matchesCountry = !countryFilter || ad.location.country === countryFilter;
                
                return matchesSearch && matchesCategory && matchesStatus && matchesCountry;
            });

            currentPage = 1;
            renderAds();
            updatePagination();
            updateOverviewStats();
        }

        // Overview Statistics
        function updateOverviewStats() {
            const total = filteredAds.length;
            const active = filteredAds.filter(ad => ad.status === 'active').length;
            const pending = filteredAds.filter(ad => ad.status === 'pending').length;
            const sold = filteredAds.filter(ad => ad.status === 'sold').length;
            const expired = filteredAds.filter(ad => ad.status === 'expired').length;

            // Count unique locations
            const countries = new Set(filteredAds.map(ad => ad.location.country));
            const states = new Set(filteredAds.map(ad => `${ad.location.country}-${ad.location.state}`));
            const cities = new Set(filteredAds.map(ad => `${ad.location.country}-${ad.location.state}-${ad.location.city}`));

            // Update main stats
            document.getElementById('totalAdsCount').textContent = total.toLocaleString();
            document.getElementById('activeAdsCount').textContent = active.toLocaleString();
            document.getElementById('countryAdsCount').textContent = countries.size;
            document.getElementById('stateAdsCount').textContent = states.size;
            document.getElementById('cityAdsCount').textContent = cities.size;
            document.getElementById('pendingAdsCount').textContent = pending.toLocaleString();

            // Update percentages and changes
            const activePercentage = total > 0 ? ((active / total) * 100).toFixed(1) : 0;
            document.querySelector('.dashboard-grid .card:nth-child(2) .card-change').textContent = `${activePercentage}% of total`;
            document.querySelector('.dashboard-grid .card:nth-child(3) .card-change').textContent = 'Countries with ads';
            document.querySelector('.dashboard-grid .card:nth-child(4) .card-change').textContent = 'States/provinces with ads';
            document.querySelector('.dashboard-grid .card:nth-child(5) .card-change').textContent = 'Cities with ads';
            document.querySelector('.dashboard-grid .card:nth-child(6) .card-change').textContent = 'Needs admin attention';
        }

        // Pagination Logic
        function changePage(direction) {
            const totalPages = Math.ceil(filteredAds.length / pageSize);
            const newPage = currentPage + direction;
            
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                renderAds();
                updatePagination();
            }
        }

        function changePageSize() {
            pageSize = parseInt(document.getElementById('pageSize').value);
            currentPage = 1;
            renderAds();
            updatePagination();
        }

        function goToPage(page) {
            const totalPages = Math.ceil(filteredAds.length / pageSize);
            if (page >= 1 && page <= totalPages) {
                currentPage = page;
                renderAds();
                updatePagination();
            }
        }

        function updatePagination() {
            const totalPages = Math.ceil(filteredAds.length / pageSize);
            const start = (currentPage - 1) * pageSize + 1;
            const end = Math.min(currentPage * pageSize, filteredAds.length);
            const total = filteredAds.length;

            document.getElementById('showingStart').textContent = start;
            document.getElementById('showingEnd').textContent = end;
            document.getElementById('totalCount').textContent = total;

            // Update Previous/Next buttons
            const prevBtn = document.getElementById('prevPage');
            const nextBtn = document.getElementById('nextPage');
            prevBtn.disabled = currentPage === 1;
            nextBtn.disabled = currentPage === totalPages;

            // Generate page numbers
            const pageNumbersContainer = document.getElementById('pageNumbers');
            pageNumbersContainer.innerHTML = '';

            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const btn = document.createElement('button');
                btn.textContent = i;
                btn.onclick = () => goToPage(i);
                btn.style.padding = '6px 12px';
                btn.style.border = '1px solid var(--border-color)';
                btn.style.borderRadius = '6px';
                btn.style.background = i === currentPage ? 'var(--primary-color)' : 'white';
                btn.style.color = i === currentPage ? 'white' : 'black';
                btn.style.cursor = 'pointer';
                pageNumbersContainer.appendChild(btn);
            }
        }

        // Rendering
        /* function renderAds() { */
        function renderAdsDisabled() {
            const tbody = document.getElementById('adsTableBody');
            tbody.innerHTML = '';

            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageAds = filteredAds.slice(startIndex, endIndex);

            pageAds.forEach(ad => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" class="ad-checkbox" data-ad-id="${ad.id}" style="width: 16px; height: 16px;"></td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; border: 1px solid var(--border-color);">
                                <img src="${ad.images[0]}" style="width: 100%; height: 100%; object-fit: cover;" alt="${ad.title}">
                            </div>
                            <div>
                                <div style="font-weight: 600; display: flex; align-items: center; gap: 8px;">
                                    ${ad.title}
                                    ${ad.isFeatured ? '<span style="background: #f3e8ff; color: #7c3aed; padding: 2px 6px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">Featured</span>' : ''}
                                </div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">${ad.description || 'No description'}</div>
                                <div style="font-size: 0.8rem; color: #64748b; margin-top: 4px;">Seller: ${ad.sellerName}</div>
                            </div>
                        </div>
                    </td>
                    <td>${getCategoryBadge(ad.category)}</td>
                    <td style="font-weight: 600; color: var(--primary-color);">${formatCurrency(ad.price, ad.currency)}</td>
                    <td>${getStatusBadge(ad.status)}</td>
                    <td>
                        <div style="font-weight: 600; color: var(--text-primary);">${ad.location.city}</div>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);">${ad.location.state}, ${ad.location.country}</div>
                    </td>
                    <td style="font-weight: 600; color: var(--text-primary);">${ad.views.toLocaleString()}</td>
                    <td style="color: var(--text-secondary); font-size: 0.875rem;">${formatDate(ad.created)}</td>
                    <td>
                        ${getActionButtons(ad)}
                    </td>
                `;
                tbody.appendChild(row);
            });

            // Update select all checkbox
            const checkboxes = document.querySelectorAll('.ad-checkbox');
            const selectAll = document.getElementById('selectAll');
            selectAll.checked = checkboxes.length > 0 && Array.from(checkboxes).every(cb => cb.checked);
        }

        function getCategoryBadge(category) {
            const categoryConfig = {
                'electronics': { bg: '#dbeafe', color: '#3b82f6', text: 'Electronics' },
                'vehicles': { bg: '#dcfce7', color: '#10b981', text: 'Vehicles' },
                'real-estate': { bg: '#fef3c7', color: '#f59e0b', text: 'Real Estate' },
                'fashion': { bg: '#f3e8ff', color: '#7c3aed', text: 'Fashion' },
                'home-garden': { bg: '#fee2e2', color: '#ef4444', text: 'Home & Garden' }
            };
            const config = categoryConfig[category] || categoryConfig.electronics;
            return `<span style="background: ${config.bg}; color: ${config.color}; padding: 4px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: 600;">${config.text}</span>`;
        }

        function getCategoryText(category) {
            const categoryTexts = {
                'electronics': 'Electronics',
                'vehicles': 'Vehicles',
                'real-estate': 'Real Estate',
                'fashion': 'Fashion',
                'home-garden': 'Home & Garden'
            };
            return categoryTexts[category] || 'Unknown';
        }

        function getStatusBadge(status) {
            const statusConfig = {
                'active': { bg: '#dcfce7', color: '#10b981', text: 'Active' },
                'pending': { bg: '#fef3c7', color: '#f59e0b', text: 'Pending' },
                'sold': { bg: '#fee2e2', color: '#ef4444', text: 'Sold' },
                'expired': { bg: '#f1f5f9', color: '#64748b', text: 'Expired' }
            };
            const config = statusConfig[status] || statusConfig.pending;
            return `<span class="status-badge" style="background: ${config.bg}; color: ${config.color};">${config.text}</span>`;
        }

        function getStatusText(status) {
            const statusTexts = {
                'active': 'Active',
                'pending': 'Pending',
                'sold': 'Sold',
                'expired': 'Expired'
            };
            return statusTexts[status] || 'Unknown';
        }

        function getActionButtons(ad) {
            let buttons = '';
            
            // View button
            buttons += `<button onclick="viewAd(${ad.id})" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">View</button>`;
            
            // Analytics button
            buttons += `<a href="/admin/analytics/ad/${ad.id}" style="padding: 4px 8px; background: #7c3aed; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px; text-decoration: none; display: inline-block;">📊 Analytics</a>`;
            
            // Enhanced Analytics button
            buttons += `<a href="/admin/analytics/ad/${ad.id}/enhanced" style="padding: 4px 8px; background: #f59e0b; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px; text-decoration: none; display: inline-block;">🛡️ Enhanced Analytics</a>`;
            
            // Edit button - Allow editing for rejected ads
            if (ad.status === 'rejected') {
                buttons += `<a href="/admin/ads/${ad.id}/edit" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px; text-decoration: none; display: inline-block;">Edit & Resubmit</a>`;
            } else {
                buttons += `<a href="/admin/ads/${ad.id}/edit" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px; text-decoration: none; display: inline-block;">Edit</a>`;
            }

            // Status-specific buttons
            if (ad.status === 'active') {
                buttons += `<button onclick="deactivateAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #f59e0b; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Deactivate</button>`;
            } else if (ad.status === 'pending') {
                buttons += `<button onclick="approveAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Approve</button>`;
                buttons += `<button onclick="rejectAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Reject</button>`;
            } else if (ad.status === 'rejected') {
                buttons += `<button onclick="approveAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Approve</button>`;
                buttons += `<button onclick="rejectAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Reject Again</button>`;
            } else if (ad.status === 'sold') {
                buttons += `<button onclick="reactivateAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Reactivate</button>`;
            } else if (ad.status === 'expired') {
                buttons += `<button onclick="renewAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Renew</button>`;
            }

            // Featured toggle
            if (ad.isFeatured) {
                buttons += `<button onclick="toggleFeatured(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #7c3aed; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Remove Featured</button>`;
            } else {
                buttons += `<button onclick="toggleFeatured(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #7c3aed; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer; margin-right: 4px;">Make Featured</button>`;
            }

            // Delete button
            buttons += `<button onclick="deleteAd(${ad.id}, '${ad.title}')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Delete</button>`;

            return `<div style="display: flex; gap: 8px;">${buttons}</div>`;
        }

        function formatCurrency(amount, currency) {
            const currencySymbols = {
                'USD': '$',
                'EUR': '€',
                'GBP': '£',
                'INR': '₹',
                'CAD': 'C$',
                'AUD': 'A$'
            };
            const symbol = currencySymbols[currency] || currency;
            return `${symbol}${amount.toLocaleString()}`;
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
        }

        // Modal Functions
        function showAddAdModal() {
            document.getElementById('addAdModal').style.display = 'block';
        }

        function hideAddAdModal() {
            document.getElementById('addAdModal').style.display = 'none';
        }

        function showEditAdModal(adId, title, category, description, price, currency, status, isFeatured, sellerName, sellerEmail, country, state, city) {
            document.getElementById('editAdId').value = adId;
            document.getElementById('editAdTitle').value = title;
            document.getElementById('editAdCategory').value = category;
            document.getElementById('editAdDescription').value = description || '';
            document.getElementById('editAdPrice').value = price;
            document.getElementById('editAdCurrency').value = currency;
            document.getElementById('editAdStatus').value = status;
            document.getElementById('editAdFeatured').value = isFeatured ? '1' : '0';
            document.getElementById('editAdSellerName').value = sellerName;
            document.getElementById('editAdSellerEmail').value = sellerEmail;
            document.getElementById('editAdCountry').value = country;
            document.getElementById('editAdState').value = state;
            document.getElementById('editAdCity').value = city;
            document.getElementById('editAdModal').style.display = 'block';
        }

        function hideEditAdModal() {
            document.getElementById('editAdModal').style.display = 'none';
        }

        function showConfirmModal(title, message, action) {
            document.getElementById('confirmTitle').textContent = title;
            document.getElementById('confirmMessage').textContent = message;
            document.getElementById('confirmActionBtn').onclick = action;
            document.getElementById('confirmModal').style.display = 'block';
        }

        function hideConfirmModal() {
            document.getElementById('confirmModal').style.display = 'none';
        }

        // Action Functions
        function exportAds() {
            alert('Export functionality would be implemented with server-side processing');
        }

        function showBulkActions() {
            const selectedAds = Array.from(document.querySelectorAll('.ad-checkbox:checked')).map(cb => cb.dataset.adId);
            if (selectedAds.length === 0) {
                alert('Please select at least one ad to perform bulk actions.');
                return;
            }
            
            // Show bulk actions modal
            const modal = document.getElementById('bulkActionsModal');
            const selectedCount = document.getElementById('selectedCount');
            selectedCount.textContent = selectedAds.length;
            modal.style.display = 'block';
            
            // Store selected ads for bulk operations
            window.selectedAds = selectedAds;
        }

        // Approval Functions - Full Backend Integration
        function approveAd(adId, adTitle) {
            showConfirmModal(
                'Approve Ad',
                `Are you sure you want to approve "${adTitle}"?`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/${adId}/approve`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                            // Update local data
                            const adIndex = ads.findIndex(a => a.id === adId);
                            if (adIndex !== -1) {
                                ads[adIndex].status = 'active';
                                ads[adIndex].approved_at = new Date().toISOString();
                                ads[adIndex].approved_by = 1; // Admin ID
                                filteredAds = [...ads];
                                renderAds();
                                updatePagination();
                                updateOverviewStats();
                            }
                            
                            // Close modals
                            hideConfirmModal();
                            hideViewAdModal();
                            alert('Ad approved successfully!');
                        } else {
                            alert('Error: ' + (data.message || 'Failed to approve ad'));
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while approving the ad.');
                    }
                }
            );
        }

        async function rejectAd(adId, adTitle) {
            const reason = prompt(`Please provide a reason for rejecting "${adTitle}":`, 'Inappropriate content');
            if (reason !== null && reason.trim() !== '') {
                try {
                    const response = await fetch(`/admin/ads/${adId}/reject`, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ rejection_reason: reason.trim() })
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok && data.success) {
                        // Update local data
                        const adIndex = ads.findIndex(a => a.id === adId);
                        if (adIndex !== -1) {
                            ads[adIndex].status = 'rejected';
                            ads[adIndex].rejected_at = new Date().toISOString();
                            ads[adIndex].rejected_by = 1; // Admin ID
                            ads[adIndex].rejection_reason = reason.trim();
                            filteredAds = [...ads];
                            renderAds();
                            updatePagination();
                            updateOverviewStats();
                            updateCharts(); // Update charts with new data
                        }
                        
                        alert('Ad rejected successfully!');
                        // Close any open modals
                        hideConfirmModal();
                        hideViewAdModal();
                    } else {
                        alert('Error: ' + (data.message || 'Failed to reject ad'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred while rejecting the ad.');
                }
            }
        }

        function deactivateAd(adId, adTitle) {
            showConfirmModal(
                'Deactivate Ad',
                `Are you sure you want to deactivate "${adTitle}"?`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/${adId}/deactivate`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                            // Update local data
                            const adIndex = ads.findIndex(a => a.id === adId);
                            if (adIndex !== -1) {
                                ads[adIndex].status = 'pending';
                                ads[adIndex].deactivated_at = new Date().toISOString();
                                ads[adIndex].deactivated_by = 1; // Admin ID
                                filteredAds = [...ads];
                                renderAds();
                                updatePagination();
                                updateOverviewStats();
                            }
                            
                            // Close modals
                            hideConfirmModal();
                            hideViewAdModal();
                            alert('Ad deactivated successfully!');
                        } else {
                            alert('Error: ' + (data.message || 'Failed to deactivate ad'));
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while deactivating the ad.');
                    }
                }
            );
        }

        async function activateAd(adId, adTitle) {
            if (confirm(`Are you sure you want to activate "${adTitle}"?`)) {
                try {
                    const response = await fetch(`/admin/ads/${adId}/activate`, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok && data.success) {
                        // Update local data
                        const adIndex = ads.findIndex(a => a.id === adId);
                        if (adIndex !== -1) {
                            ads[adIndex].status = 'active';
                            ads[adIndex].approved_at = new Date().toISOString();
                            ads[adIndex].approved_by = 1; // Admin ID
                            filteredAds = [...ads];
                            renderAds();
                            updatePagination();
                            updateOverviewStats();
                        }
                        
                        alert('Ad activated successfully!');
                        // Close any open modals
                        hideConfirmModal();
                        hideViewAdModal();
                    } else {
                        alert('Error: ' + (data.message || 'Failed to activate ad'));
                    }
                } catch (error) {
                    console.error('Error:', error);
                    alert('An error occurred while activating the ad.');
                }
            }
        }

        // Bulk Approval Functions
        // Bulk Approval Functions
        function bulkApprove() {
            if (!window.selectedAds || window.selectedAds.length === 0) {
                alert('Please select ads first.');
                return;
            }
            
            showConfirmModal(
                'Bulk Approve',
                `Are you sure you want to approve ${window.selectedAds.length} selected ads?`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/bulk/approve`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ ad_ids: window.selectedAds })
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                            alert(data.message);
                            location.reload();
                        } else {
                            alert('Error: ' + (data.message || 'Failed to bulk approve ads'));
                        }
                        hideConfirmModal();
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while bulk approving ads.');
                    }
                }
            );
        }

        function bulkReject() {
            if (!window.selectedAds || window.selectedAds.length === 0) {
                alert('Please select ads first.');
                return;
            }
            
            const reason = prompt('Please provide a reason for rejecting these ads:', 'Inappropriate content');
            if (reason !== null && reason.trim() !== '') {
                showConfirmModal(
                    'Bulk Reject',
                    `Are you sure you want to reject ${window.selectedAds.length} selected ads?`,
                    async function() {
                        try {
                            const response = await fetch(`/admin/ads/bulk/reject`, {
                                method: 'POST',
                                headers: {
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ 
                                    ad_ids: window.selectedAds,
                                    rejection_reason: reason.trim()
                                })
                            });
                            
                            const data = await response.json();
                            
                            if (response.ok && data.success) {
                                alert(data.message);
                                location.reload();
                            } else {
                                alert('Error: ' + (data.message || 'Failed to bulk reject ads'));
                            }
                            hideConfirmModal();
                        } catch (error) {
                            console.error('Error:', error);
                            alert('An error occurred while bulk rejecting ads.');
                        }
                    }
                );
            }
        }

        function bulkDeactivate() {
            if (!window.selectedAds || window.selectedAds.length === 0) {
                alert('Please select ads first.');
                return;
            }
            
            showConfirmModal(
                'Bulk Deactivate',
                `Are you sure you want to deactivate ${window.selectedAds.length} selected ads?`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/bulk/deactivate`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ ad_ids: window.selectedAds })
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                            alert(data.message);
                            location.reload();
                        } else {
                            alert('Error: ' + (data.message || 'Failed to bulk deactivate ads'));
                        }
                        hideConfirmModal();
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while bulk deactivating ads.');
                    }
                }
            );
        }

        // Toggle Featured/Boosted
        function toggleFeatured(adId, adTitle) {
            const ad = ads.find(a => a.id === adId);
            const action = ad && ad.isFeatured ? 'remove featured status from' : 'make';
            const suffix = ad && ad.isFeatured ? '' : 'featured';
            
            showConfirmModal(
                'Toggle Featured',
                `Are you sure you want to ${action} "${adTitle}" ${suffix}?`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/${adId}/toggle-featured`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                            // Update local data
                            const adIndex = ads.findIndex(a => a.id === adId);
                            if (adIndex !== -1) {
                                ads[adIndex].isFeatured = !ads[adIndex].isFeatured;
                                filteredAds = [...ads];
                                renderAds();
                            }
                            hideConfirmModal();
                            alert(data.message || 'Featured status updated successfully!');
                        } else {
                            alert('Error: ' + data.message);
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while updating featured status.');
                    }
                }
            );
        }

        function toggleBoost(adId, adTitle) {
            const ad = ads.find(a => a.id === adId);
            const action = ad && ad.isBoosted ? 'unboost' : 'boost';
            
            showConfirmModal(
                'Toggle Boost',
                `Are you sure you want to ${action} "${adTitle}"?`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/${adId}/toggle-boost`, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                             // Update local data
                            const adIndex = ads.findIndex(a => a.id === adId);
                            if (adIndex !== -1) {
                                ads[adIndex].isBoosted = !ads[adIndex].isBoosted;
                                filteredAds = [...ads];
                                renderAds();
                            }
                            hideConfirmModal();
                            alert(data.message || 'Boost status updated successfully!');
                        } else {
                            alert('Error: ' + (data.message || 'Failed to toggle boost status'));
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while updating boost status.');
                    }
                }
            );
        }

        function deleteAd(adId, adTitle) {
            showConfirmModal(
                'Delete Ad',
                `Are you sure you want to delete "${adTitle}"? This action cannot be undone.`,
                async function() {
                    try {
                        const response = await fetch(`/admin/ads/${adId}`, {
                            method: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.success) {
                            // Update local data
                            ads = ads.filter(a => a.id !== adId);
                            filteredAds = [...ads];
                            renderAds();
                            updatePagination();
                            updateOverviewStats();
                            
                            hideConfirmModal();
                            alert('Ad deleted successfully!');
                        } else {
                            alert('Error: ' + (data.message || 'Failed to delete ad'));
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('An error occurred while deleting the ad.');
                    }
                }
            );
        }

        // Form Submissions
        document.getElementById('addAdForm').onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const newAd = {
                id: ads.length + 1,
                title: formData.get('title'),
                category: formData.get('category'),
                price: parseFloat(formData.get('price')),
                currency: formData.get('currency'),
                status: formData.get('status'),
                isFeatured: formData.get('is_featured') === '1',
                sellerName: formData.get('seller_name'),
                sellerEmail: formData.get('seller_email'),
                views: 0,
                created: new Date().toISOString().split('T')[0],
                images: ['https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?w=300&h=300&fit=crop'],
                location: { 
                    city: formData.get('city'), 
                    state: formData.get('state'), 
                    country: formData.get('country') 
                }
            };
            
            ads.unshift(newAd);
            filteredAds = [...ads];
            renderAds();
            updatePagination();
            renderAds();
            updatePagination();
            loadStatsFromAPI();
            hideAddAdModal();
            alert('Ad added successfully!');
        };

        document.getElementById('editAdForm').onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const adId = parseInt(formData.get('ad_id'));
            const adIndex = ads.findIndex(a => a.id === adId);
            
            if (adIndex !== -1) {
                ads[adIndex] = {
                    ...ads[adIndex],
                    title: formData.get('title'),
                    category: formData.get('category'),
                    description: formData.get('description') || '',
                    price: parseFloat(formData.get('price')),
                    currency: formData.get('currency'),
                    status: formData.get('status'),
                    isFeatured: formData.get('is_featured') === '1',
                    sellerName: formData.get('seller_name'),
                    sellerEmail: formData.get('seller_email'),
                    location: {
                        city: formData.get('city'),
                        state: formData.get('state'),
                        country: formData.get('country')
                    }
                };
                filteredAds = [...ads];
                renderAds();
                updatePagination();
                renderAds();
                updatePagination();
                loadStatsFromAPI();
                hideEditAdModal();
                alert('Ad updated successfully!');
            }
        };

        // Approval Settings Form Submission
        document.getElementById('approvalSettingsForm').onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            // In a real application, this would make an API call to save settings
            const autoApprove = formData.get('auto_approve_ads') === '1';
            const validityDays = parseInt(formData.get('default_ad_validity_days'));
            
            // Simulate API call
            setTimeout(() => {
                alert(`Settings saved successfully!\nAuto Approval: ${autoApprove ? 'Enabled' : 'Disabled'}\nDefault Validity: ${validityDays} days`);
                document.getElementById('approvalSettingsModal').style.display = 'none';
            }, 500);
        };

        // Ad Action Functions
        function viewAd(adId) {
            const ad = ads.find(a => a.id === adId);
            
            // Populate Ad Information Tab
            populateAdInfoTab(ad);
            
            // Populate Image Gallery Tab
            populateImageGalleryTab(ad);
            
            // Populate User Management Tab
            populateUserManagementTab(ad);
            
            // Populate Safety & Actions Tab
            populateSafetyTab(ad);
            
            // Set initial tab
            switchTab('ad-info');
            
            document.getElementById('viewAdModal').style.display = 'block';
        }

        function populateAdInfoTab(ad) {
            // Update status badge
            const statusBadge = document.getElementById('adStatusBadge');
            statusBadge.textContent = getStatusText(ad.status);
            statusBadge.className = 'status-badge status-' + ad.status;
            
            // Update main image
            document.getElementById('mainImage').src = ad.images[0] || '';
            
            // Update image thumbnails
            const thumbnailsContainer = document.getElementById('imageThumbnails');
            thumbnailsContainer.innerHTML = ad.images.slice(1, 4).map((img, index) => `
                <div style="width: 100%; height: 60px; border-radius: 6px; overflow: hidden; border: 1px solid var(--border-color); position: relative;">
                    <img src="${img}" style="width: 100%; height: 100%; object-fit: cover;" alt="Ad Image ${index + 2}">
                    <div style="position: absolute; top: 4px; right: 4px; background: rgba(0,0,0,0.5); color: white; padding: 2px 6px; border-radius: 8px; font-size: 0.625rem;">${index + 2}</div>
                </div>
            `).join('');

            // Update ad statistics
            document.getElementById('adViews').textContent = ad.views.toLocaleString();
            document.getElementById('adCreated').textContent = formatDate(ad.created);
            document.getElementById('adLocation').textContent = `${ad.location.city}, ${ad.location.state}`;
            document.getElementById('adCategory').textContent = getCategoryText(ad.category);

            // Update ad details
            document.getElementById('adTitle').textContent = ad.title;
            document.getElementById('adCategoryFull').textContent = getCategoryText(ad.category);
            document.getElementById('adPrice').textContent = formatCurrency(ad.price, ad.currency);
            document.getElementById('adStatus').textContent = getStatusText(ad.status);
            document.getElementById('adFeatured').textContent = ad.isFeatured ? 'Yes' : 'No';
            document.getElementById('adCurrency').textContent = ad.currency;

            // Update location details
            document.getElementById('adCity').textContent = ad.location.city;
            document.getElementById('adState').textContent = ad.location.state;
            document.getElementById('adCountry').textContent = ad.location.country;
            document.getElementById('adFullAddress').textContent = `${ad.location.city}, ${ad.location.state}, ${ad.location.country}`;

            // Update description
            document.getElementById('adDescription').textContent = ad.description || 'No description provided';

            // Update seller information
            document.getElementById('adSellerName').textContent = ad.sellerName;
            document.getElementById('adSellerEmail').textContent = ad.sellerEmail;
            
            // Mock user statistics (would come from API)
            document.getElementById('adAccountAge').textContent = '45 days';
            document.getElementById('adTrustScore').textContent = '85/100';
        }

        function populateImageGalleryTab(ad) {
            const thumbnailsContainer = document.getElementById('galleryThumbnails');
            thumbnailsContainer.innerHTML = ad.images.map((img, index) => `
                <div style="border: 2px solid transparent; border-radius: 8px; overflow: hidden; cursor: pointer;" onclick="selectGalleryImage(${index})">
                    <img src="${img}" style="width: 100%; height: 80px; object-fit: cover;" alt="Gallery Image ${index + 1}">
                    <div style="padding: 4px; font-size: 0.75rem; color: var(--text-secondary); background: #f8fafc; border-top: 1px solid var(--border-color);">
                        Image ${index + 1}
                    </div>
                </div>
            `).join('');

            // Set initial gallery image
            document.getElementById('galleryMainImage').src = ad.images[0] || '';
            document.getElementById('imageCounter').textContent = `1 / ${ad.images.length}`;
            document.getElementById('imageCaption').textContent = `Image 1 of ${ad.images.length}`;
        }

        function populateUserManagementTab(ad) {
            // Get user data from ads (in real app, this would be from API)
            const user = {
                name: ad.sellerName,
                email: ad.sellerEmail,
                totalAds: 12,
                activeAds: 8,
                featuredAds: 3,
                accountAge: 45,
                trustScore: 85,
                verified: true,
                safetyReports: 1,
                appealsPending: 0,
                isBanned: false,
                isSuspended: false,
                lastLogin: '2024-01-10',
                memberSince: '2023-11-20',
                riskLevel: 'Low',
                suspiciousActivity: 'No',
                lastReport: '2024-01-05',
                warningCount: 0
            };

            // Update user profile
            document.getElementById('userProfileName').textContent = user.name;
            document.getElementById('userProfileEmail').textContent = user.email;

            // Update user statistics
            document.getElementById('userTotalAds').textContent = user.totalAds;
            document.getElementById('userActiveAds').textContent = user.activeAds;
            document.getElementById('userFeaturedAds').textContent = user.featuredAds;
            document.getElementById('userAccountAge').textContent = `${user.accountAge} days`;

            // Update trust & safety
            document.getElementById('userTrustScore').textContent = `${user.trustScore}/100`;
            document.getElementById('userVerified').textContent = user.verified ? 'Yes' : 'No';
            document.getElementById('userVerified').style.color = user.verified ? '#10b981' : '#ef4444';
            document.getElementById('userSafetyReports').textContent = user.safetyReports;
            document.getElementById('userAppealsPending').textContent = user.appealsPending;

            // Update account status
            document.getElementById('userIsBanned').textContent = user.isBanned ? 'Yes' : 'No';
            document.getElementById('userIsBanned').style.color = user.isBanned ? '#ef4444' : '#10b981';
            document.getElementById('userIsSuspended').textContent = user.isSuspended ? 'Yes' : 'No';
            document.getElementById('userIsSuspended').style.color = user.isSuspended ? '#f59e0b' : '#10b981';
            document.getElementById('userLastLogin').textContent = user.lastLogin;
            document.getElementById('userMemberSince').textContent = user.memberSince;

            // Update risk assessment
            document.getElementById('userRiskLevel').textContent = user.riskLevel;
            document.getElementById('userRiskLevel').style.color = user.riskLevel === 'Low' ? '#10b981' : '#ef4444';
            document.getElementById('userSuspiciousActivity').textContent = user.suspiciousActivity;
            document.getElementById('userSuspiciousActivity').style.color = user.suspiciousActivity === 'No' ? '#10b981' : '#f59e0b';
            document.getElementById('userLastReport').textContent = user.lastReport;
            document.getElementById('userWarningCount').textContent = user.warningCount;

            // Update user's other ads (filter ads by seller)
            const otherAdsContainer = document.getElementById('userOtherAds');
            const userOtherAds = ads.filter(a => a.sellerEmail === ad.sellerEmail && a.id !== ad.id);
            
            if (userOtherAds.length > 0) {
                otherAdsContainer.innerHTML = userOtherAds.slice(0, 5).map(otherAd => `
                    <div style="background: white; padding: 8px; border-radius: 6px; border: 1px solid var(--border-color); font-size: 0.875rem; cursor: pointer; transition: background-color 0.2s;" 
                         onclick="viewAd(${otherAd.id})" 
                         onmouseover="this.style.backgroundColor='#f8fafc'" 
                         onmouseout="this.style.backgroundColor='white'">
                        <div style="font-weight: 600; color: var(--text-primary);">${otherAd.title}</div>
                        <div style="color: var(--text-secondary);">
                            ${getCategoryText(otherAd.category)} • ${formatCurrency(otherAd.price, otherAd.currency)}
                        </div>
                        <div style="font-size: 0.75rem; color: var(--text-secondary); margin-top: 4px;">
                            Status: ${getStatusText(otherAd.status)} • Views: ${otherAd.views}
                        </div>
                    </div>
                `).join('');
            } else {
                otherAdsContainer.innerHTML = `
                    <div style="background: white; padding: 12px; border-radius: 6px; border: 1px solid var(--border-color); font-size: 0.875rem; color: var(--text-secondary); text-align: center;">
                        No other ads found for this user
                    </div>
                `;
            }
        }

        function populateSafetyTab(ad) {
            // Mock safety reports (would come from API)
            const safetyReports = [
                { id: 1, type: 'Inappropriate Content', reason: 'Spam listing', reporter: 'user123', date: '2024-01-10', status: 'Under Review' },
                { id: 2, type: 'Misleading Price', reason: 'Price too low', reporter: 'user456', date: '2024-01-08', status: 'Resolved' }
            ];

            const reportsContainer = document.getElementById('safetyReportsList');
            reportsContainer.innerHTML = safetyReports.map(report => `
                <div style="background: white; padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                        <div style="font-weight: 600; color: var(--text-primary);">${report.type}</div>
                        <span style="background: #fef3c7; color: #f59e0b; padding: 2px 6px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">${report.status}</span>
                    </div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">Reason: ${report.reason}</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Reported by: ${report.reporter} • ${report.date}</div>
                </div>
            `).join('');
        }

        // Tab switching functionality
        function switchTab(tabName) {
            // Update tab buttons
            document.querySelectorAll('.tab-button').forEach(btn => {
                btn.classList.remove('active');
                btn.style.color = 'var(--text-secondary)';
                btn.style.borderBottom = '2px solid transparent';
            });
            
            document.getElementById('tab-' + tabName).classList.add('active');
            document.getElementById('tab-' + tabName).style.color = 'var(--text-primary)';
            document.getElementById('tab-' + tabName).style.borderBottom = '2px solid var(--primary-color)';

            // Update tab content
            document.querySelectorAll('.tab-content').forEach(content => {
                content.style.display = 'none';
            });
            
            document.getElementById('tab-content-' + tabName).style.display = 'block';
        }

        // Image gallery functions
        let currentImageIndex = 0;
        let currentAdImages = [];

        function selectGalleryImage(index) {
            currentImageIndex = index;
            updateGalleryDisplay();
        }

        function prevImage() {
            currentImageIndex = (currentImageIndex - 1 + currentAdImages.length) % currentAdImages.length;
            updateGalleryDisplay();
        }

        function nextImage() {
            currentImageIndex = (currentImageIndex + 1) % currentAdImages.length;
            updateGalleryDisplay();
        }

        function updateGalleryDisplay() {
            if (currentAdImages.length > 0) {
                document.getElementById('galleryMainImage').src = currentAdImages[currentImageIndex];
                document.getElementById('imageCounter').textContent = `${currentImageIndex + 1} / ${currentAdImages.length}`;
                document.getElementById('imageCaption').textContent = `Image ${currentImageIndex + 1} of ${currentAdImages.length}`;
            }
        }

        // User management functions
        function showUserDetails() {
            switchTab('user-details');
        }

        function showSafetyReports() {
            switchTab('safety');
        }

        function banUser() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                if (confirm(`Are you sure you want to ban user "${ad.sellerName}"? This will suspend all their ads.`)) {
                    // Update user status
                    const userIndex = ads.findIndex(a => a.sellerEmail === ad.sellerEmail);
                    if (userIndex !== -1) {
                        // Ban all user's ads
                        ads.forEach(a => {
                            if (a.sellerEmail === ad.sellerEmail) {
                                a.status = 'pending'; // Deactivate all ads
                            }
                        });
                        
                        filteredAds = [...ads];
                        renderAds();
                        updatePagination();
                        updateOverviewStats();
                        
                        // Update user management tab to reflect changes
                        populateUserManagementTab(ad);
                        
                        alert(`User "${ad.sellerName}" has been banned. All their ads have been deactivated.`);
                    }
                }
            }
        }

        function suspendUser() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                if (confirm(`Are you sure you want to suspend user "${ad.sellerName}"? This will temporarily disable their account.`)) {
                    // Mark user as suspended (in real app, this would be in user table)
                    alert(`User "${ad.sellerName}" has been suspended. They will be notified via email.`);
                    
                    // Update user management tab to show suspended status
                    const userOtherAds = ads.filter(a => a.sellerEmail === ad.sellerEmail);
                    userOtherAds.forEach(a => {
                        if (a.status === 'active') {
                            a.status = 'pending'; // Temporarily deactivate
                        }
                    });
                    
                    filteredAds = [...ads];
                    renderAds();
                    updatePagination();
                    updateOverviewStats();
                    populateUserManagementTab(ad);
                }
            }
        }

        function verifyUser() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                // Update user verification status
                alert(`User "${ad.sellerName}" has been verified. They will receive a verification badge.`);
                
                // Update user management tab to show verified status
                populateUserManagementTab(ad);
            }
        }

        function contactUser() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                // Create a contact modal or redirect to messaging system
                const contactModal = document.createElement('div');
                contactModal.className = 'modal';
                contactModal.style.display = 'block';
                contactModal.innerHTML = `
                    <div class="modal-content" style="max-width: 600px;">
                        <div class="modal-header">
                            <h3 style="margin: 0;">Contact User</h3>
                            <button onclick="this.closest('.modal').style.display='none'" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
                        </div>
                        <div style="padding: 20px;">
                            <div style="background: #f8fafc; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
                                <div style="font-weight: 600; color: var(--text-primary);">To:</div>
                                <div style="color: var(--text-secondary);">${ad.sellerName} <${ad.sellerEmail}></div>
                            </div>
                            <form id="contactUserForm" style="display: flex; flex-direction: column; gap: 12px;">
                                <div>
                                    <label style="display: block; margin-bottom: 4px; font-weight: 600;">Subject</label>
                                    <input type="text" id="contactSubject" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Enter subject">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 4px; font-weight: 600;">Message</label>
                                    <textarea id="contactMessage" rows="6" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Enter your message to the user"></textarea>
                                </div>
                                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                                    <button type="button" onclick="this.closest('.modal').style.display='none'" style="padding: 8px 16px; border: 1px solid var(--border-color); border-radius: 6px; background: white; cursor: pointer;">Cancel</button>
                                    <button type="submit" style="padding: 8px 16px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer;">Send Message</button>
                                </div>
                            </form>
                        </div>
                    </div>
                `;
                
                document.body.appendChild(contactModal);
                
                // Handle form submission
                document.getElementById('contactUserForm').onsubmit = function(e) {
                    e.preventDefault();
                    const subject = document.getElementById('contactSubject').value;
                    const message = document.getElementById('contactMessage').value;
                    
                    if (subject.trim() && message.trim()) {
                        alert(`Message sent to ${ad.sellerName}!\n\nSubject: ${subject}\n\nMessage: ${message.substring(0, 50)}...`);
                        contactModal.style.display = 'none';
                    } else {
                        alert('Please fill in both subject and message.');
                    }
                };
            }
        }

        function resetUserPassword() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                if (confirm(`Are you sure you want to reset the password for "${ad.sellerName}"? They will receive an email with reset instructions.`)) {
                    alert(`Password reset request sent to ${ad.sellerEmail}. The user will receive instructions to reset their password.`);
                }
            }
        }

        function changeUserEmail() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                const newEmail = prompt(`Enter new email address for ${ad.sellerName}:`, ad.sellerEmail);
                if (newEmail && newEmail !== ad.sellerEmail) {
                    if (confirm(`Change email from ${ad.sellerEmail} to ${newEmail}?`)) {
                        // Update all ads for this user
                        ads.forEach(a => {
                            if (a.sellerEmail === ad.sellerEmail) {
                                a.sellerEmail = newEmail;
                            }
                        });
                        
                        filteredAds = [...ads];
                        renderAds();
                        updatePagination();
                        updateOverviewStats();
                        populateUserManagementTab({ ...ad, sellerEmail: newEmail });
                        
                        alert(`Email updated successfully from ${ad.sellerEmail} to ${newEmail}`);
                    }
                }
            }
        }

        function viewUserActivity() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                // Create activity modal
                const activityModal = document.createElement('div');
                activityModal.className = 'modal';
                activityModal.style.display = 'block';
                activityModal.innerHTML = `
                    <div class="modal-content" style="max-width: 800px; max-height: 70vh; overflow-y: auto;">
                        <div class="modal-header">
                            <h3 style="margin: 0;">User Activity: ${ad.sellerName}</h3>
                            <button onclick="this.closest('.modal').style.display='none'" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
                        </div>
                        <div style="padding: 20px;">
                            <div style="background: #f8fafc; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size: 0.875rem;">
                                    <div><strong>Total Ads:</strong> ${ads.filter(a => a.sellerEmail === ad.sellerEmail).length}</div>
                                    <div><strong>Active Ads:</strong> ${ads.filter(a => a.sellerEmail === ad.sellerEmail && a.status === 'active').length}</div>
                                    <div><strong>Last Login:</strong> 2 hours ago</div>
                                    <div><strong>Member Since:</strong> ${ad.created}</div>
                                    <div><strong>Total Views:</strong> ${ads.filter(a => a.sellerEmail === ad.sellerEmail).reduce((sum, a) => sum + a.views, 0)}</div>
                                    <div><strong>Avg. Response Time:</strong> 2 hours</div>
                                </div>
                            </div>
                            
                            <div style="background: white; border-radius: 8px; border: 1px solid var(--border-color);">
                                <div style="padding: 12px; border-bottom: 1px solid var(--border-color); font-weight: 600; color: var(--text-primary);">
                                    Recent Activity
                                </div>
                                <div style="padding: 12px;">
                                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 12px; font-size: 0.875rem; margin-bottom: 8px;">
                                        <div style="color: var(--text-secondary);">2024-01-15 14:30</div>
                                        <div>Posted new ad: "${ad.title}"</div>
                                    </div>
                                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 12px; font-size: 0.875rem; margin-bottom: 8px;">
                                        <div style="color: var(--text-secondary);">2024-01-14 10:15</div>
                                        <div>Responded to 3 messages</div>
                                    </div>
                                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 12px; font-size: 0.875rem; margin-bottom: 8px;">
                                        <div style="color: var(--text-secondary);">2024-01-13 16:45</div>
                                        <div>Updated ad: "Vintage Camera"</div>
                                    </div>
                                    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 12px; font-size: 0.875rem;">
                                        <div style="color: var(--text-secondary);">2024-01-12 09:20</div>
                                        <div>Received 5 new views on "Designer Watch"</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                document.body.appendChild(activityModal);
            }
        }

        function exportUserReport() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                // Generate user report
                const userAds = ads.filter(a => a.sellerEmail === ad.sellerEmail);
                const totalViews = userAds.reduce((sum, a) => sum + a.views, 0);
                const activeAds = userAds.filter(a => a.status === 'active').length;
                
                const report = `
User Report: ${ad.sellerName}
Email: ${ad.sellerEmail}
Member Since: ${ad.created}
Total Ads: ${userAds.length}
Active Ads: ${activeAds}
Total Views: ${totalViews}
Avg. Views per Ad: ${userAds.length > 0 ? Math.round(totalViews / userAds.length) : 0}

Recent Ads:
${userAds.slice(0, 5).map(a => `- ${a.title} (${a.status}) - ${a.views} views`).join('\n')}

Generated: ${new Date().toLocaleString()}
                `;
                
                // Create download link
                const blob = new Blob([report], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `user_report_${ad.sellerName.replace(/\s+/g, '_')}_${Date.now()}.txt`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                alert('User report exported successfully!');
            }
        }

        function viewAllUserAds() {
            const ad = getCurrentAdFromModal();
            if (ad) {
                // Filter table to show only this user's ads
                const userAds = ads.filter(a => a.sellerEmail === ad.sellerEmail);
                
                if (userAds.length > 0) {
                    // Store original filteredAds for restore
                    window.originalFilteredAds = [...filteredAds];
                    
                    // Update the table with user's ads
                    filteredAds = userAds;
                    currentPage = 1;
                    renderAds();
                    updatePagination();
                    
                    // Update overview stats to show user's ads
                    const total = filteredAds.length;
                    const active = filteredAds.filter(a => a.status === 'active').length;
                    
                    document.getElementById('totalAdsCount').textContent = total.toLocaleString();
                    document.getElementById('activeAdsCount').textContent = active.toLocaleString();
                    
                    alert(`Showing ${total} ads from ${ad.sellerName}. Use the search or filters to return to all ads.`);
                } else {
                    alert('No other ads found for this user.');
                }
            }
        }

        // Safety & Actions functions
        function approveAdFromModal() {
            const adId = getCurrentAdId();
            approveAd(adId, getCurrentAdTitle());
        }

        function rejectAdFromModal() {
            const adId = getCurrentAdId();
            rejectAd(adId, getCurrentAdTitle());
        }

        function deactivateAdFromModal() {
            const adId = getCurrentAdId();
            deactivateAd(adId, getCurrentAdTitle());
        }

        function reactivateAdFromModal() {
            const adId = getCurrentAdId();
            reactivateAd(adId, getCurrentAdTitle());
        }

        function makeFeaturedFromModal() {
            const adId = getCurrentAdId();
            addFeatured(adId, getCurrentAdTitle());
        }

        function removeFeaturedFromModal() {
            const adId = getCurrentAdId();
            removeFeatured(adId, getCurrentAdTitle());
        }

        function boostAdFromModal() {
            alert('Boost ad functionality would be implemented here');
        }

        function unboostAdFromModal() {
            alert('Unboost ad functionality would be implemented here');
        }

        function deleteAdFromModal() {
            const adId = getCurrentAdId();
            deleteAd(adId, getCurrentAdTitle());
        }

        function archiveAdFromModal() {
            alert('Archive ad functionality would be implemented here');
        }

        function flagAdFromModal() {
            alert('Flag ad functionality would be implemented here');
        }

        function reportAdFromModal() {
            alert('Report ad functionality would be implemented here');
        }

        function viewAllSafetyReports() {
            alert('View all safety reports functionality would be implemented here');
        }

        // Helper functions
        function getCurrentAdId() {
            // Get the current ad ID from the modal
            const adId = document.getElementById('editAdId')?.value;
            return adId ? parseInt(adId) : 1; // Fallback to 1 if not found
        }

        function getCurrentAdTitle() {
            // Get the current ad title from the modal
            const adTitle = document.getElementById('editAdTitle')?.value;
            return adTitle || 'Sample Ad'; // Fallback to 'Sample Ad' if not found
        }

        function getCurrentAdFromModal() {
            // Get the current ad data from the modal
            const adId = getCurrentAdId();
            return ads.find(ad => ad.id === adId);
        }
        
        function hideViewAdModal() {
            document.getElementById('viewAdModal').style.display = 'none';
        }



        function editAd(adId, title, category, description, price, currency, status, isFeatured, sellerName, sellerEmail, country, state, city) {
            showEditAdModal(adId, title, category, description, price, currency, status, isFeatured, sellerName, sellerEmail, country, state, city);
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }

        // Overview Filtering and Charts
        function updateOverviewFiltering() {
            const overviewLevel = document.getElementById('overviewLevel').value;
            const overviewStatus = document.getElementById('overviewStatus').value;
            const overviewType = document.getElementById('overviewType').value;
            const overviewCategory = document.getElementById('overviewCategory').value;

            // Apply filters to overview data
            let overviewData = [...filteredAds];

            if (overviewStatus !== 'all') {
                overviewData = overviewData.filter(ad => ad.status === overviewStatus);
            }

            if (overviewType !== 'all') {
                const isFeatured = overviewType === 'featured';
                overviewData = overviewData.filter(ad => ad.isFeatured === isFeatured);
            }

            if (overviewCategory !== 'all') {
                overviewData = overviewData.filter(ad => ad.category === overviewCategory);
            }

            // Update charts based on filtered data
            renderCharts(overviewData, overviewLevel);
            updateTopLocationsTable(overviewData, overviewLevel);
        }

        function renderCharts(data, level) {
            // Location Distribution Chart
            renderLocationChart(data, level);
            
            // Status Distribution Chart
            renderStatusChart(data);
            
            // Category Distribution Chart
            renderCategoryChart(data);
            
            // Featured vs Regular Chart
            renderFeaturedChart(data);
        }

        function renderLocationChart(data, level) {
            const chartContainer = document.getElementById('locationChart');
            const legendContainer = document.getElementById('locationChartLegend');
            
            // Group data by location level
            let locationData = {};
            if (level === 'country') {
                locationData = groupBy(data, 'location.country');
            } else if (level === 'state') {
                locationData = groupBy(data, 'location.state');
            } else if (level === 'city') {
                locationData = groupBy(data, 'location.city');
            } else {
                // All locations - show countries
                locationData = groupBy(data, 'location.country');
            }

            // Create simple bar chart using CSS
            const total = data.length;
            let chartHTML = '';
            let legendHTML = '';
            const colors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#f472b6', '#14b8a6', '#f97316'];
            let colorIndex = 0;

            Object.entries(locationData).forEach(([location, ads], index) => {
                const count = ads.length;
                const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
                const color = colors[colorIndex % colors.length];
                colorIndex++;

                chartHTML += `
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                            <span style="font-weight: 600; color: var(--text-primary);">${location}</span>
                            <span style="color: var(--text-secondary); font-size: 0.875rem;">${count} ads (${percentage}%)</span>
                        </div>
                        <div style="width: 100%; height: 20px; background: #e5e7eb; border-radius: 10px; overflow: hidden;">
                            <div style="width: ${percentage}%; height: 100%; background: ${color}; border-radius: 10px;"></div>
                        </div>
                    </div>
                `;

                legendHTML += `
                    <div style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem;">
                        <div style="width: 12px; height: 12px; background: ${color}; border-radius: 50%;"></div>
                        <span>${location}</span>
                    </div>
                `;
            });

            chartContainer.innerHTML = chartHTML;
            legendContainer.innerHTML = legendHTML;
        }

        function renderStatusChart(data) {
            const chartContainer = document.getElementById('statusChart');
            const legendContainer = document.getElementById('statusChartLegend');
            
            const statusData = groupBy(data, 'status');
            const total = data.length;
            const colors = { 'active': '#10b981', 'pending': '#f59e0b', 'sold': '#ef4444', 'expired': '#64748b' };

            let chartHTML = '';
            let legendHTML = '';

            Object.entries(statusData).forEach(([status, ads]) => {
                const count = ads.length;
                const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
                const color = colors[status] || '#64748b';

                chartHTML += `
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                            <span style="font-weight: 600; color: var(--text-primary);">${getStatusText(status)}</span>
                            <span style="color: var(--text-secondary); font-size: 0.875rem;">${count} ads (${percentage}%)</span>
                        </div>
                        <div style="width: 100%; height: 12px; background: #e5e7eb; border-radius: 6px; overflow: hidden;">
                            <div style="width: ${percentage}%; height: 100%; background: ${color}; border-radius: 6px;"></div>
                        </div>
                    </div>
                `;

                legendHTML += `
                    <div style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem;">
                        <div style="width: 12px; height: 12px; background: ${color}; border-radius: 50%;"></div>
                        <span>${getStatusText(status)}</span>
                    </div>
                `;
            });

            chartContainer.innerHTML = chartHTML;
            legendContainer.innerHTML = legendHTML;
        }

        function renderCategoryChart(data) {
            const chartContainer = document.getElementById('categoryChart');
            const legendContainer = document.getElementById('categoryChartLegend');
            
            const categoryData = groupBy(data, 'category');
            const total = data.length;
            const colors = { 'electronics': '#3b82f6', 'vehicles': '#10b981', 'real-estate': '#f59e0b', 'fashion': '#7c3aed', 'home-garden': '#ef4444' };

            let chartHTML = '';
            let legendHTML = '';

            Object.entries(categoryData).forEach(([category, ads]) => {
                const count = ads.length;
                const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
                const color = colors[category] || '#64748b';

                chartHTML += `
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                            <span style="font-weight: 600; color: var(--text-primary);">${getCategoryText(category)}</span>
                            <span style="color: var(--text-secondary); font-size: 0.875rem;">${count} ads (${percentage}%)</span>
                        </div>
                        <div style="width: 100%; height: 12px; background: #e5e7eb; border-radius: 6px; overflow: hidden;">
                            <div style="width: ${percentage}%; height: 100%; background: ${color}; border-radius: 6px;"></div>
                        </div>
                    </div>
                `;

                legendHTML += `
                    <div style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem;">
                        <div style="width: 12px; height: 12px; background: ${color}; border-radius: 50%;"></div>
                        <span>${getCategoryText(category)}</span>
                    </div>
                `;
            });

            chartContainer.innerHTML = chartHTML;
            legendContainer.innerHTML = legendHTML;
        }

        function renderFeaturedChart(data) {
            const chartContainer = document.getElementById('featuredChart');
            const legendContainer = document.getElementById('featuredChartLegend');
            
            const featuredCount = data.filter(ad => ad.isFeatured).length;
            const regularCount = data.length - featuredCount;
            const total = data.length;

            const featuredPercentage = total > 0 ? ((featuredCount / total) * 100).toFixed(1) : 0;
            const regularPercentage = total > 0 ? ((regularCount / total) * 100).toFixed(1) : 0;

            let chartHTML = '';
            let legendHTML = '';

            // Featured
            chartHTML += `
                <div style="margin-bottom: 12px;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                        <span style="font-weight: 600; color: var(--text-primary);">Featured Ads</span>
                        <span style="color: var(--text-secondary); font-size: 0.875rem;">${featuredCount} ads (${featuredPercentage}%)</span>
                    </div>
                    <div style="width: 100%; height: 12px; background: #e5e7eb; border-radius: 6px; overflow: hidden;">
                        <div style="width: ${featuredPercentage}%; height: 100%; background: #7c3aed; border-radius: 6px;"></div>
                    </div>
                </div>
            `;

            // Regular
            chartHTML += `
                <div style="margin-bottom: 12px;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
                        <span style="font-weight: 600; color: var(--text-primary);">Regular Ads</span>
                        <span style="color: var(--text-secondary); font-size: 0.875rem;">${regularCount} ads (${regularPercentage}%)</span>
                    </div>
                    <div style="width: 100%; height: 12px; background: #e5e7eb; border-radius: 6px; overflow: hidden;">
                        <div style="width: ${regularPercentage}%; height: 100%; background: #64748b; border-radius: 6px;"></div>
                    </div>
                </div>
            `;

            legendHTML = `
                <div style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem;">
                    <div style="width: 12px; height: 12px; background: #7c3aed; border-radius: 50%;"></div>
                    <span>Featured Ads</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem;">
                    <div style="width: 12px; height: 12px; background: #64748b; border-radius: 50%;"></div>
                    <span>Regular Ads</span>
                </div>
            `;

            chartContainer.innerHTML = chartHTML;
            legendContainer.innerHTML = legendHTML;
        }

        function updateTopLocationsTable(data, level) {
            const tableBody = document.getElementById('topLocationsTable');
            
            // Group and sort by count
            let locationData = {};
            if (level === 'country') {
                locationData = groupBy(data, 'location.country');
            } else if (level === 'state') {
                locationData = groupBy(data, 'location.state');
            } else if (level === 'city') {
                locationData = groupBy(data, 'location.city');
            } else {
                locationData = groupBy(data, 'location.country');
            }

            // Sort by count descending
            const sortedLocations = Object.entries(locationData)
                .map(([location, ads]) => ({
                    name: location,
                    type: level === 'country' ? 'Country' : level === 'state' ? 'State/Province' : 'City',
                    total: ads.length,
                    active: ads.filter(ad => ad.status === 'active').length,
                    featured: ads.filter(ad => ad.isFeatured).length,
                    views: ads.reduce((sum, ad) => sum + ad.views, 0)
                }))
                .sort((a, b) => b.total - a.total)
                .slice(0, 10); // Top 10

            let tableHTML = '';
            sortedLocations.forEach(location => {
                tableHTML += `
                    <tr>
                        <td style="font-weight: 600; color: var(--text-primary);">${location.name}</td>
                        <td><span style="background: #f1f5f9; color: #64748b; padding: 2px 6px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;">${location.type}</span></td>
                        <td style="font-weight: 600; color: var(--primary-color);">${location.total}</td>
                        <td style="font-weight: 600; color: #10b981;">${location.active}</td>
                        <td style="font-weight: 600; color: #7c3aed;">${location.featured}</td>
                        <td style="font-weight: 600; color: var(--text-primary);">${location.views.toLocaleString()}</td>
                    </tr>
                `;
            });

            tableBody.innerHTML = tableHTML;
        }

        function groupBy(array, key) {
            return array.reduce((groups, item) => {
                const keys = key.split('.');
                let value = item;
                for (const k of keys) {
                    value = value[k];
                }
                if (!groups[value]) {
                    groups[value] = [];
                }
                groups[value].push(item);
                return groups;
            }, {});
        }

        // Event Listeners
        /*
        document.getElementById('searchInput').addEventListener('input', searchAds);
        document.getElementById('categoryFilter').addEventListener('change', searchAds);
        document.getElementById('statusFilter').addEventListener('change', searchAds);
        document.getElementById('countryFilter').addEventListener('change', searchAds);
        document.getElementById('pageSize').addEventListener('change', changePageSize);
        */
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.ad-checkbox');
            checkboxes.forEach(cb => cb.checked = this.checked);
        });

        // Overview Controls Event Listeners
        document.getElementById('overviewLevel').addEventListener('change', updateOverviewFiltering);
        document.getElementById('overviewStatus').addEventListener('change', updateOverviewFiltering);
        document.getElementById('overviewType').addEventListener('change', updateOverviewFiltering);
        document.getElementById('overviewCategory').addEventListener('change', updateOverviewFiltering);

        // Initialize
        // document.addEventListener('DOMContentLoaded', initializeAds);

        // ========== API INTEGRATION - Load Stats from Backend ==========
        
        async function loadStatsFromAPI() {
            try {
                const params = new URLSearchParams();
                const overviewStatus = document.getElementById('overviewStatus')?.value;
                const overviewType = document.getElementById('overviewType')?.value;
                const overviewCategory = document.getElementById('overviewCategory')?.value;

                if (overviewStatus && overviewStatus !== 'all') params.append('status', overviewStatus);
                if (overviewType && overviewType !== 'all') params.append('type', overviewType);
                if (overviewCategory && overviewCategory !== 'all') params.append('category', overviewCategory);

                const response = await fetch(`/api/admin/ads/stats?${params.toString()}`, {
                    headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '' }
                });
                
                if (!response.ok) return null;
                const data = await response.json();

                document.getElementById('totalAdsCount').textContent = data.total.toLocaleString();
                document.getElementById('activeAdsCount').textContent = data.active.toLocaleString();
                document.getElementById('featuredAdsCount').textContent = data.featured.toLocaleString();
                document.getElementById('countryAdsCount').textContent = data.countries.toLocaleString();
                document.getElementById('stateAdsCount').textContent = data.states.toLocaleString();
                document.getElementById('pendingAdsCount').textContent = data.pending.toLocaleString();

                console.log('✅ Stats loaded from API');
                return data;
            } catch (error) {
                console.error('❌ Error loading stats:', error);
                return null;
            }
        }

        async function loadChartsFromAPI() {
            try {
                const params = new URLSearchParams();
                const overviewLevel = document.getElementById('overviewLevel')?.value || 'country';
                const overviewStatus = document.getElementById('overviewStatus')?.value;
                const overviewType = document.getElementById('overviewType')?.value;
                const overviewCategory = document.getElementById(' overviewCategory')?.value;

                params.append('location_level', overviewLevel === 'all' ? 'country' : overviewLevel);
                if (overviewStatus && overviewStatus !== 'all') params.append('status', overviewStatus);
                if (overviewType && overviewType !== 'all') params.append('type', overviewType);
                if (overviewCategory && overviewCategory !== 'all') params.append('category', overviewCategory);

                const response = await fetch(`/api/admin/ads/charts?${params.toString()}`, {
                    headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '' }
                });
                
                if (!response.ok) return null;
                const data = await response.json();

                renderStatusChartAPI(data.status_distribution);
                renderCategoryChartAPI(data.category_distribution);
                renderFeaturedChartAPI(data.featured_distribution);
                renderLocationChartAPI(data.location_distribution);
                renderTopLocationsTableAPI(data.top_locations);

                console.log('✅ Charts loaded from API');
                return data;
            } catch (error) {
                console.error('❌ Error loading charts:', error);
                return null;
            }
        }

        function renderStatusChartAPI(statusData) {
            const container = document.getElementById('statusChart');
            if (!statusData || statusData.length === 0) {
                container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;">No data</div>';
                return;
            }
            const total = statusData.reduce((sum, item) => sum + item.count, 0);
            const colors = { 'Active': '#10b981', 'Pending': '#f59e0b', 'Sold': '#3b82f6', 'Expired': '#ef4444', 'Rejected': '#94a3b8' };
            let html = '<div style="display:flex;flex-direction:column;gap:8px;padding:10px;">';
            statusData.forEach(item => {
                const pct = ((item.count / total) * 100).toFixed(1);
                const color = colors[item.status] || '#94a3b8';
                html += `<div style="display:flex;align-items:center;gap:8px;">
                    <div style="width:12px;height:12px;background:${color};border-radius:3px;"></div>
                    <div style="flex:1;font-size:0.875rem;color:#64748b;">${item.status}</div>
                    <div style="font-weight:600;color:${color};">${item.count.toLocaleString()}</div>
                    <div style="font-size:0.875rem;color:#94a3b8;width:45px;text-align:right;">${pct}%</div>
                </div>`;
            });
            container.innerHTML = html + '</div>';
        }

        function renderCategoryChartAPI(categoryData) {
            const container = document.getElementById('categoryChart');
            if (!categoryData || categoryData.length === 0) {
                container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;">No data</div>';
                return;
            }
            const total = categoryData.reduce((sum, item) => sum + item.count, 0);
            const colors = ['#8b5cf6', '#ec4899', '#f59e0b', '#10b981', '#3b82f6', '#ef4444'];
            let html = '<div style="display:flex;flex-direction:column;gap:8px;padding:10px;">';
            categoryData.slice(0, 6).forEach((item, i) => {
                const pct = ((item.count / total) * 100).toFixed(1);
                const color = colors[i % colors.length];
                html += `<div style="display:flex;align-items:center;gap:8px;">
                    <div style="width:12px;height:12px;background:${color};border-radius:3px;"></div>
                    <div style="flex:1;font-size:0.875rem;color:#64748b;">Category ${item.category_id}</div>
                    <div style="font-weight:600;color:${color};">${item.count.toLocaleString()}</div>
                    <div style="font-size:0.875rem;color:#94a3b8;width:45px;text-align:right;">${pct}%</div>
                </div>`;
            });
            container.innerHTML = html + '</div>';
        }

        function renderFeaturedChartAPI(featuredData) {
            const container = document.getElementById('featuredChart');
            if (!featuredData || featuredData.length === 0) {
                container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;">No data</div>';
                return;
            }
            const featured = featuredData.find(item => item.is_featured === 1 || item.is_featured === true);
            const regular = featuredData.find(item => item.is_featured === 0 || item.is_featured === false);
            const fCount = featured ? featured.count : 0;
            const rCount = regular ? regular.count : 0;
            const total = fCount + rCount;
            if (total === 0) {
                container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;">No data</div>';
                return;
            }
            const fPct = ((fCount / total) * 100).toFixed(1);
            const rPct = ((rCount / total) * 100).toFixed(1);
            container.innerHTML = `<div style="display:flex;flex-direction:column;gap:12px;padding:10px;">
                <div style="display:flex;align-items:center;gap:8px;">
                    <div style="width:12px;height:12px;background:#7c3aed;border-radius:3px;"></div>
                    <div style="flex:1;">Featured</div>
                    <div style="font-weight:600;color:#7c3aed;">${fCount.toLocaleString()}</div>
                    <div style="width:45px;text-align:right;">${fPct}%</div>
                </div>
                <div style="display:flex;align-items:center;gap:8px;">
                    <div style="width:12px;height:12px;background:#64748b;border-radius:3px;"></div>
                    <div style="flex:1;">Regular</div>
                    <div style="font-weight:600;color:#64748b;">${rCount.toLocaleString()}</div>
                    <div style="width:45px;text-align:right;">${rPct}%</div>
                </div>
            </div>`;
        }

        function renderLocationChartAPI(locationData) {
            const container = document.getElementById('locationChart');
            if (!locationData || locationData.length === 0) {
                container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#94a3b8;">No data</div>';
                return;
            }
            const maxCount = Math.max(...locationData.map(item => item.count));
            const colors = ['#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444', '#ec4899', '#06b6d4', '#84cc16'];
            let html = '<div style="display:flex;align-items:flex-end;justify-content:space-around;height:100%;padding:20px 10px;gap:8px;">';
            locationData.slice(0, 10).forEach((item, i) => {
                const height = (item.count / maxCount) * 100;
                const color = colors[i % colors.length];
                html += `<div style="flex:1;display:flex;flex-direction:column;align-items:center;gap8px;">
                    <div style="font-size:0.875rem;font-weight:600;color:${color};">${item.count}</div>
                    <div style="width:100%;background:${color};height:${height}%;border-radius:4px 4px 0 0;" title="${item.name}: ${item.count}"></div>
                    <div style="font-size:0.75rem;color:#64748b;text-align:center;max-width:60px;overflow:hidden;text-overflow:ellipsis;">${item.name}</div>
                </div>`;
            });
            container.innerHTML = html + '</div>';
        }

        function renderTopLocationsTableAPI(topLocations) {
            const tableBody = document.getElementById('topLocationsTable');
            if (!topLocations || topLocations.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:20px;color:#94a3b8;">No location data</td></tr>';
                return;
            }
            let html = '';
            topLocations.forEach(location => {
                html += `<tr>
                    <td style="font-weight:600;">${location.name || 'Unknown'}</td>
                    <td><span style="background:#e0e7ff;color:#4f46e5;padding:4px 8px;border-radius:12px;font-size:0.75rem;font-weight:600;">${location.type || 'N/A'}</span></td>
                    <td style="font-weight:600;">${(location.total || 0).toLocaleString()}</td>
                    <td style="color:#10b981;font-weight:600;">${(location.active || 0).toLocaleString()}</td>
                    <td style="color:#7c3aed;font-weight:600;">${(location.featured || 0).toLocaleString()}</td>
                    <td>${(location.views || 0).toLocaleString()}</td>
                </tr>`;
            });
            tableBody.innerHTML = html;
        }

        // Auto-update every 30 seconds
        setInterval(() => { loadStatsFromAPI(); }, 30000);

        // Override updateOverviewFiltering to use API
        const originalUpdateOverviewFiltering = updateOverviewFiltering;
        updateOverviewFiltering = async function() {
            await loadStatsFromAPI();
            await loadChartsFromAPI();
            if (originalUpdateOverviewFiltering) originalUpdateOverviewFiltering();
        };

        // Initialize
        document.addEventListener('DOMContentLoaded', () => { 
            loadStatsFromAPI(); 
            loadChartsFromAPI(); 
        });
        
        // Legacy compatibility
        /* 
        function updateOverviewStats() {
            // No-op or forward to API
            loadStatsFromAPI();
        }
        
        function updateCharts() {
            loadChartsFromAPI();
        }
        */
    </script>

    <style>
        .modal {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(2px);
        }

        .modal-content {
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border-color);
            max-width: 90vw;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalSlideIn 0.3s ease-out;
            position: relative;
            margin: 0 auto;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 20px 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        /* Perfect centering with flexbox */
        .modal {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        /* Mobile responsive centering */
        @media (max-width: 768px) {
            .modal-content {
                width: 95vw;
                margin: 20px auto;
            }
        }
        
        /* Ensure modals are always centered */
        .modal-content {
            position: relative;
            left: 0;
            top: 0;
            transform: none;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-active {
            background: #dcfce7;
            color: #10b981;
        }

        .status-pending {
            background: #fef3c7;
            color: #f59e0b;
        }

        .status-sold {
            background: #fee2e2;
            color: #ef4444;
        }

        .status-expired {
            background: #f1f5f9;
            color: #64748b;
        }

        /* Enhanced pagination styles */
        #prevPage:disabled, #nextPage:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .table {
                font-size: 0.875rem;
            }
            .table th, .table td {
                padding: 8px 6px;
            }
            #pageNumbers {
                display: none;
            }
            .modal-content {
                max-width: 95vw;
                margin: 10px;
            }
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
        }

        /* Enhanced ad card styling */
        .ad-image-container {
            position: relative;
            display: inline-block;
        }

        .featured-badge {
            position: absolute;
            top: 8px;
            right: 8px;
            background: #7c3aed;
            color: white;
            border-radius: 12px;
            padding: 4px 8px;
            font-size: 0.75rem;
            font-weight: 600;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
    </style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\DND\Apps\CLXpro\clx_backend\resources\views/admin/ads/index.blade.php ENDPATH**/ ?>