@extends('admin.layouts.app')

@section('title', 'User Management')

@section('content')
    <style>
        /* Modal Input Styling for Dark Mode */
        /* Global Input & Form Styling for Dark Mode */
        input, select, textarea {
            background-color: var(--bg-secondary) !important;
            color: var(--text-primary) !important;
            border: 1px solid var(--border-color) !important;
        }

        /* Ensure dropdown options are readable */
        select option {
            background-color: var(--card-bg);
            color: var(--text-primary);
        }

        .modal-content input,
        .modal-content select,
        .modal-content textarea {
            background-color: var(--bg-secondary) !important;
            color: var(--text-primary) !important;
            border: 1px solid var(--border-color) !important;
        }

        /* Action Card Styling */
        .action-card {
            padding: 16px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--bg-secondary);
            transition: all 0.2s;
        }
    </style>

    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">User Management</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Manage user accounts and permissions</div>
        </div>
        
        <div style="padding: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <div style="display: flex; gap: 12px; align-items: center;">
                    <div style="position: relative;">
                        <input type="text" id="searchUsers" placeholder="Search users..." style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px; width: 300px;">
                        <span style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: var(--text-secondary);">🔍</span>
                    </div>
                    <select id="filterStatus" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        <option value="">All Status</option>
                        <option value="active">Active</option>
                        <option value="suspended">Suspended</option>
                        <option value="pending">Pending Verification</option>
                    </select>
                    <select id="filterPlan" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                        <option value="">All Plans</option>
                        <option value="premium">Premium</option>
                        <option value="basic">Basic</option>
                        <option value="free">Free</option>
                    </select>
                </div>
                
                <div style="display: flex; gap: 8px;">
                    <button onclick="exportUsers()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Export Users</button>
                    <button onclick="openBulkActions()" style="padding: 8px 16px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer;">Bulk Actions</button>
                    <button onclick="openUserAnalytics()" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">User Analytics</button>
                </div>
            </div>
            
            <!-- Statistics Cards -->
            <div class="dashboard-grid" style="margin-bottom: 24px;">
                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Total Users</div>
                            <div class="card-value">{{ number_format($stats['total']) }}</div>
                        </div>
                        <div class="stat-icon">👥</div>
                    </div>
                    <div class="card-change">All registered users</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Active Users</div>
                            <div class="card-value">{{ number_format($stats['active']) }}</div>
                        </div>
                        <div class="stat-icon">✅</div>
                    </div>
                    <div class="card-change">Last 30 days</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Premium Users</div>
                            <div class="card-value">{{ number_format($stats['premium']) }}</div>
                        </div>
                        <div class="stat-icon">💎</div>
                    </div>
                    <div class="card-change">Subscribed users</div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div>
                            <div class="card-title">Pending Verification</div>
                            <div class="card-value">{{ number_format($stats['pending']) }}</div>
                        </div>
                        <div class="stat-icon">⏳</div>
                    </div>
                    <div class="card-change">Awaiting approval</div>
                </div>
            </div>

            <!-- Users Table -->
            <div class="table-card" style="border: none; padding: 0;">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width: 50px;">
                                <input type="checkbox" id="selectAllUsers" style="width: 16px; height: 16px;">
                            </th>
                            <th>User</th>
                            <th>Email</th>
                            <th>Plan</th>
                            <th>Status</th>
                            <th>Trust Score</th>
                            <th>Ads</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                <tbody id="usersTableBody">
                    @forelse($users as $user)
                        <tr>
                            <td><input type="checkbox" class="user-checkbox" data-user-id="{{ $user->id }}" style="width: 16px; height: 16px;"></td>
                            <td>
                                <div style="display: flex; align-items: center; gap: 12px;">
                                    <div style="width: 40px; height: 40px; border-radius: 50%; background: {{ ['#7c3aed', '#f59e0b', '#ef4444', '#10b981', '#3b82f6'][rand(0,4)] }}; color: white; display: flex; align-items: center; justify-content: center; font-weight: bold;">
                                        {{ strtoupper(substr($user->name, 0, 2)) }}
                                    </div>
                                    <div>
                                        <div style="font-weight: 600; color: var(--text-primary);">{{ $user->name }}</div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">Joined: {{ $user->created_at->format('M d, Y') }}</div>
                                    </div>
                                </div>
                            </td>
                            <td style="color: var(--text-secondary);">
                                <div>{{ $user->email }}</div>
                                <div style="font-size: 0.75rem; margin-top: 2px;">{{ $user->phone_number ?? $user->mobile_number ?? 'N/A' }}</div>
                            </td>
                            <td>
                                @php
                                    $planName = $user->currentPlan->plan_name ?? 'Free';
                                    
                                    $planColor = match($planName) {
                                        'VIP Pro' => '#7c3aed',
                                        'VIP Seller' => '#f59e0b',
                                        'VIP Buyer' => '#3b82f6',
                                        default => '#6b7280'
                                    };
                                    $planBg = match($planName) {
                                        'VIP Pro' => '#f3e8ff',
                                        'VIP Seller' => '#fef3c7',
                                        'VIP Buyer' => '#dbeafe',
                                        default => '#f3f4f6'
                                    };
                                @endphp
                                <span style="background: {{ $planBg }}; color: {{ $planColor }}; padding: 4px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 600;">
                                    {{ $planName }}
                                </span>
                            </td>
                            <td>
                                @if($user->is_banned)
                                    <span class="status-badge status-inactive">Banned</span>
                                @elseif($user->is_suspended)
                                    <span class="status-badge status-inactive">Suspended</span>
                                @elseif(!$user->is_verified)
                                    <span class="status-badge status-pending">Pending</span>
                                @else
                                    <span class="status-badge status-active">Active</span>
                                @endif
                            </td>
                            <td>
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <div style="width: 60px; height: 6px; background: #e2e8f0; border-radius: 3px;">
                                        <div style="width: {{ $user->trustScore->score ?? 0 }}%; height: 100%; background: {{ ($user->trustScore->score ?? 0) > 70 ? '#10b981' : (($user->trustScore->score ?? 0) > 40 ? '#f59e0b' : '#ef4444') }}; border-radius: 3px;"></div>
                                    </div>
                                    <span style="font-weight: 600; color: {{ ($user->trustScore->score ?? 0) > 70 ? '#10b981' : (($user->trustScore->score ?? 0) > 40 ? '#f59e0b' : '#ef4444') }};">{{ $user->trustScore->score ?? 0 }}%</span>
                                </div>
                            </td>
                            <td style="font-weight: 600; color: var(--primary-color);">{{ $user->ads_count }}</td>
                            <td>
                                <div style="display: flex; gap: 8px;">
                                    <button onclick="viewUserProfile({{ $user->id }})" style="padding: 4px 8px; background: #3b82f6; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">View</button>
                                    <button onclick="editUser({{ $user->id }})" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Edit</button>
                                    
                                    @if(!$user->is_banned && !$user->is_suspended)
                                        <button onclick="suspendUser({{ $user->id }})" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Suspend</button>
                                    @endif

                                    <button onclick="deleteUser({{ $user->id }})" style="padding: 4px 8px; background: #6b7280; color: white; border: none; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">Delete</button>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 40px;">
                                <div style="font-size: 1.1rem; color: var(--text-secondary);">No users found</div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="8" style="padding: 20px;">
                            {{ $users->links() }}
                        </td>
                    </tr>
                </tfoot>
            </table>
            </div>
            
            <!-- Bulk Actions -->
            <div style="display: flex; gap: 12px; align-items: center; margin-top: 20px; padding: 16px; background: #f8fafc; border-radius: 8px; border: 1px solid var(--border-color);">
                <label style="font-weight: 600; color: var(--text-primary);">Bulk Actions:</label>
                <select id="userBulkAction" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                    <option value="">Select Action</option>
                    <option value="activate">Activate Selected</option>
                    <option value="suspend">Suspend Selected</option>
                    <option value="verify">Verify Selected</option>
                    <option value="delete">Delete Selected</option>
                    <option value="send_notification">Send Notification</option>
                </select>
                <button onclick="applyUserBulkAction()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Apply to Selected</button>
                <button onclick="selectAllUsers()" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer;">Select All</button>
                <button onclick="clearUserSelection()" style="padding: 8px 16px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Clear Selection</button>
            </div>
        </div>
    </div>

    <!-- Enhanced User Profile Modal -->
    <div id="userProfileModal" class="modal" style="display: none;">
        <div class="modal-content" style="width: 90vw; max-width: 1200px; height: 85vh; display: flex; flex-direction: column; overflow: hidden; background: var(--card-bg); color: var(--text-primary);">
            <div class="modal-header" style="padding: 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center;">
                <div style="display: flex; gap: 16px; align-items: center;">
                    <div id="userProfileImageContainer" style="width: 64px; height: 64px; border-radius: 50%; overflow: hidden; background: var(--bg-secondary); display: flex; align-items: center; justify-content: center; border: 2px solid var(--border-color);">
                        <!-- Image or Initials will be injected here -->
                    </div>
                    <div>
                        <h3 style="margin: 0; font-size: 1.25rem; color: var(--text-primary);" id="userProfileTitle">User Profile</h3>
                        <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;" id="userProfileSubtitle">Loading user details...</div>
                    </div>
                </div>
                <div style="display: flex; gap: 8px; align-items: center;">
                    <button onclick="exportUserReport()" style="padding: 8px 12px; background: #10b981; color: white; border: none; border-radius: 6px; font-size: 0.875rem; cursor: pointer;">Export Report</button>
                    <button onclick="openUserActions()" style="padding: 8px 12px; background: #f59e0b; color: white; border: none; border-radius: 6px; font-size: 0.875rem; cursor: pointer;">Quick Actions</button>
                    <button onclick="closeUserProfileModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; padding: 4px 8px; border-radius: 4px; color: var(--text-secondary);">×</button>
                </div>
            </div>
            
            <div style="display: flex; height: calc(90vh - 80px);">
                <!-- Sidebar Navigation -->
                <div style="width: 280px; background: var(--bg-secondary); border-right: 1px solid var(--border-color); padding: 20px; overflow-y: auto;">
                    <div style="display: flex; flex-direction: column; gap: 12px;">
                        <button onclick="showUserSection('overview')" class="nav-btn active" data-section="overview">
                            <span style="font-size: 1.2rem; margin-right: 12px;">👤</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Overview</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Basic info & stats</div>
                            </div>
                        </button>
                        
                        <button onclick="showUserSection('ads')" class="nav-btn" data-section="ads">
                            <span style="font-size: 1.2rem; margin-right: 12px;">📊</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Ads & Listings</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Active & expired ads</div>
                            </div>
                        </button>
                        
                        <button onclick="showUserSection('transactions')" class="nav-btn" data-section="transactions">
                            <span style="font-size: 1.2rem; margin-right: 12px;">💳</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Transactions</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Payments & purchases</div>
                            </div>
                        </button>
                        
                        <button onclick="showUserSection('security')" class="nav-btn" data-section="security">
                            <span style="font-size: 1.2rem; margin-right: 12px;">🔒</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Security</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Login history & 2FA</div>
                            </div>
                        </button>
                        
                        <button onclick="showUserSection('analytics')" class="nav-btn" data-section="analytics">
                            <span style="font-size: 1.2rem; margin-right: 12px;">📈</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Analytics</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Behavior & engagement</div>
                            </div>
                        </button>
                        
                        <button onclick="showUserSection('reports')" class="nav-btn" data-section="reports">
                            <span style="font-size: 1.2rem; margin-right: 12px;">⚠️</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Reports</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Safety & violations</div>
                            </div>
                        </button>
                        
                        <button onclick="showUserSection('settings')" class="nav-btn" data-section="settings">
                            <span style="font-size: 1.2rem; margin-right: 12px;">⚙️</span>
                            <div style="text-align: left;">
                                <div style="font-weight: 600; font-size: 0.875rem;">Settings</div>
                                <div style="font-size: 0.75rem; color: var(--text-secondary);">Preferences & controls</div>
                            </div>
                        </button>
                    </div>
                </div>
                
                <!-- Main Content Area -->
                <div style="flex: 1; overflow-y: auto; padding: 20px; background: var(--card-bg);">
                    <div id="userProfileContent">
                        <!-- Content will be loaded here based on selected section -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions Modal -->
    <div id="userActionsModal" class="modal" style="display: none;">
        <div class="modal-content" style="width: 700px; max-width: 95vw; background: var(--card-bg); color: var(--text-primary);">
            <div class="modal-header">
                <h3 style="margin: 0;">Quick Actions</h3>
                <button onclick="closeUserActionsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">×</button>
            </div>
            <div style="padding: 20px;">
                <div style="display: grid; gap: 16px;">
                    <div class="action-card">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: rgba(16, 185, 129, 0.15); color: #10b981; display: flex; align-items: center; justify-content: center; font-weight: bold;">✅</div>
                            <div>
                                <div style="font-weight: 600; color: var(--text-primary);">Verify User</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Manually verify user identity</div>
                            </div>
                        </div>
                        <button onclick="verifyUserQuick()" style="margin-top: 12px; padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; width: 100%;">Verify Now</button>
                    </div>
                    
                    <div class="action-card">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: rgba(239, 68, 68, 0.15); color: #ef4444; display: flex; align-items: center; justify-content: center; font-weight: bold;">🚫</div>
                            <div>
                                <div style="font-weight: 600; color: var(--text-primary);">Suspend User</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Temporarily disable account</div>
                            </div>
                        </div>
                        <div style="margin-top: 12px; display: grid; gap: 8px;">
                            <select id="suspendDuration" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                <option value="1">1 Hour</option>
                                <option value="24">1 Day</option>
                                <option value="168">1 Week</option>
                                <option value="720">1 Month</option>
                                <option value="permanent">Permanent</option>
                            </select>
                            <textarea id="suspendReason" rows="3" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Reason for suspension..."></textarea>
                            <button onclick="suspendUserQuick()" style="padding: 8px 16px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; width: 100%;">Suspend User</button>
                        </div>
                    </div>
                    
                    <div class="action-card">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: rgba(14, 165, 233, 0.15); color: #0ea5e9; display: flex; align-items: center; justify-content: center; font-weight: bold;">📧</div>
                            <div>
                                <div style="font-weight: 600; color: var(--text-primary);">Send Notification</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Send push/email notification</div>
                            </div>
                        </div>
                        <div style="margin-top: 12px; display: grid; gap: 8px;">
                            <select id="notificationType" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                <option value="info">Information</option>
                                <option value="warning">Warning</option>
                                <option value="error">Error</option>
                                <option value="success">Success</option>
                            </select>
                            <textarea id="notificationMessage" rows="3" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Notification message..."></textarea>
                            <button onclick="sendNotificationQuick()" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; width: 100%;">Send Notification</button>
                        </div>
                    </div>
                    
                    <div class="action-card">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; border-radius: 8px; background: rgba(245, 158, 11, 0.15); color: #f59e0b; display: flex; align-items: center; justify-content: center; font-weight: bold;">💎</div>
                            <div>
                                <div style="font-weight: 600; color: var(--text-primary);">Upgrade Plan</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Change user subscription</div>
                            </div>
                        </div>
                        <div style="margin-top: 12px; display: grid; gap: 8px;">
                            <select id="newPlan" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                                @foreach($allPlans as $plan)
                                    <option value="{{ $plan->id }}">{{ $plan->plan_name }} ({{ number_format($plan->price, 2) }})</option>
                                @endforeach
                            </select>
                            <div style="display: flex; gap: 8px;">
                                <button onclick="upgradePlanQuick()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; flex: 1;">Upgrade</button>
                                <button onclick="downgradePlanQuick()" style="padding: 8px 16px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer; flex: 1;">Downgrade</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bulk Actions Modal -->
    <div id="bulkActionsModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px; background-color: var(--card-bg) !important; color: var(--text-primary) !important;">
            <div class="modal-header">
                <h3 style="margin: 0;">Bulk Actions</h3>
                <button onclick="closeBulkActionsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; color: var(--text-primary);">×</button>
            </div>
            <div id="bulkActionsContent" style="padding: 20px;">
                <div style="display: grid; gap: 16px;">
                    <div>
                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Action Type</label>
                        <select id="bulkActionType" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;">
                            <option value="activate">Activate Users</option>
                            <option value="suspend">Suspend Users</option>
                            <option value="verify">Verify Users</option>
                            <option value="delete">Delete Users</option>
                            <option value="send_notification">Send Notification</option>
                        </select>
                    </div>
                    
                    <div id="notificationMessage" style="display: none;">
                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-primary);">Notification Message</label>
                        <textarea id="bulkNotificationMessage" rows="4" style="width: 100%; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 6px;" placeholder="Enter your message..."></textarea>
                    </div>

                    <div style="display: flex; gap: 12px; justify-content: flex-end;">
                        <button onclick="closeBulkActionsModal()" style="padding: 8px 16px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Cancel</button>
                        <button onclick="executeBulkAction()" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;">Execute Action</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // State management
        let selectedUsers = new Set();
        let currentUserData = null; // Store loaded user data

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            setupUserEventListeners();
        });

        // Event Listeners
        function setupUserEventListeners() {
            document.getElementById('selectAllUsers').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.user-checkbox');
                checkboxes.forEach(cb => {
                    cb.checked = this.checked;
                    if (this.checked) {
                        selectedUsers.add(parseInt(cb.dataset.userId));
                    } else {
                        selectedUsers.clear();
                    }
                });
            });

            document.getElementById('bulkActionType').addEventListener('change', function() {
                const notificationMessage = document.getElementById('notificationMessage');
                if (this.value === 'send_notification') {
                    notificationMessage.style.display = 'block';
                } else {
                    notificationMessage.style.display = 'none';
                }
            });

            // Enhanced Search
            document.getElementById('searchUsers').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = document.querySelectorAll('#usersTableBody tr');
                
                rows.forEach(row => {
                    const userName = row.querySelector('td:nth-child(2) div:first-child').textContent.toLowerCase();
                    const userEmail = row.querySelector('td:nth-child(3)').textContent.toLowerCase();
                    
                    if (userName.includes(searchTerm) || userEmail.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
        }
        
        function getInitials(name) {
            return name
                .split(' ')
                .map(n => n[0])
                .slice(0, 2)
                .join('')
                .toUpperCase();
        }

        // --- User Profile Functions ---

        async function viewUserProfile(userId) {
            // Show loading state
            document.getElementById('userProfileModal').style.display = 'flex';
            document.getElementById('userProfileTitle').textContent = `User Profile`;
            document.getElementById('userProfileSubtitle').textContent = `Loading data...`;
            document.getElementById('userProfileContent').innerHTML = '<div style="padding: 40px; text-align: center;">Loading user details...</div>';

            try {
                const response = await fetch(`/admin/users/${userId}/details`);
                const data = await response.json();
                currentUserData = data; // Save for tab switching

                // Update Header
                document.getElementById('userProfileTitle').textContent = data.user.name;
                const phone = data.user.phone_number || data.user.mobile_number || 'No Phone';
                document.getElementById('userProfileSubtitle').textContent = data.user.email + ' • ' + phone + ' • Joined ' + new Date(data.user.created_at).toLocaleDateString();

                // Update Profile Picture
                const userImg = data.user.profile_picture || data.user.profile_image;
                const imgContainer = document.getElementById('userProfileImageContainer');
                
                if (userImg) {
                    // Start with /storage/ if not absolute URL
                    const src = userImg.startsWith('http') ? userImg : `/storage/${userImg}`;
                    imgContainer.innerHTML = `<img src="${src}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.style.display='none'; this.parentElement.innerHTML='${getInitials(data.user.name)}'">`;
                } else {
                    imgContainer.innerHTML = `<div style="font-size: 1.5rem; font-weight: 700; color: var(--text-secondary);">${getInitials(data.user.name)}</div>`;
                }

                // Show default section (Overview)
                renderUserOverview(data);
                
                // Reset Active Tab
                document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
                document.querySelector('.nav-btn[data-section="overview"]').classList.add('active');

            } catch (error) {
                console.error('Error fetching user details:', error);
                document.getElementById('userProfileContent').innerHTML = '<div style="color: red; padding: 20px;">Failed to load user data.</div>';
            }
        }

        function showUserSection(section) {
            // Update Tab UI
            document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector(`.nav-btn[data-section="${section}"]`).classList.add('active');

            // Render Content
            if (!currentUserData) return;

            if (section === 'overview') renderUserOverview(currentUserData);
            else if (section === 'ads') renderUserAds(currentUserData);
            else if (section === 'analytics') renderUserAnalytics(currentUserData);
            else if (section === 'security') renderUserSecurity(currentUserData);
            else if (section === 'settings') renderUserSettings(currentUserData);
            else {
                document.getElementById('userProfileContent').innerHTML = `<div style="padding:20px;">Section ${section} is under construction</div>`;
            }
        }

        function renderUserOverview(data) {
            const user = data.user;
            const stats = data.stats;
            
            // Map logic
            let mapHtml = '';
            if (user.latitude && user.longitude) {
                // We'll initialize map after render
                setTimeout(() => initMap(user.latitude, user.longitude), 100);
                 mapHtml = `<div id="userMap" style="width: 100%; height: 100%; z-index: 1;"></div>`;
            } else {
                 mapHtml = `
                    <div style="text-align: center; z-index: 10;">
                        <i class="fas fa-map-marker-alt" style="font-size: 2rem; color: #ef4444; margin-bottom: 8px;"></i>
                        <div style="font-weight: 600; color: var(--text-secondary);">No Location Data Available</div>
                    </div>`;
            }
            
            let html = `
                <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px;">
                    <!-- Left Column -->
                    <div style="display: flex; flex-direction: column; gap: 24px;">
                        
                        <!-- Quick Stats Row -->
                         <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px;">
                              <div style="background: var(--bg-secondary); padding: 16px; border-radius: 12px; border: 1px solid var(--border-color);">
                                <div style="font-size: 0.8rem; color: var(--text-secondary); margin-bottom: 4px;">Trust Score</div>
                                <div style="font-size: 1.5rem; font-weight: 700; color: ${stats.trust_score > 80 ? '#10b981' : '#f59e0b'};">${stats.trust_score}%</div>
                             </div>
                             <div style="background: var(--bg-secondary); padding: 16px; border-radius: 12px; border: 1px solid var(--border-color);">
                                <div style="font-size: 0.8rem; color: var(--text-secondary); margin-bottom: 4px;">Total Ads</div>
                                <div style="font-size: 1.5rem; font-weight: 700; color: var(--text-primary);">${stats.total_ads}</div>
                             </div>
                             <div style="background: var(--bg-secondary); padding: 16px; border-radius: 12px; border: 1px solid var(--border-color);">
                                <div style="font-size: 0.8rem; color: var(--text-secondary); margin-bottom: 4px;">Reports</div>
                                <div style="font-size: 1.5rem; font-weight: 700; color: ${stats.safety_reports > 0 ? '#ef4444' : '#10b981'};">${stats.safety_reports}</div>
                             </div>
                        </div>

                        <!-- Basic Info Card -->
                        <div class="card" style="box-shadow: none; border: 1px solid var(--border-color);">
                            <div class="card-header" style="padding-bottom: 0; border: none;">
                                <h4 style="margin: 0; font-size: 1.1rem;">Basic Details</h4>
                                <button onclick="enableEditMode()" style="color: var(--primary-color); background: none; border: none; font-weight: 600; cursor: pointer;">Edit</button>
                            </div>
                            <!-- Read Mode -->
                            <div id="userOverviewRead" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; padding: 20px;">
                                <div>
                                    <label style="display: block; font-size: 0.8rem; color: var(--text-secondary);">Full Name</label>
                                    <div style="font-weight: 500;">${user.name}</div>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 0.8rem; color: var(--text-secondary);">Email Address</label>
                                    <div style="font-weight: 500;">${user.email}</div>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 0.8rem; color: var(--text-secondary);">Phone Number</label>
                                    <div style="font-weight: 500;">${user.phone_number || 'Not provided'}</div>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 0.8rem; color: var(--text-secondary);">Location</label>
                                    <div style="font-weight: 500;">${user.city || 'Unknown'}, ${user.country || ''}</div>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 0.8rem; color: var(--text-secondary);">Verified</label>
                                    <div style="font-weight: 500;">${user.is_verified ? '<span style="color:#10b981">Yes</span>' : '<span style="color:#ef4444">No</span>'}</div>
                                </div>
                            </div>

                            <!-- Edit Mode -->
                            <form id="userOverviewEdit" onsubmit="saveUserChanges(event)" style="display: none; padding: 20px; grid-template-columns: 1fr 1fr; gap: 20px;">
                                <div class="form-group">
                                    <label class="form-label">Full Name</label>
                                    <input type="text" name="name" class="form-input" value="${user.name}" required>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Email Address</label>
                                    <input type="email" name="email" class="form-input" value="${user.email}" required>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Phone Number</label>
                                    <input type="text" name="phone_number" class="form-input" value="${user.phone_number || ''}">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Verified User</label>
                                    <select name="is_verified" class="form-select">
                                        <option value="1" ${user.is_verified ? 'selected' : ''}>Yes</option>
                                        <option value="0" ${!user.is_verified ? 'selected' : ''}>No</option>
                                    </select>
                                </div>
                                <div style="grid-column: 1 / -1; display: flex; gap: 10px; justify-content: flex-end;">
                                    <button type="button" onclick="cancelEditMode()" style="padding: 8px 16px; border: 1px solid var(--border-color); background: var(--card-bg); border-radius: 6px; cursor: pointer; color: var(--text-primary);">Cancel</button>
                                    <button type="submit" style="padding: 8px 16px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer;">Save Changes</button>
                                </div>
                            </form>
                        </div>

                         <!-- Map Preview -->
                        <div class="card" style="box-shadow: none; border: 1px solid var(--border-color); overflow: hidden; height: 300px; background: var(--bg-secondary); display: flex; align-items: center; justify-content: center; position: relative;">
                             ${mapHtml}
                        </div>
                    </div>

                    <!-- Right Column (Status & Actions) -->
                    <div style="display: flex; flex-direction: column; gap: 24px;">
                         <div class="card" style="box-shadow: none; border: 1px solid var(--border-color); background: var(--bg-secondary);">
                            <div style="padding: 20px;">
                                <h4 style="margin: 0 0 16px 0; font-size: 1rem;">Account Status</h4>
                                
                                <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
                                    <span>Status</span>
                                    <span class="status-badge ${user.is_banned ? 'status-inactive' : 'status-active'}">
                                        ${user.is_banned ? 'BANNED' : (user.is_suspended ? 'SUSPENDED' : 'ACTIVE')}
                                    </span>
                                </div>

                                <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
                                    <span>Plan</span>
                                    <span style="background: #f3e8ff; color: #7c3aed; padding: 4px 8px; border-radius: 4px; font-weight: 600; font-size: 0.8rem;">
                                        ${user.current_plan ? user.current_plan.plan_name : 'Free'}
                                    </span>
                                </div>

                                <div style="display: grid; gap: 8px; margin-top: 24px;">
                                    ${!user.is_banned ? 
                                      `<button onclick="openUserActions()" style="width: 100%; padding: 10px; background: #ef4444; color: white; border: none; border-radius: 6px; font-weight: 600; cursor: pointer;">Suspend / Ban</button>` :
                                      `<button onclick="performAction('unban', ${user.id})" style="width: 100%; padding: 10px; background: #10b981; color: white; border: none; border-radius: 6px; font-weight: 600; cursor: pointer;">Unban User</button>`
                                    }
                                </div>
                            </div>
                         </div>
                    </div>
                </div>
            `;
            document.getElementById('userProfileContent').innerHTML = html;
        }

        function initMap(lat, lng) {
             if (typeof L === 'undefined') return; // Leaflet not loaded
             
             // Remove existing map if any
             if (window.userMapInstance) {
                 window.userMapInstance.remove();
             }

             window.userMapInstance = L.map('userMap').setView([lat, lng], 13);
             
             L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; OpenStreetMap contributors'
             }).addTo(window.userMapInstance);

             L.marker([lat, lng]).addTo(window.userMapInstance)
                .bindPopup('User Location')
                .openPopup();
        }

        function enableEditMode() {
            document.getElementById('userOverviewRead').style.display = 'none';
            document.getElementById('userOverviewEdit').style.display = 'grid';
        }

        function cancelEditMode() {
            document.getElementById('userOverviewRead').style.display = 'grid';
            document.getElementById('userOverviewEdit').style.display = 'none';
        }
        
        async function saveUserChanges(event) {
            event.preventDefault();
            const form = event.target;
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());
            
            // Convert select "1"/"0" to boolean for API if needed, or send as is
            // Add CSRF token
            const csrfToken = document.querySelector('meta[name="csrf-token"]').content;

            try {
                const response = await fetch(`/admin/users/${currentUserData.user.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('User updated successfully!');
                    viewUserProfile(currentUserData.user.id); // Reload
                } else {
                    alert('Error: ' + (result.message || 'Update failed'));
                }
            } catch (error) {
                console.error('Update error:', error);
                alert('An error occurred while saving changes.');
            }
        }

        function renderUserAds(data) {
             let html = '<h3 style="margin-top:0;">Recent Listings</h3><div style="display: grid; gap: 16px;">';
             if (data.user_ads.length === 0) {
                 html += '<div style="padding: 20px; text-align: center; color: var(--text-secondary);">No ads found for this user.</div>';
             } else {
                 data.user_ads.forEach(ad => {
                     html += `
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 16px; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 8px;">
                            <div style="display: flex; gap: 12px; align-items: center;">
                                <div style="width: 48px; height: 48px; background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 6px;"></div> <!-- Placeholder -->
                                <div>
                                    <div style="font-weight: 600;">${ad.title}</div>
                                    <div style="font-size: 0.85rem; color: var(--text-secondary);">${ad.price} ${ad.currency} • ${new Date(ad.created_at).toLocaleDateString()}</div>
                                </div>
                            </div>
                            <div style="text-align: right;">
                                <span class="status-badge ${ad.status === 'active' ? 'status-active' : 'status-pending'}" style="margin-bottom: 4px; display: inline-block;">${ad.status}</span>
                                <div style="font-size: 0.8rem; color: var(--text-secondary);">👁️ ${ad.views} views</div>
                            </div>
                        </div>
                     `;
                 });
             }
             html += '</div>';
             document.getElementById('userProfileContent').innerHTML = html;
        }

        function renderUserAnalytics(data) {
             const stats = data.stats;
             document.getElementById('userProfileContent').innerHTML = `
                <h3>Behavioral Analytics</h3>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 24px;">
                     <div class="card" style="box-shadow: none; border: 1px solid var(--border-color); padding: 20px;">
                        <h4 style="margin: 0 0 16px 0;">Engagement</h4>
                        <div style="display: grid; gap: 12px;">
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-secondary);">Total Ad Views</span>
                                <span style="font-weight: 600;">${stats.total_views}</span>
                            </div>
                             <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-secondary);">Avg. Response Time</span>
                                <span style="font-weight: 600;">~2.4 hrs</span>
                            </div>
                        </div>
                     </div>
                     
                     <div class="card" style="box-shadow: none; border: 1px solid var(--border-color); padding: 20px;">
                        <h4 style="margin: 0 0 16px 0;">Trust & Safety</h4>
                        <div style="display: grid; gap: 12px;">
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-secondary);">Trust Score</span>
                                <span style="font-weight: 600; color: ${stats.trust_score > 70 ? '#10b981' : '#f59e0b'}">${stats.trust_score}/100</span>
                            </div>
                            <div style="display: flex; justify-content: space-between;">
                                <span style="color: var(--text-secondary);">Account Age</span>
                                <span style="font-weight: 600;">${stats.account_age_days} days</span>
                            </div>
                        </div>
                     </div>
                </div>
             `;
        }

        function renderUserSecurity(data) {
             document.getElementById('userProfileContent').innerHTML = `
                <h3>Security Settings</h3>
                 <div class="card" style="box-shadow: none; border: 1px solid var(--border-color); padding: 20px;">
                    <div style="display: grid; gap: 16px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <div style="font-weight: 600;">Two-Factor Authentication</div>
                                <div style="font-size: 0.85rem; color: var(--text-secondary);">Extra layer of security</div>
                            </div>
                            <span class="status-badge status-inactive">Disabled</span>
                        </div>
                         <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <div style="font-weight: 600;">Last Password Change</div>
                            </div>
                            <div style="font-size: 0.9rem; color: var(--text-secondary);">3 months ago</div>
                        </div>
                    </div>
                 </div>
             `;
        }
        
        function renderUserSettings(data) {
             document.getElementById('userProfileContent').innerHTML = `
                <div style="text-align:center; padding: 40px; color: var(--text-secondary);">
                    <i class="fas fa-cogs" style="font-size: 2rem; margin-bottom: 12px;"></i>
                    <p>User preference settings are not yet editable by admins.</p>
                </div>
             `;
        }

        function performAction(action, userId) {
            if(!confirm(`Are you sure you want to perform: ${action}?`)) return;
            
            // Here you would call fetch() to post the action
            alert(`Action ${action} triggered for user ${userId}. (Backend integration pending)`);
            
            // Example Integration:
            // fetch(\`/admin/users/\${userId}/\${action}\`, { method: 'POST', body: JSON.stringify({_token: '{{ csrf_token() }}'}) })
            // .then(res => res.json())
            // .then(res => { if(res.success) alert('Success'); viewUserProfile(userId); }); 
        }

        // --- Other Modal Functions ---

        function editUser(userId) {
            // Open the profile modal then switch to edit mode (simple implementation)
            viewUserProfile(userId).then(() => {
                // In a real app, this might show a form or separate modal
                console.log("Edit mode triggered for", userId);
                // Switch to edit mode automatically
                 setTimeout(() => enableEditMode(), 500);
            });
        }

        function suspendUser(userId) {
            if (confirm('Are you sure you want to suspend this user?')) {
                // Real implementation would use fetch
                 alert(`User #${userId} suspension request sent.`);
            }
        }

        function deleteUser(userId) {
            if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
                 alert(`User #${userId} deletion request sent.`);
            }
        }

        function applyUserBulkAction() {
            const action = document.getElementById('userBulkAction').value;
            const selected = Array.from(selectedUsers);
            
            if (selected.length === 0) {
                alert('Please select at least one user.');
                return;
            }

            if (action === 'activate' || action === 'suspend' || action === 'verify' || action === 'delete') {
                const actionText = action.charAt(0).toUpperCase() + action.slice(1);
                if (confirm(`Are you sure you want to ${action} ${selected.length} users?`)) {
                    alert(`${actionText} action applied to ${selected.length} users.`);
                }
            } else if (action === 'send_notification') {
                openBulkActionsModal();
            }
        }

        // Utility Functions
        function selectAllUsers() {
            const checkboxes = document.querySelectorAll('.user-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = true;
                selectedUsers.add(parseInt(cb.dataset.userId));
            });
        }

        function clearUserSelection() {
            const checkboxes = document.querySelectorAll('.user-checkbox');
            checkboxes.forEach(cb => {
                cb.checked = false;
            });
            selectedUsers.clear();
        }

        function exportUsers() {
            alert('Export functionality would be implemented here.');
        }

        function openBulkActions() {
            document.getElementById('bulkActionsModal').style.display = 'flex';
        }

        function openUserAnalytics() {
             alert('Global user analytics dashboard is under construction.');
        }

        function openBulkActionsModal() {
            document.getElementById('bulkActionsModal').style.display = 'flex';
        }

        function closeBulkActionsModal() {
            document.getElementById('bulkActionsModal').style.display = 'none';
        }
        
        function openUserActions() {
             document.getElementById('userActionsModal').style.display = 'flex';
        }

        function closeUserProfileModal() {
            document.getElementById('userProfileModal').style.display = 'none';
            currentUserData = null;
        }

        function closeUserActionsModal() {
            document.getElementById('userActionsModal').style.display = 'none';
        }

        function executeBulkAction() {
            const action = document.getElementById('bulkActionType').value;
            const selected = Array.from(selectedUsers);
            
            if (selected.length === 0) {
                alert('Please select at least one user.');
                return;
            }

            if (action === 'send_notification') {
                const message = document.getElementById('bulkNotificationMessage').value;
                if (!message.trim()) {
                    alert('Please enter a message.');
                    return;
                }
                alert(`Notification sent to ${selected.length} users: "${message}"`);
            } else {
                const actionText = action.charAt(0).toUpperCase() + action.slice(1);
                alert(`${actionText} action applied to ${selected.length} users.`);
            }
            
            closeBulkActionsModal();
        }

        // --- Quick Actions Functions ---

        async function verifyUserQuick() {
            if (!currentUserData) return;
            if (!confirm('Are you sure you want to verify this user?')) return;

            try {
                const response = await fetch(`/admin/users/${currentUserData.user.id}/verify`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });
                const result = await response.json();
                if (result.success) {
                    alert(result.message);
                    closeUserActionsModal();
                    viewUserProfile(currentUserData.user.id); // Reload
                } else {
                    alert('Error: ' + result.message);
                }
            } catch (error) {
                console.error(error);
                alert('An error occurred.');
            }
        }

        async function suspendUserQuick() {
            if (!currentUserData) return;
            const duration = document.getElementById('suspendDuration').value;
            const reason = document.getElementById('suspendReason').value;
            
            if (!reason) {
                alert('Please provide a reason for suspension.');
                return;
            }

            if (!confirm('Are you sure you want to suspend this user?')) return;

            try {
                const response = await fetch(`/admin/users/${currentUserData.user.id}/suspend`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ duration_days: duration === 'permanent' ? 36500 : duration, reason: reason })
                });
                const result = await response.json();
                if (result.success) {
                    alert(result.message);
                    closeUserActionsModal();
                    viewUserProfile(currentUserData.user.id);
                } else {
                    alert('Error: ' + result.message);
                }
            } catch (error) {
                console.error(error);
                alert('An error occurred.');
            }
        }

        async function sendNotificationQuick() {
            if (!currentUserData) return;
            const type = document.getElementById('notificationType').value;
            const message = document.getElementById('notificationMessage').value;

            if (!message) {
                alert('Please enter a message.');
                return;
            }

            try {
                const response = await fetch(`/admin/users/${currentUserData.user.id}/notify`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ type, message })
                });
                const result = await response.json();
                if (result.success) {
                    alert(result.message);
                    document.getElementById('notificationMessage').value = ''; // Clear
                    closeUserActionsModal();
                } else {
                    alert('Error: ' + result.message);
                }
            } catch (error) {
                console.error(error);
                alert('An error occurred.');
            }
        }

        async function upgradePlanQuick() {
            changeUserPlan('upgrade');
        }

        async function downgradePlanQuick() {
            changeUserPlan('downgrade');
        }

        async function changeUserPlan(action) {
            if (!currentUserData) return;
            const planId = document.getElementById('newPlan').value;

            if (!confirm(`Are you sure you want to ${action} this user's plan?`)) return;

            try {
                const response = await fetch(`/admin/users/${currentUserData.user.id}/change-plan`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ plan_id: planId, action: action })
                });
                const result = await response.json();
                if (result.success) {
                    alert(result.message);
                    closeUserActionsModal();
                    viewUserProfile(currentUserData.user.id);
                } else {
                    alert('Error: ' + result.message);
                }
            } catch (error) {
                console.error(error);
                alert('An error occurred.');
            }
        }
    </script>

    <style>
        /* Modal styles */
        .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;
        }

        /* Status badges */
        .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-inactive {
            background: #fee2e2;
            color: #ef4444;
        }
    </style>
@endsection
