@extends('admin.layout.main')

@section('admin')
<div class="flex flex-col h-full">
    <!-- Header -->
    <div class="mb-8">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
                <h1 class="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white">Contact Messages</h1>
                <p class="text-gray-500 dark:text-gray-400 mt-1">Manage all incoming contact messages</p>
               
            </div>
            
        </div>
    </div>

    <!-- Stats Overview -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <!-- Total Messages -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-5 border border-gray-100 dark:border-gray-700/50 shadow-sm">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Total Messages</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ $totalContacts }}</p>
                </div>
                <div class="w-10 h-10 rounded-lg bg-blue-50 dark:bg-blue-900/20 flex items-center justify-center">
                    <i class="fas fa-envelope text-blue-500 dark:text-blue-400"></i>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-700">
                <p class="text-xs text-gray-500 dark:text-gray-400">All time messages</p>
            </div>
        </div>

        <!-- Unread -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-5 border border-gray-100 dark:border-gray-700/50 shadow-sm">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Unread</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ $unreadContacts }}</p>
                </div>
                <div class="w-10 h-10 rounded-lg bg-red-50 dark:bg-red-900/20 flex items-center justify-center">
                    <i class="fas fa-envelope-open text-red-500 dark:text-red-400"></i>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-700">
                @php
                    $unreadPercentage = $totalContacts > 0 ? ($unreadContacts / $totalContacts) * 100 : 0;
                @endphp
                <div class="flex items-center gap-2">
                    <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5">
                        <div class="bg-red-500 h-1.5 rounded-full transition-all duration-300" 
                             style="width: {{ $unreadPercentage }}%"></div>
                    </div>
                    <span class="text-xs font-medium text-red-600 dark:text-red-400">{{ number_format($unreadPercentage, 0) }}%</span>
                </div>
            </div>
        </div>

        <!-- Read -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-5 border border-gray-100 dark:border-gray-700/50 shadow-sm">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Read</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ $readContacts }}</p>
                </div>
                <div class="w-10 h-10 rounded-lg bg-green-50 dark:bg-green-900/20 flex items-center justify-center">
                    <i class="fas fa-check-circle text-green-500 dark:text-green-400"></i>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-700">
                <div class="flex items-center justify-between">
                    <span class="text-xs text-gray-500 dark:text-gray-400">Reviewed messages</span>
                </div>
            </div>
        </div>

        <!-- Responded -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-5 border border-gray-100 dark:border-gray-700/50 shadow-sm">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Responded</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ $respondedContacts }}</p>
                </div>
                <div class="w-10 h-10 rounded-lg bg-purple-50 dark:bg-purple-900/20 flex items-center justify-center">
                    <i class="fas fa-reply text-purple-500 dark:text-purple-400"></i>
                </div>
            </div>
            <div class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-700">
                <div class="flex items-center justify-between">
                    <span class="text-xs text-gray-500 dark:text-gray-400">Resolved messages</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-100 dark:border-gray-700/50 shadow-sm p-5 mb-6">
        <form method="GET" action="{{ route('admin.contacts.index') }}" class="space-y-4" id="filterForm">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- Status Filter -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Status</label>
                    <select name="status" 
                            class="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-3 py-2 text-sm
                                   bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white 
                                   focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none">
                        <option value="all" {{ request('status') == 'all' ? 'selected' : '' }}>All Status</option>
                        <option value="new" {{ request('status') == 'new' ? 'selected' : '' }}>Unread</option>
                        <option value="read" {{ request('status') == 'read' ? 'selected' : '' }}>Read</option>
                        <option value="responded" {{ request('status') == 'responded' ? 'selected' : '' }}>Responded</option>
                        <option value="archived" {{ request('status') == 'archived' ? 'selected' : '' }}>Archived</option>
                    </select>
                </div>
                
                <!-- Date From -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">From Date</label>
                    <input type="date" 
                           name="date_from" 
                           value="{{ request('date_from') }}"
                           class="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-3 py-2 text-sm
                                  bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white 
                                  focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none">
                </div>
                
                <!-- Date To -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">To Date</label>
                    <input type="date" 
                           name="date_to" 
                           value="{{ request('date_to') }}"
                           class="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-3 py-2 text-sm
                                  bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white 
                                  focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none">
                </div>
                
                <!-- Sort By -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Sort By</label>
                    <select name="sort_by" 
                            class="w-full border border-gray-200 dark:border-gray-700 rounded-lg px-3 py-2 text-sm
                                   bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white 
                                   focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none">
                        <option value="created_at" {{ request('sort_by') == 'created_at' ? 'selected' : '' }}>Date</option>
                        <option value="name" {{ request('sort_by') == 'name' ? 'selected' : '' }}>Name</option>
                        <option value="email" {{ request('sort_by') == 'email' ? 'selected' : '' }}>Email</option>
                        <option value="status" {{ request('sort_by') == 'status' ? 'selected' : '' }}>Status</option>
                    </select>
                </div>
            </div>
            
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div class="flex gap-3">
                    <button type="submit" 
                            class="inline-flex items-center gap-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 py-2 rounded-lg 
                                   hover:from-blue-600 hover:to-blue-700 active:scale-[0.98] transition-all shadow-sm hover:shadow text-sm">
                        <i class="fas fa-filter text-xs"></i>
                        Apply Filters
                    </button>
                    <a href="{{ route('admin.contacts.index') }}" 
                       class="inline-flex items-center gap-2 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 
                              px-4 py-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors text-sm">
                        <i class="fas fa-times text-xs"></i>
                        Clear Filters
                    </a>
                </div>
                
                <!-- Bulk Actions -->
                <div class="flex items-center gap-3">
                    <select id="bulkAction" 
                            class="border border-gray-200 dark:border-gray-700 rounded-lg px-3 py-2 text-sm
                                   bg-gray-50 dark:bg-gray-700/50 text-gray-900 dark:text-white 
                                   focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none">
                        <option value="">Bulk Actions</option>
                        <option value="mark_read">Mark as Read</option>
                        <option value="mark_responded">Mark as Responded</option>
                        <option value="delete">Delete</option>
                    </select>
                    <button type="button" 
                            id="applyBulkAction"
                            class="inline-flex items-center gap-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 py-2 rounded-lg 
                                   hover:from-blue-600 hover:to-blue-700 active:scale-[0.98] transition-all shadow-sm hover:shadow 
                                   disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:from-blue-500 disabled:hover:to-blue-600 text-sm"
                            disabled>
                        Apply
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Contacts Table -->
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-100 dark:border-gray-700/50 shadow-sm overflow-hidden flex-1 flex flex-col">
        <div class="px-5 py-4 border-b border-gray-100 dark:border-gray-700">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <h2 class="font-semibold text-gray-900 dark:text-white">All Contact Messages</h2>
                <div class="text-sm text-gray-500 dark:text-gray-400">
                    Showing {{ $contacts->firstItem() ?? 0 }}-{{ $contacts->lastItem() ?? 0 }} of {{ $contacts->total() }}
                </div>
            </div>
        </div>
        
        <div class="flex-1 overflow-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider w-10">
                            <input type="checkbox" id="selectAll" class="rounded border-gray-300 text-blue-500 focus:ring-blue-500">
                        </th>
                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                            Contact
                        </th>
                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                            Message
                        </th>
                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                            Status
                        </th>
                        <th class="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider w-32">
                            Actions
                        </th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    @forelse($contacts as $contact)
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors {{ $contact->status == 'new' ? 'bg-blue-50/50 dark:bg-blue-900/10' : '' }}">
                            <td class="px-5 py-4">
                                <input type="checkbox" 
                                       name="contacts[]" 
                                       value="{{ $contact->id }}"
                                       class="contact-checkbox rounded border-gray-300 text-blue-500 focus:ring-blue-500">
                            </td>
                            
                            <!-- Contact Column -->
                            <td class="px-5 py-4">
                                <div class="flex items-center gap-3">
                                    <div class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center text-white text-sm">
                                        {{ strtoupper(substr($contact->name, 0, 1)) }}
                                    </div>
                                    <div class="min-w-0 flex-1">
                                        <p class="text-sm font-medium text-gray-900 dark:text-white truncate">
                                            {{ $contact->name }}
                                        </p>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 truncate">
                                            {{ $contact->email }}
                                        </p>
                                        @if($contact->phone)
                                            <p class="text-xs text-gray-500 dark:text-gray-400 truncate">
                                                {{ $contact->phone }}
                                            </p>
                                        @endif
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Message Column -->
                            <td class="px-5 py-4">
                                <p class="text-sm text-gray-900 dark:text-white max-w-xs truncate">
                                    {{ Str::limit($contact->message, 80) }}
                                </p>
                                @if($contact->service)
                                    <span class="inline-block mt-1 px-2 py-1 text-xs bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded">
                                        {{ $contact->service }}
                                    </span>
                                @endif
                            </td>
                            
                            <!-- Status Column -->
                            <td class="px-5 py-4">
                                @php
                                    $statusConfig = [
                                        'new' => [
                                            'color' => 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300',
                                            'icon' => 'fa-envelope'
                                        ],
                                        'read' => [
                                            'color' => 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300',
                                            'icon' => 'fa-envelope-open'
                                        ],
                                        'responded' => [
                                            'color' => 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300',
                                            'icon' => 'fa-reply'
                                        ],
                                        'archived' => [
                                            'color' => 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300',
                                            'icon' => 'fa-archive'
                                        ]
                                    ];
                                    $config = $statusConfig[$contact->status] ?? [
                                        'color' => 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
                                        'icon' => 'fa-question-circle'
                                    ];
                                @endphp
                                <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium {{ $config['color'] }}">
                                    <i class="fas {{ $config['icon'] }} text-xs"></i>
                                    {{ ucfirst($contact->status) }}
                                </span>
                            </td>
                            
                            <!-- Actions Column -->
                            <td class="px-5 py-4">
                                <div class="flex items-center gap-2">
                                    <a href="{{ route('admin.contacts.show', $contact) }}" 
                                       class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 
                                              hover:bg-blue-100 dark:hover:bg-blue-900/30 active:scale-[0.95] transition-all"
                                       title="View Message">
                                        <i class="fas fa-eye text-xs"></i>
                                    </a>
                                    
                                    <button onclick="openDeleteModal('{{ $contact->id }}', '{{ $contact->name }}')"
                                            class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 
                                                   hover:bg-red-100 dark:hover:bg-red-900/30 active:scale-[0.95] transition-all"
                                            title="Delete Contact">
                                        <i class="fas fa-trash text-xs"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="5" class="px-5 py-12">
                                <div class="flex flex-col items-center justify-center text-gray-400 dark:text-gray-500">
                                    <div class="w-16 h-16 rounded-full bg-gradient-to-r from-blue-500 to-blue-600 flex items-center justify-center mb-4">
                                        <i class="fas fa-envelope text-white text-xl"></i>
                                    </div>
                                    <p class="text-lg font-medium text-gray-500 dark:text-gray-400 mb-2">No contact messages found</p>
                                    <p class="text-sm text-gray-400 dark:text-gray-500">All contact messages will appear here</p>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        @if($contacts->hasPages())
            <div class="px-5 py-4 border-t border-gray-100 dark:border-gray-700">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                        Showing {{ $contacts->firstItem() }} to {{ $contacts->lastItem() }} of {{ $contacts->total() }} results
                    </div>
                    <div class="flex items-center gap-2">
                        {{ $contacts->links() }}
                    </div>
                </div>
            </div>
        @endif
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="fixed inset-0 bg-black/50 dark:bg-black/70 flex items-center justify-center p-4 z-50 hidden">
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-md w-full transform transition-all duration-300 scale-95 opacity-0"
         id="modalContent">
        <!-- Modal Header -->
        <div class="p-6 border-b border-gray-200 dark:border-gray-700">
            <div class="flex items-center gap-3">
                <div class="w-12 h-12 rounded-full bg-red-50 dark:bg-red-900/20 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-red-500 dark:text-red-400 text-lg"></i>
                </div>
                <div class="min-w-0 flex-1">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-white">Confirm Deletion</h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">This action cannot be undone</p>
                </div>
            </div>
        </div>

        <!-- Modal Body -->
        <div class="p-6">
            <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-4">
                <div class="flex items-start gap-3">
                    <i class="fas fa-info-circle text-red-500 dark:text-red-400 mt-0.5"></i>
                    <div class="min-w-0 flex-1">
                        <p class="text-sm font-medium text-red-800 dark:text-red-300">Warning: Contact Deletion</p>
                        <p class="text-xs text-red-600 dark:text-red-400 mt-1">
                            This will permanently delete the contact message and all associated data.
                        </p>
                    </div>
                </div>
            </div>

            <div class="space-y-3">
                <div class="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
                    <span class="text-sm font-medium text-gray-500 dark:text-gray-400">Contact:</span>
                    <span class="text-sm font-semibold text-gray-900 dark:text-white" id="modalContactName"></span>
                </div>
                <div class="flex justify-between items-center py-2">
                    <span class="text-sm font-medium text-gray-500 dark:text-gray-400">Date:</span>
                    <span class="text-sm text-gray-900 dark:text-white" id="modalContactDate"></span>
                </div>
            </div>
        </div>

        <!-- Modal Footer -->
        <div class="p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 rounded-b-xl">
            <div class="flex gap-3 justify-end">
                <button type="button" 
                        onclick="closeDeleteModal()"
                        class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 
                               border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 
                               focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors duration-200">
                    Cancel
                </button>
                <form id="deleteForm" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" 
                            class="px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-red-500 to-red-600 
                                   hover:from-red-600 hover:to-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 
                                   focus:ring-red-500 rounded-lg shadow-sm transition-all duration-200 transform hover:scale-105">
                        <i class="fas fa-trash mr-2"></i>
                        Delete Message
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Action Confirmation Modal -->
<div id="bulkModal" class="fixed inset-0 bg-black/50 dark:bg-black/70 flex items-center justify-center p-4 z-50 hidden">
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-md w-full transform transition-all duration-300 scale-95 opacity-0"
         id="bulkModalContent">
        <div class="p-6">
            <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">Confirm Bulk Action</h3>
            <p class="text-gray-600 dark:text-gray-300 mb-6" id="bulkActionText"></p>
            <form id="bulkActionForm" method="POST" action="{{ route('admin.contacts.bulk-action') }}">
                @csrf
                <div id="selectedContactsInput"></div>
                <input type="hidden" name="action" id="bulkActionType">
                <div class="flex gap-3 justify-end">
                    <button type="button" 
                            onclick="closeBulkModal()"
                            class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 
                                   border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 
                                   transition-colors">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-500 to-blue-600 
                                   hover:from-blue-600 hover:to-blue-700 rounded-lg shadow-sm transition-all duration-200 transform hover:scale-105">
                        <i class="fas fa-check mr-2"></i>
                        Confirm
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    .dark .bg-gray-700 {
        background-color: rgba(55, 65, 81, 0.5);
    }
    
    table {
        border-collapse: separate;
        border-spacing: 0;
    }
    
    thead th {
        position: sticky;
        top: 0;
        z-index: 10;
    }
    
    tbody tr:last-child td {
        border-bottom: none;
    }
    
    /* Smooth transitions for modals */
    #deleteModal, #bulkModal {
        backdrop-filter: blur(4px);
    }
    
    #modalContent, #bulkModalContent {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
</style>

<script>
    let deleteModalContactId = null;

    // Delete Modal Functions
    function openDeleteModal(contactId, contactName) {
        deleteModalContactId = contactId;
        
        // Set modal content
        document.getElementById('modalContactName').textContent = contactName;
        document.getElementById('modalContactDate').textContent = new Date().toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });

        // Set delete form action
        const deleteForm = document.getElementById('deleteForm');
        deleteForm.action = `/admin/panel/contacts/${contactId}`;

        // Show modal with animation
        const modal = document.getElementById('deleteModal');
        const modalContent = document.getElementById('modalContent');
        
        modal.classList.remove('hidden');
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    }

    function closeDeleteModal() {
        const modal = document.getElementById('deleteModal');
        const modalContent = document.getElementById('modalContent');
        
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');
        
        setTimeout(() => {
            modal.classList.add('hidden');
            deleteModalContactId = null;
        }, 300);
    }

    // Bulk Actions Modal Functions
    function openBulkModal(action) {
        const modal = document.getElementById('bulkModal');
        const modalContent = document.getElementById('bulkModalContent');
        const actionText = document.getElementById('bulkActionText');
        const actionType = document.getElementById('bulkActionType');
        const selectedContactsInput = document.getElementById('selectedContactsInput');
        
        const selectedContacts = getSelectedContacts();
        if (selectedContacts.length === 0) {
            alert('Please select at least one contact.');
            return;
        }
        
        let actionMessage = '';
        switch(action) {
            case 'mark_read':
                actionMessage = `Mark ${selectedContacts.length} contact(s) as read?`;
                break;
            case 'mark_responded':
                actionMessage = `Mark ${selectedContacts.length} contact(s) as responded?`;
                break;
            case 'delete':
                actionMessage = `Delete ${selectedContacts.length} contact(s)?`;
                break;
        }
        
        actionText.textContent = actionMessage;
        actionType.value = action;
        
        // Add selected contacts as hidden inputs
        selectedContactsInput.innerHTML = '';
        selectedContacts.forEach(contactId => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'contacts[]';
            input.value = contactId;
            selectedContactsInput.appendChild(input);
        });
        
        modal.classList.remove('hidden');
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    }

    function closeBulkModal() {
        const modal = document.getElementById('bulkModal');
        const modalContent = document.getElementById('bulkModalContent');
        
        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');
        
        setTimeout(() => {
            modal.classList.add('hidden');
        }, 300);
    }

    // Helper Functions
    function getSelectedContacts() {
        const checkboxes = document.querySelectorAll('.contact-checkbox:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    function updateBulkActionButton() {
        const selectedCount = getSelectedContacts().length;
        const applyBulkActionBtn = document.getElementById('applyBulkAction');
        
        if (selectedCount > 0) {
            applyBulkActionBtn.disabled = false;
            applyBulkActionBtn.textContent = `Apply (${selectedCount})`;
        } else {
            applyBulkActionBtn.disabled = true;
            applyBulkActionBtn.textContent = 'Apply';
        }
    }

    function updateSelectAllCheckbox() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const contactCheckboxes = document.querySelectorAll('.contact-checkbox');
        const checkedCount = getSelectedContacts().length;
        
        if (checkedCount === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        } else if (checkedCount === contactCheckboxes.length) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        }
    }

    // Event Listeners
    document.addEventListener('DOMContentLoaded', function() {
        // Select All functionality
        const selectAllCheckbox = document.getElementById('selectAll');
        const contactCheckboxes = document.querySelectorAll('.contact-checkbox');
        
        selectAllCheckbox?.addEventListener('change', function() {
            contactCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            updateBulkActionButton();
        });

        // Individual checkbox change
        contactCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateBulkActionButton();
                updateSelectAllCheckbox();
            });
        });

        // Bulk action button
        const bulkActionSelect = document.getElementById('bulkAction');
        const applyBulkActionBtn = document.getElementById('applyBulkAction');
        
        bulkActionSelect?.addEventListener('change', function() {
            applyBulkActionBtn.disabled = this.value === '';
        });

        applyBulkActionBtn?.addEventListener('click', function() {
            const action = bulkActionSelect.value;
            if (action) {
                openBulkModal(action);
            }
        });

        // Close modals when clicking outside
        document.getElementById('deleteModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeDeleteModal();
            }
        });

        document.getElementById('bulkModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeBulkModal();
            }
        });

        // Close modals with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeDeleteModal();
                closeBulkModal();
            }
        });

        // Search functionality
        const searchInput = document.querySelector('input[type="text"]');
        if (searchInput) {
            searchInput.addEventListener('input', function(e) {
                const searchTerm = e.target.value.toLowerCase();
                const rows = document.querySelectorAll('tbody tr');
                
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    if (text.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
        }
        
        // Animate progress bars on load
        const progressBars = document.querySelectorAll('.h-1\\.5 > div');
        progressBars.forEach(bar => {
            const width = bar.style.width;
            bar.style.width = '0';
            setTimeout(() => {
                bar.style.width = width;
            }, 300);
        });
    });
</script>
@endsection