@extends('layouts.admin')

@section('title', 'Daftar Pesan Kontak')

@section('content')

    <!-- Notifikasi Modern -->
    <x-admin-notification />

    <!-- Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800 dark:text-white">Daftar Pesan Kontak</h1>
    </div>

    <!-- Filter Section -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 mb-6">
        <form method="GET" action="{{ route('admin.contacts.index') }}" id="filterForm"
            class="flex flex-col sm:flex-row items-end gap-3">
            <!-- Search Bar -->
            <div class="relative flex-1 w-full sm:w-auto">
                <input type="text" name="search" id="searchInput" value="{{ request('search') }}"
                    placeholder="Cari nama, email, pesan..." class="form-input-search" />
                <i
                    class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                @if (request('search'))
                    <button type="button" onclick="clearSearch()"
                        class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300">
                        <i class="fas fa-times"></i>
                    </button>
                @endif
            </div>

            <!-- Status Filter -->
            <div class="relative w-full sm:w-auto">
                <select name="status" id="statusFilter" onchange="submitFilter()" class="form-select">
                    <option value="">Semua Status</option>
                    <option value="unread" {{ request('status') == 'unread' ? 'selected' : '' }}>Belum Dibaca</option>
                    <option value="read" {{ request('status') == 'read' ? 'selected' : '' }}>Sudah Dibaca</option>
                </select>
                <i
                    class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
            </div>

            <!-- Bulk Actions -->
            <div class="relative w-full sm:w-auto">
                <select id="bulkAction" class="form-select">
                    <option value="">Bulk Actions</option>
                    <option value="mark-read">Tandai Dibaca</option>
                    <option value="mark-unread">Tandai Belum Dibaca</option>
                    <option value="delete">Hapus</option>
                </select>
                <i
                    class="fas fa-list absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                <i
                    class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
            </div>

            <!-- Action Buttons -->
            <div class="flex items-center gap-3 w-full sm:w-auto">
                <button type="button" onclick="executeBulkAction()" id="bulkActionBtn" disabled
                    class="action-btn-primary disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fas fa-check mr-2"></i>Execute
                </button>
                <a href="{{ route('admin.contacts.index') }}" class="action-btn-primary">
                    <i class="fas fa-refresh mr-2"></i>Refresh
                </a>
            </div>
        </form>
    </div>

    <!-- Active Filters Info -->
    @if (request()->hasAny(['search', 'status']))
        <div class="mb-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
            <div class="flex flex-wrap items-center gap-2">
                <span class="text-sm font-medium text-blue-800 dark:text-blue-200">Filter Aktif:</span>

                @if (request('search'))
                    <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-200">
                        <i class="fas fa-search mr-1"></i>
                        Pencarian: "{{ request('search') }}"
                        <button onclick="clearFilter('search')" class="ml-2 hover:text-blue-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif

                @if (request('status'))
                    <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-200">
                        <i class="fas fa-filter mr-1"></i>
                        Status: {{ request('status') == 'unread' ? 'Belum Dibaca' : 'Sudah Dibaca' }}
                        <button onclick="clearFilter('status')" class="ml-2 hover:text-green-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif

                <button onclick="clearAllFilters()"
                    class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-700 transition-colors">
                    <i class="fas fa-times-circle mr-1"></i>
                    Hapus Semua Filter
                </button>
            </div>
        </div>
    @endif

    <!-- Table Container -->
    <div
        class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden transition-colors duration-300">
        <div class="overflow-x-auto admin-table-wrapper">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="w-12 px-4 py-4 text-center">
                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll()"
                                class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                        </th>
                        <th
                            class="w-16 px-4 py-4 text-center text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            No
                        </th>
                        <th
                            class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            Nama</th>
                        <th
                            class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            Email</th>
                        <th
                            class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            Pesan</th>
                        <th
                            class="px-6 py-4 text-center text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            Status</th>
                        <th
                            class="px-6 py-4 text-center text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            Tanggal</th>
                        <th
                            class="px-6 py-4 text-center text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-200">
                            Aksi</th>
                    </tr>
                </thead>

                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    @forelse ($contacts as $contact)
                        <tr data-contact-id="{{ $contact->id }}" data-contact-nama="{{ $contact->nama }}"
                            data-contact-email="{{ $contact->email }}" data-contact-pesan="{{ $contact->pesan }}"
                            data-contact-tanggal="{{ $contact->created_at->format('d M Y H:i') }}"
                            class="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors duration-200">
                            <td class="px-4 py-4 text-center">
                                <input type="checkbox"
                                    class="contact-checkbox w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                                    value="{{ $contact->id }}" onchange="updateBulkActionButton()">
                            </td>
                            <td class="px-4 py-4 text-sm text-gray-900 dark:text-gray-100 text-center align-middle">
                                {{ $loop->iteration + $contacts->firstItem() - 1 }}
                            </td>

                            <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 font-medium align-middle">
                                {{ $contact->nama }}
                            </td>

                            <td
                                class="px-6 py-4 text-sm text-gray-600 dark:text-gray-400 align-middle break-words max-w-xs">
                                {{ $contact->email }}
                            </td>

                            <td
                                class="px-6 py-4 text-sm text-gray-700 dark:text-gray-300 align-middle break-words max-w-xs">
                                <span title="{{ $contact->pesan }}">
                                    {{ Str::limit($contact->pesan, 50) }}
                                </span>
                            </td>

                            <td class="px-6 py-4 text-center align-middle">
                                @if ($contact->is_read)
                                    <span
                                        class="inline-flex items-center px-3 py-1.5 text-xs font-semibold rounded-full bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        Dibaca
                                    </span>
                                @else
                                    <span
                                        class="inline-flex items-center px-3 py-1.5 text-xs font-semibold rounded-full bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200">
                                        <i class="fas fa-envelope mr-1"></i>
                                        Belum Dibaca
                                    </span>
                                @endif
                            </td>

                            <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 text-center align-middle">
                                {{ $contact->created_at->format('d M Y H:i') }}
                            </td>

                            <td class="px-6 py-4 text-center align-middle">
                                <div class="flex justify-center items-center space-x-2">
                                    <!-- Tombol Lihat Detail -->
                                    <button onclick="openContactModal({{ $contact->id }})" type="button"
                                        class="inline-flex items-center justify-center w-8 h-8 text-indigo-500 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900 rounded-lg transition-all duration-200"
                                        title="Lihat Detail">
                                        <i class="fas fa-eye text-sm"></i>
                                    </button>

                                    <!-- Tombol Reply (Email/WA/Phone) -->
                                    @if ($contact->email || $contact->phone)
                                        <button onclick="openReplyModal({{ $contact->id }})" type="button"
                                            class="inline-flex items-center justify-center w-8 h-8 text-blue-500 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900 rounded-lg transition-all duration-200"
                                            title="Reply Pesan (Email/WA/Phone)">
                                            <i class="fas fa-envelope text-sm"></i>
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" class="px-6 py-16 text-center">
                                <div class="flex flex-col items-center">
                                    <div
                                        class="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
                                        <i class="fas fa-inbox text-2xl text-gray-400 dark:text-gray-500"></i>
                                    </div>
                                    <p class="text-gray-500 dark:text-gray-400 text-lg font-medium">Belum ada pesan kontak
                                    </p>
                                    <p class="text-gray-400 dark:text-gray-500 text-sm mt-1">Pesan kontak akan muncul di
                                        sini</p>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pagination -->
    @if ($contacts->hasPages())
        <div class="mt-6 flex justify-center">
            {{ $contacts->onEachSide(1)->links() }}
        </div>
    @endif

    {{-- Modal Detail Pesan --}}
    <div id="contactModal"
        class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center z-[9999] transition-opacity duration-300">
        <div id="contactModalContent"
            class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-xl max-w-lg w-full mx-4 p-0 overflow-hidden max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
                            <i class="fas fa-envelope text-blue-600 dark:text-blue-400"></i>
                        </div>
                        <h2 class="text-xl font-bold text-gray-900 dark:text-white">Detail Pesan Kontak</h2>
                    </div>
                    <button onclick="closeContactModal()"
                        class="text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-200 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-times text-lg"></i>
                    </button>
                </div>

                <div id="contactDetails" class="space-y-4 mb-6">
                    <!-- Konten akan diisi via JS -->
                </div>

                <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button type="button" onclick="closeContactModal()"
                        class="px-6 py-2.5 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 duration-200 font-medium text-sm">
                        Tutup
                    </button>
                </div>
            </div>
        </div>
    </div>

    {{-- Modal Reply --}}
    <div id="replyModal"
        class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center z-[9999] transition-opacity duration-300">
        <div id="replyModalContent"
            class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-xl max-w-lg w-full mx-4 p-0 overflow-hidden max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-green-100 dark:bg-green-900 rounded-lg flex items-center justify-center">
                            <i class="fas fa-reply text-green-600 dark:text-green-400"></i>
                        </div>
                        <h2 class="text-xl font-bold text-gray-900 dark:text-white">Reply Pesan</h2>
                    </div>
                    <button onclick="closeReplyModal()"
                        class="text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-200 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-times text-lg"></i>
                    </button>
                </div>

                <form id="replyForm" class="space-y-4 mb-6">
                    @csrf
                    <input type="hidden" id="reply-contact-id" value="" />

                    <div>
                        <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Kepada</label>
                        <p id="replyTo"
                            class="text-gray-900 dark:text-gray-100 bg-gray-50 dark:bg-gray-700 rounded-lg px-3 py-2"></p>
                    </div>

                    <div>
                        <label for="replyMethod"
                            class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Metode Reply</label>
                        <div class="relative">
                            <select id="replyMethod" name="reply_method" required
                                class="w-full pl-10 pr-10 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white appearance-none">
                                <option value="">Pilih Metode Reply</option>
                                <option value="email">Email</option>
                                <option value="whatsapp">WhatsApp</option>
                                <option value="phone">Telepon</option>
                            </select>
                            <i id="replyMethodIcon"
                                class="fas fa-envelope absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                            <i
                                class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                        </div>
                    </div>

                    <div>
                        <label for="replySubject"
                            class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Subject (Subjek
                            Balasan)</label>
                        <input type="text" id="replySubject" name="subject"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                            placeholder="Contoh: Re: Pertanyaan Anda" required>
                    </div>
                    <div>
                        <label for="replyMessage"
                            class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Pesan Balasan</label>
                        <textarea id="replyMessage" name="message" rows="6"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                            placeholder="Tulis pesan balasan Anda di sini..." required></textarea>
                    </div>
                </form>

                <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button type="button" onclick="closeReplyModal()"
                        class="px-6 py-2.5 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 duration-200 font-medium text-sm">
                        Batal
                    </button>
                    <button type="button" id="kirimReplyBtn" onclick="sendReply()"
                        class="px-6 py-2.5 text-white bg-green-600 hover:bg-green-700 rounded-lg transition-colors duration-200 font-medium text-sm">
                        <i class="fas fa-paper-plane mr-2"></i>Kirim Reply
                    </button>
                </div>
            </div>
        </div>
    </div>

    <style>
        /* Modal Animation */
        #contactModal.show {
            display: flex;
            animation: fadeIn 0.3s ease-out;
        }

        #contactModal.hide {
            animation: fadeOut 0.3s ease-in;
        }

        #contactModalContent {
            animation: scaleIn 0.3s ease-out;
        }

        #contactModal.hide #contactModalContent {
            animation: scaleOut 0.3s ease-in;
        }

        #replyModal.show {
            display: flex;
            animation: fadeIn 0.3s ease-out;
        }

        #replyModal.hide {
            animation: fadeOut 0.3s ease-in;
        }

        #replyModalContent {
            animation: scaleIn 0.3s ease-out;
        }

        #replyModal.hide #replyModalContent {
            animation: scaleOut 0.3s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes fadeOut {
            from {
                opacity: 1;
            }

            to {
                opacity: 0;
            }
        }

        @keyframes scaleIn {
            from {
                transform: scale(0.95);
                opacity: 0;
            }

            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        @keyframes scaleOut {
            from {
                transform: scale(1);
                opacity: 1;
            }

            to {
                transform: scale(0.95);
                opacity: 0;
            }
        }

        /* Konsisten Style untuk form inputs */
        .form-input-search,
        .form-select {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            line-height: 1.5 !important;
            padding: 0 2.5rem 0 2.5rem !important;
            margin: 0 !important;
        }

        .form-input-search {
            width: 100%;
            padding-left: 2.5rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .dark .form-input-search {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }

        .form-input-search:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
            border-color: rgb(59 130 246);
        }

        .form-select {
            width: 100%;
            padding-left: 2.5rem !important;
            padding-right: 2rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
            background-position: right 0.5rem center;
            background-repeat: no-repeat;
            background-size: 1.5em 1.5em;
            transition: all 0.2s;
        }

        .dark .form-select {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }

        .form-select:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
            border-color: rgb(59 130 246);
        }

        .action-btn-primary {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            padding: 0 1rem !important;
            margin: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            font-weight: 500;
            border-radius: 0.5rem;
            transition: all 0.2s;
            white-space: nowrap;
            background-color: rgb(59 130 246);
            color: white;
            text-decoration: none;
            border: none;
            cursor: pointer;
        }

        .action-btn-primary:hover {
            background-color: rgb(37 99 235);
        }

        .action-btn-primary:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .dark .action-btn-primary {
            background-color: rgb(59 130 246);
        }

        .dark .action-btn-primary:hover {
            background-color: rgb(37 99 235);
        }
    </style>

    <script>
        let currentContactId = null;

        function openContactModal(id) {
            currentContactId = id;
            const row = document.querySelector(`tr[data-contact-id="${id}"]`);
            if (row) {
                const nama = row.dataset.contactNama;
                const email = row.dataset.contactEmail;
                const pesan = row.dataset.contactPesan;
                const tanggal = row.dataset.contactTanggal;

                document.getElementById('contactDetails').innerHTML = `
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Nama</label>
                            <p class="text-gray-900 dark:text-gray-100 bg-gray-50 dark:bg-gray-700 rounded-lg px-3 py-2">${nama}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Email</label>
                            <p class="text-gray-900 dark:text-gray-100 bg-gray-50 dark:bg-gray-700 rounded-lg px-3 py-2">${email}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Tanggal</label>
                            <p class="text-gray-900 dark:text-gray-100 bg-gray-50 dark:bg-gray-700 rounded-lg px-3 py-2">${tanggal}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Pesan</label>
                            <textarea class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none bg-white dark:bg-gray-700 text-gray-900 dark:text-white" rows="6" readonly>${pesan}</textarea>
                        </div>
                    </div>
                `;

                const modal = document.getElementById('contactModal');
                if (modal) {
                    modal.classList.remove('hidden', 'hide');
                    modal.classList.add('show');
                    document.body.style.overflow = 'hidden';
                }
            }
        }

        function closeContactModal() {
            const modal = document.getElementById('contactModal');
            if (modal) {
                modal.classList.remove('show');
                modal.classList.add('hide');
                setTimeout(() => {
                    modal.classList.add('hidden');
                    modal.classList.remove('hide');
                    document.body.style.overflow = 'auto';
                }, 300);
            }
        }

        function openReplyModal(id) {
            currentContactId = id;
            const row = document.querySelector(`tr[data-contact-id="${id}"]`);
            if (row) {
                const nama = row.dataset.contactNama;
                const email = row.dataset.contactEmail;

                // Set contact ID for the form
                document.getElementById('reply-contact-id').value = id;

                // Set recipient info
                document.getElementById('replyTo').textContent = `${nama} (${email})`;

                // Set default subject
                document.getElementById('replySubject').value = `Re: Kontak dari ${nama}`;

                // Reset form values
                document.getElementById('replyMessage').value = '';
                document.getElementById('replyMethod').value = '';

                // Reset icon
                updateReplyMethodIcon();

                // Remove existing event listener and add new one
                const methodSelect = document.getElementById('replyMethod');
                const newMethodSelect = methodSelect.cloneNode(true);
                methodSelect.parentNode.replaceChild(newMethodSelect, methodSelect);
                newMethodSelect.addEventListener('change', updateReplyMethodIcon);

                // Show modal
                const modal = document.getElementById('replyModal');
                if (modal) {
                    modal.classList.remove('hidden', 'hide');
                    modal.classList.add('show');
                    document.body.style.overflow = 'hidden';
                }
            }
        }

        function closeReplyModal() {
            const modal = document.getElementById('replyModal');
            if (modal) {
                modal.classList.remove('show');
                modal.classList.add('hide');
                setTimeout(() => {
                    modal.classList.add('hidden');
                    modal.classList.remove('hide');
                    document.body.style.overflow = 'auto';
                }, 300);
            }
        }

        function updateReplyMethodIcon() {
            const method = document.getElementById('replyMethod').value;
            const iconElement = document.getElementById('replyMethodIcon');

            if (iconElement) {
                // Remove all icon classes
                iconElement.className =
                    'absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none';

                // Add appropriate icon based on method
                if (method === 'email') {
                    iconElement.classList.add('fas', 'fa-envelope');
                } else if (method === 'whatsapp') {
                    iconElement.classList.add('fab', 'fa-whatsapp');
                } else if (method === 'phone') {
                    iconElement.classList.add('fas', 'fa-phone');
                } else {
                    iconElement.classList.add('fas', 'fa-envelope');
                }
            }
        }

        function sendReply() {
            const subject = document.getElementById('replySubject').value;
            const message = document.getElementById('replyMessage').value;
            const replyMethod = document.getElementById('replyMethod').value;
            const contactId = currentContactId || document.getElementById('reply-contact-id').value;

            if (!subject || !message || !replyMethod) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Semua field harus diisi!',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            if (!contactId) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Contact ID tidak ditemukan. Silakan tutup dan buka modal lagi.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            // Konfirmasi sebelum kirim
            Swal.fire({
                title: 'Konfirmasi Reply',
                html: `
                    <div class="text-left">
                        <p><strong>Metode:</strong> ${replyMethod === 'email' ? '📧 Email' : replyMethod === 'whatsapp' ? '📱 WhatsApp' : '📞 Telepon'}</p>
                        <p><strong>Subject:</strong> ${subject}</p>
                        <p><strong>Pesan:</strong> ${message.substring(0, 100)}${message.length > 100 ? '...' : ''}</p>
                    </div>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#10b981',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Ya, Kirim',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Kirim AJAX request
                    fetch(`/admin/contacts/${contactId}/reply`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute(
                                    'content')
                            },
                            body: JSON.stringify({
                                subject: subject,
                                message: message,
                                reply_method: replyMethod
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                if (data.whatsapp_link) {
                                    Swal.fire({
                                        title: 'Berhasil!',
                                        text: data.message,
                                        icon: 'success',
                                        showCancelButton: true,
                                        confirmButtonText: 'Buka WhatsApp',
                                        cancelButtonText: 'Tutup'
                                    }).then((result) => {
                                        if (result.isConfirmed) {
                                            window.open(data.whatsapp_link, '_blank');
                                        }
                                        closeReplyModal();
                                    });
                                } else if (data.phone_link) {
                                    Swal.fire({
                                        title: 'Berhasil!',
                                        text: data.message,
                                        icon: 'success',
                                        showCancelButton: true,
                                        confirmButtonText: 'Telepon',
                                        cancelButtonText: 'Tutup'
                                    }).then((result) => {
                                        if (result.isConfirmed) {
                                            window.location.href = data.phone_link;
                                        }
                                        closeReplyModal();
                                    });
                                } else {
                                    Swal.fire({
                                        title: 'Berhasil!',
                                        text: data.message,
                                        icon: 'success',
                                        confirmButtonText: 'OK'
                                    });
                                    closeReplyModal();
                                }
                            } else {
                                Swal.fire({
                                    title: 'Error!',
                                    text: data.message,
                                    icon: 'error',
                                    confirmButtonText: 'OK'
                                });
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            Swal.fire({
                                title: 'Error!',
                                text: 'Terjadi kesalahan saat mengirim reply',
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                        });
                }
            });
        }

        // Submit filter form
        function submitFilter() {
            const params = new URLSearchParams();

            // Ambil nilai dari setiap input/select
            const search = document.getElementById('searchInput')?.value?.trim() || '';
            const status = document.getElementById('statusFilter')?.value || '';

            // Hanya tambahkan parameter yang memiliki nilai
            if (search) {
                params.append('search', search);
            }
            if (status) {
                params.append('status', status);
            }

            // Redirect dengan parameter yang bersih
            const url = '{{ route('admin.contacts.index') }}' + (params.toString() ? '?' + params.toString() : '');
            window.location.href = url;
        }

        // Clear search only
        function clearSearch() {
            const url = new URL(window.location);
            url.searchParams.delete('search');
            window.location.href = url.toString();
        }

        // Clear individual filter
        function clearFilter(filterName) {
            const url = new URL(window.location);
            url.searchParams.delete(filterName);
            window.location.href = url.toString();
        }

        // Clear all filters
        function clearAllFilters() {
            window.location.href = '{{ route('admin.contacts.index') }}';
        }

        // Event listener for Enter key on search input
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        submitFilter();
                    }
                });
            }
        });

        // Bulk Actions Functions
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.contact-checkbox');

            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });

            updateBulkActionButton();
        }

        function updateBulkActionButton() {
            const checkboxes = document.querySelectorAll('.contact-checkbox:checked');
            const bulkActionBtn = document.getElementById('bulkActionBtn');

            if (checkboxes.length > 0) {
                bulkActionBtn.disabled = false;
                bulkActionBtn.classList.remove('disabled:bg-gray-400', 'disabled:cursor-not-allowed');
                bulkActionBtn.classList.add('bg-blue-600', 'hover:bg-blue-700');
            } else {
                bulkActionBtn.disabled = true;
                bulkActionBtn.classList.add('disabled:bg-gray-400', 'disabled:cursor-not-allowed');
                bulkActionBtn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
            }
        }

        function executeBulkAction() {
            const checkboxes = document.querySelectorAll('.contact-checkbox:checked');
            const bulkAction = document.getElementById('bulkAction').value;

            if (checkboxes.length === 0) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Pilih minimal satu item!',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            if (!bulkAction) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Pilih aksi yang akan dilakukan!',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            const contactIds = Array.from(checkboxes).map(cb => cb.value);

            let confirmText = '';
            let confirmIcon = 'question';

            switch (bulkAction) {
                case 'mark-read':
                    confirmText = `Tandai ${contactIds.length} pesan sebagai dibaca?`;
                    confirmIcon = 'question';
                    break;
                case 'mark-unread':
                    confirmText = `Tandai ${contactIds.length} pesan sebagai belum dibaca?`;
                    confirmIcon = 'question';
                    break;
                case 'delete':
                    confirmText = `Hapus ${contactIds.length} pesan secara permanen?`;
                    confirmIcon = 'warning';
                    break;
            }

            Swal.fire({
                title: 'Konfirmasi',
                text: confirmText,
                icon: confirmIcon,
                showCancelButton: true,
                confirmButtonColor: bulkAction === 'delete' ? '#ef4444' : '#10b981',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Ya, Lanjutkan',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    performBulkAction(bulkAction, contactIds);
                }
            });
        }

        function performBulkAction(action, contactIds) {
            let url;
            switch (action) {
                case 'mark-read':
                    url = '{{ route('admin.contacts.bulk-mark-read') }}';
                    break;
                case 'mark-unread':
                    url = '{{ route('admin.contacts.bulk-mark-unread') }}';
                    break;
                case 'delete':
                    url = '{{ route('admin.contacts.bulk-delete') }}';
                    break;
                default:
                    Swal.fire({
                        title: 'Error!',
                        text: 'Aksi tidak valid!',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    return;
            }

            fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        contact_ids: contactIds
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            title: 'Berhasil!',
                            text: data.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        });
                        // Reload halaman untuk update data
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: data.message,
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        title: 'Error!',
                        text: 'Terjadi kesalahan saat memproses aksi',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                });
        }

        // Tutup modal jika klik di luar
        document.addEventListener('click', function(e) {
            const contactModal = document.getElementById('contactModal');
            const replyModal = document.getElementById('replyModal');

            if (e.target === contactModal) {
                closeContactModal();
            }
            if (e.target === replyModal) {
                closeReplyModal();
            }
        });

        // Keyboard ESC for modal
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const contactModal = document.getElementById('contactModal');
                const replyModal = document.getElementById('replyModal');

                if (contactModal && !contactModal.classList.contains('hidden')) {
                    closeContactModal();
                }
                if (replyModal && !replyModal.classList.contains('hidden')) {
                    closeReplyModal();
                }
            }
        });
    </script>
@endsection
