@extends('admin.layouts.app')

@section('title', 'FMP CORE - Account – Lawyer List')

@section('breadcrumbs')
    <i class="fa-solid fa-chevron-right mx-3 text-[8px]"></i>
    <span class="text-slate-900">Account Lawyer Mapping</span>
@endsection

@push('styles')
<style>


    .pill-red {
   
}
        /* .pill {
            border-radius: 24px;
            padding: 4px 12px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            white-space: nowrap;
        } */

    .pill-green {
        background: #dcfce7;
        color: #15803d;
         border-radius: 999px;
        padding: 4px 10px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }

    .pill-red {
         border-radius: 999px;
        padding: 4px 10px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        background: #fee2e2;
        color: #b91c1c;
    .pill {
        border-radius: 24px; padding: 4px 12px; font-size: 11px; font-weight: 700;
        text-transform: uppercase; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap;
    }
    .pill-green { background: #dcfce7; color: #15803d; }
    .pill-red { background: #fee2e2; color: #b91c1c; }
    .grid-view { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.25rem; }
    .card-badge {
        display: inline-flex; align-items: center; gap: 5px; padding: 6px 14px;
        background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 10px; font-size: 11px;
        font-weight: 600; color: #15803d;
    }
    .lawyer-avatars { display: flex; align-items: center; }
    .lawyer-avatars .avatar {
        width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center;
        justify-content: center; font-size: 10px; font-weight: 800; color: #fff;
        border: 2px solid #fff; margin-left: -8px; box-shadow: 0 1px 4px rgba(0,0,0,0.12);
    }
    .lawyer-avatars .avatar:first-child { margin-left: 0; }
    .lawyer-tag {
        display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 8px;
        background: #e6f7f6; color: #0f766e; font-size: 10px; font-weight: 700; margin: 2px;
    }

    /* Delete modal */
    .modal-overlay {
        position: fixed; inset: 0; z-index: 500; display: none; align-items: center; justify-content: center; padding: 16px;
    }
    .modal-overlay.active { display: flex; }
    .modal-backdrop { position: absolute; inset: 0; background: rgba(15,23,42,0.4); backdrop-filter: blur(4px); }
    .modal-card {
        position: relative; background: #fff; padding: 32px; border-radius: 2rem;
        box-shadow: 0 25px 60px rgba(0,0,0,0.2); max-width: 400px; width: 100%; text-align: center;
    }

    /* Edit modal fields */
    .edit-label { display:block;font-size:12px;font-weight:700;color:#475569;margin-bottom:5px;text-transform:uppercase;letter-spacing:0.04em; }
    .edit-input {
        width:100%;border-radius:10px;border:1.5px solid #e2e8f0;padding:9px 12px;font-size:13px;outline:none;
        background:#fff;transition:border-color 0.15s,box-shadow 0.15s;font-family:'Plus Jakarta Sans',sans-serif;
    }
    .edit-input:focus { border-color:#00ada8;box-shadow:0 0 0 3px rgba(0,173,168,0.12); }
    .edit-lawyer-row {
        display:flex;align-items:center;justify-content:space-between;padding:10px 14px;background:#fff;
        border:1.5px solid #e2e8f0;border-radius:12px;margin-bottom:8px;transition:all 0.15s;
    }
    .edit-lawyer-row:hover { border-color:#00ada8; }
    .edit-lawyer-remove {
        width:28px;height:28px;border-radius:8px;background:#fee2e2;color:#b91c1c;border:none;
        cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:12px;flex-shrink:0;transition:all 0.15s;
    }
    .edit-lawyer-remove:hover { background:#fecaca;transform:scale(1.1); }
    .edit-sug-item { padding:8px 12px;cursor:pointer;border-bottom:1px solid #f1f5f9;font-size:12px;transition:background 0.1s; }
    .edit-sug-item:hover { background:#f0fdfb; }
    @media (max-width: 768px) { .grid-view { grid-template-columns: minmax(0, 1fr); } }
</style>
@endpush

@section('content')
    <div class="workspace-console min-h-full p-8 shadow-sm flex flex-col">
        <!-- Top Bar -->
        <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-8">
            <div class="flex items-center gap-3 flex-1">
                <div class="relative w-full max-w-xs">
                    <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                    <input id="searchInput" type="text" placeholder="Search by account or lawyer..." oninput="render()"
                        class="w-full pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-2xl text-xs outline-none focus:ring-1 focus:ring-[#00ada8]">
                </div>
            </div>
            <div class="flex items-center gap-3">
                <div class="flex bg-slate-100 p-1.5 rounded-xl">
                    <button onclick="setView('grid')" id="gridBtn" class="w-9 h-9 flex items-center justify-center rounded-lg text-slate-400 hover:text-[#00ada8]"><i class="fa-solid fa-table-cells-large"></i></button>
                    <button onclick="setView('list')" id="listBtn" class="w-9 h-9 flex items-center justify-center rounded-lg bg-white shadow-sm text-[#00ada8]"><i class="fa-solid fa-list"></i></button>
                </div>
                @if($perms['add'])
                <button onclick="window.location.href='{{ route('admin.account-lawyer.search-account') }}'" class="bg-[#00ada8] text-white px-5 py-2.5 rounded-xl text-xs font-extrabold shadow-lg shadow-[#00ada8]/20 hover:scale-105 transition-all whitespace-nowrap">
                    <i class="fa-solid fa-plus mr-2"></i> ADD MAPPING
                </button>
                @endif
            </div>
        </div>

        @if(!$perms['view'])
        <div class="flex-1 flex items-center justify-center py-20">
            <div class="text-center">
                <div class="w-20 h-20 bg-red-50 text-red-400 rounded-3xl flex items-center justify-center mx-auto mb-6">
                    <i class="fa-solid fa-lock text-3xl"></i>
                </div>
                <h3 class="text-lg font-extrabold text-slate-800 mb-2">Access Restricted</h3>
                <p class="text-sm text-slate-400 max-w-xs mx-auto">You don't have permission to view Account Lawyer Mappings. Contact your administrator.</p>
            </div>
        </div>
        @else
        <!-- Content Wrapper -->
        <div id="contentWrapper" class="flex-1">
            <div id="gridContainer" class="grid-view" style="display:none"></div>
            <div id="listContainer" class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-slate-100">
                            <th class="text-left py-3 px-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">Account</th>
                            <th class="text-left py-3 px-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">Lawyer(s)</th>
                            <th class="text-left py-3 px-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">Last Updated</th>
                            <th class="text-left py-3 px-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">Status</th>
                            <th class="text-center py-3 px-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="listBody" class="divide-y divide-slate-50"></tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <div class="mt-6 pt-6 border-t border-slate-100 flex items-center justify-between">
            <p id="showingText" class="text-[11px] font-bold text-slate-400 uppercase"></p>
            <div class="flex gap-2" id="pagination"></div>
        </div>
        @endif
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal-overlay">
        <div class="modal-backdrop" onclick="closeEditModal()"></div>
        <div class="modal-card" style="max-width:820px;text-align:left;padding:0;border-radius:1.75rem;overflow:hidden;">
            <!-- Header -->
            <div style="background:linear-gradient(135deg,#00ada8 0%,#007d79 100%);padding:18px 28px;display:flex;align-items:center;justify-content:space-between;">
                <div>
                    <h3 style="font-size:15px;font-weight:800;color:#fff;">Edit Account Mapping</h3>
                    <p id="editAccountLabel" style="font-size:11px;color:rgba(255,255,255,0.7);margin-top:2px;"></p>
                </div>
                <button onclick="closeEditModal()" style="width:32px;height:32px;border-radius:50%;background:rgba(255,255,255,0.2);color:#fff;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            <!-- Body -->
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:0;">
                <!-- Left: Form fields -->
                <div style="padding:24px 28px;border-right:1px solid #e2e8f0;max-height:480px;overflow-y:auto;" class="scroll-custom">
                    <div style="margin-bottom:14px;">
                        <label class="edit-label">Assign Date *</label>
                        <input type="date" id="editAssignDate" class="edit-input" required />
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="edit-label">Case Submitted Date *</label>
                        <input type="date" id="editSubmittedDate" class="edit-input" required />
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="edit-label">Case Registration Via *</label>
                        <input type="text" id="editRegistrationVia" class="edit-input" required />
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="edit-label">Court Fee *</label>
                        <input type="number" step="0.001" id="editCourtFee" class="edit-input" required />
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="edit-label">Case Filed Date *</label>
                        <input type="date" id="editCaseFiledDate" class="edit-input" required />
                    </div>
                    <div style="margin-bottom:14px;">
                        <label class="edit-label">Internal Remarks</label>
                        <textarea id="editRemarks" rows="2" class="edit-input" style="resize:none;border-radius:12px;"></textarea>
                    </div>
                </div>
                <!-- Right: Lawyer management -->
                <div style="padding:24px 28px;max-height:480px;overflow-y:auto;background:#f8fafc;" class="scroll-custom">
                    <label class="edit-label">Search Lawyer</label>
                    <div style="position:relative;margin-bottom:12px;">
                        <i class="fa-solid fa-magnifying-glass" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#94a3b8;font-size:11px;pointer-events:none;"></i>
                        <input type="text" id="editLawyerSearch" class="edit-input" style="padding-left:32px;margin-bottom:0;" placeholder="Type code or name..." autocomplete="off" />
                    </div>
                    <div id="editSuggestions" style="border-radius:12px;border:1.5px solid #e2e8f0;background:#fff;box-shadow:0 8px 24px rgba(15,23,42,0.10);max-height:160px;overflow-y:auto;display:none;margin-bottom:12px;"></div>
                    <div id="editAlertError" style="background:#fef2f2;border:1px solid #fecaca;border-radius:10px;padding:10px 14px;color:#b91c1c;font-size:11px;font-weight:500;display:none;margin-bottom:12px;">
                        <i class="fa-solid fa-circle-exclamation mr-1"></i><span id="editAlertMsg"></span>
                    </div>

                    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
                        <label class="edit-label" style="margin-bottom:0;">Lawyers (<span id="editLawyerCount">0</span>)</label>
                    </div>
                    <div id="editLawyersList"></div>
                </div>
            </div>
            <!-- Footer -->
            <div style="padding:16px 28px;border-top:1px solid #e2e8f0;display:flex;justify-content:flex-end;gap:12px;">
                <button onclick="closeEditModal()" style="padding:10px 24px;border-radius:999px;border:2px solid #e2e8f0;background:#fff;color:#64748b;font-size:13px;font-weight:500;cursor:pointer;">Cancel</button>
                <button id="btnEditSave" onclick="saveEdit()" style="padding:10px 24px;border-radius:999px;border:none;background:radial-gradient(circle at top left,#00ada8 0%,#007d79 100%);color:#fff;font-size:13px;font-weight:600;cursor:pointer;box-shadow:0 8px 20px rgba(0,173,168,0.3);">Submit</button>
            </div>
        </div>
    </div>

    <!-- Delete Modal -->
    <div id="deleteModal" class="modal-overlay">
        <div class="modal-backdrop" onclick="closeDeleteModal()"></div>
        <div class="modal-card">
            <div class="w-16 h-16 bg-red-50 text-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4">
                <i class="fa-solid fa-trash-can text-2xl"></i>
            </div>
            <h3 class="font-extrabold text-slate-800 text-base">Delete Mapping?</h3>
            <p id="deleteInfo" class="text-sm font-semibold text-slate-600 mt-1"></p>
            <p class="text-xs text-slate-400 mt-2">This action cannot be undone.</p>
            <div class="flex gap-3 mt-8">
                <button onclick="closeDeleteModal()" class="flex-1 py-3 bg-slate-100 rounded-xl text-[10px] font-black uppercase text-slate-500 hover:bg-slate-200 transition-all">Cancel</button>
                <button onclick="confirmDelete()" id="deleteConfirmBtn" class="flex-1 py-3 bg-red-500 text-white rounded-xl text-[10px] font-black uppercase shadow-lg hover:bg-red-600 transition-all">Delete</button>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    const CSRF_TOKEN = '{{ csrf_token() }}';
    const DELETE_BASE = '{{ url("admin/account-lawyer") }}';
    const EDIT_BASE   = '{{ url("admin/account-lawyer") }}';
    const PERM = @json($perms);
    const PER_PAGE = 8;

    let page = 1, currentView = 'grid', deleteId = null;

    const rows = @json($mappings->values());
    const avatarColors = ['bg-teal-500','bg-blue-500','bg-purple-500','bg-orange-500','bg-rose-500','bg-green-500'];

    const lawyerColors = ['#e57373','#ba68c8','#4fc3f7','#81c784','#ffb74d','#a1887f','#f06292','#7986cb'];

    function getFiltered() {
        const q = document.getElementById('searchInput').value.toLowerCase();
        return rows.filter(r => {
            const lawyerMatch = (r.lawyers || []).some(l =>
                l.name.toLowerCase().includes(q) || l.id.toLowerCase().includes(q)
            );
            return r.accountNo.toLowerCase().includes(q) ||
                r.accountName.toLowerCase().includes(q) || lawyerMatch;
        });
    }

    function render() {
        const filtered = getFiltered();
        const total    = filtered.length;
        const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
        if (page > totalPages) page = 1;
        const start = (page - 1) * PER_PAGE;
        const slice = filtered.slice(start, start + PER_PAGE);

        // LIST
        const listBody = document.getElementById('listBody');
        listBody.innerHTML = '';
        slice.forEach((row, i) => {
            const color = avatarColors[i % avatarColors.length];
            const initials = row.accountName ? row.accountName.split(' ').map(p => p[0]).join('').substring(0,2) : row.accountNo.slice(-2);
            const primaryLawyer = (row.lawyers || [])[0] || {};
            const lawyerInfo = row.lawyerCount > 1
                ? `<span class="lawyer-tag">${primaryLawyer.id || ''}</span> <span class="text-[10px] text-slate-400">+${row.lawyerCount - 1} more</span>`
                : `<span class="lawyer-tag">${primaryLawyer.id || ''}</span>`;
            const tr = document.createElement('tr');
            tr.className = 'transition-colors hover:bg-slate-50';
            tr.innerHTML = `
                <td class="py-3 px-4">
                    <div class="flex items-center gap-3">
                        <div class="w-9 h-9 ${color} text-white text-[11px] font-black flex items-center justify-center rounded-xl shrink-0">${initials.toUpperCase()}</div>
                        <div>
                            <p class="text-xs font-bold text-slate-800">${row.accountNo}</p>
                            <p class="text-[10px] text-slate-400">${row.accountName}</p>
                        </div>
                    </div>
                </td>
                <td class="py-3 px-4">
                    <p class="text-xs font-bold text-slate-800">${primaryLawyer.name || ''}</p>
                    <div class="mt-1">${lawyerInfo}</div>
                </td>
                <td class="py-3 px-4 text-xs font-semibold text-slate-600">${row.updatedOn}</td>
                <td class="py-3 px-4"><span class="pill ${row.status === 'Active' ? 'pill-green' : 'pill-red'}">${row.status}</span></td>
                <td class="py-3 px-4">
                    <div class="flex items-center justify-center gap-2">
                        ${PERM.edit ? `<button onclick="editMapping(${row.id})" class="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 text-slate-500 hover:bg-[#e6f7f6] hover:text-[#00ada8] transition-colors" title="Edit"><i class="fa-solid fa-pen text-[10px]"></i></button>` : ''}
                        ${PERM.delete ? `<button onclick="openDeleteModal(${row.id}, '${row.accountNo}')" class="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 text-slate-500 hover:bg-red-50 hover:text-red-500 transition-colors" title="Delete"><i class="fa-solid fa-trash-can text-[10px]"></i></button>` : ''}
                    </div>
                </td>`;
            listBody.appendChild(tr);
        });

        // GRID
        const gridContainer = document.getElementById('gridContainer');
        gridContainer.innerHTML = '';
        slice.forEach((row, i) => {
            // Build lawyer avatar circles
            const lawyers = row.lawyers || [];
            const avatarsHtml = lawyers.map((l, li) => {
                const init = (l.name || 'L').split(' ').map(w => w[0]).join('').substring(0,2).toUpperCase();
                const bg = lawyerColors[li % lawyerColors.length];
                return `<div class="avatar" style="background:${bg};" title="${l.name} (${l.id})">${init}</div>`;
            }).join('');

            const card = document.createElement('article');
            card.className = 'bg-white rounded-2xl border border-slate-200 p-5 hover:shadow-lg hover:border-[#00ada8] transition-all';
            card.innerHTML = `
                <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0">
                        <p class="text-[15px] font-extrabold text-slate-900">${row.accountNo}</p>
                        <p class="text-[11px] text-slate-400 mt-1">${row.createdOn}</p>
                    </div>
                    <div class="flex items-center gap-2 shrink-0">
                        ${PERM.edit ? `<button onclick="editMapping(${row.id})" class="w-8 h-8 flex items-center justify-center rounded-lg text-blue-600 hover:bg-blue-50 transition-colors" title="Edit"><i class="fa-solid fa-pen-to-square text-sm"></i></button>` : ''}
                        ${PERM.delete ? `<button onclick="openDeleteModal(${row.id}, '${row.accountNo}')" class="w-8 h-8 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 transition-colors" title="Delete"><i class="fa-solid fa-trash-can text-sm"></i></button>` : ''}
                    </div>
                </div>
                <div class="flex items-center justify-between mt-4 pt-4 border-t border-slate-100">
                    <div class="card-badge"><i class="fa-regular fa-calendar text-[10px]"></i> ${row.assignDate}</div>
                    <div class="flex items-center gap-3">
                        <span class="text-xs font-bold text-slate-600">Lawyers (${row.lawyerCount})</span>
                        <div class="lawyer-avatars">${avatarsHtml}</div>
                    </div>
                </div>`;
            gridContainer.appendChild(card);
        });

        // Pagination
        document.getElementById('showingText').textContent = `Showing ${total ? start + 1 : 0}–${Math.min(start + PER_PAGE, total)} of ${total} mappings`;
        const pag = document.getElementById('pagination');
        pag.innerHTML = `<button onclick="changePage(${page-1})" ${page===1?'disabled':''} class="w-8 h-8 rounded-lg border border-slate-200 text-slate-400 disabled:opacity-40"><i class="fa-solid fa-chevron-left text-[10px]"></i></button>`;
        for (let p = 1; p <= totalPages; p++)
            pag.innerHTML += `<button onclick="changePage(${p})" class="w-8 h-8 rounded-lg text-xs font-bold ${p===page?'bg-[#00ada8] text-white':'border border-slate-200 text-slate-400'}">${p}</button>`;
        pag.innerHTML += `<button onclick="changePage(${page+1})" ${page===totalPages?'disabled':''} class="w-8 h-8 rounded-lg border border-slate-200 text-slate-400 disabled:opacity-40"><i class="fa-solid fa-chevron-right text-[10px]"></i></button>`;
    }

    function changePage(p) {
        const tp = Math.max(1, Math.ceil(getFiltered().length / PER_PAGE));
        if (p < 1 || p > tp) return;
        page = p; render();
    }

    function setView(v) {
        currentView = v;
        document.getElementById('gridContainer').style.display = v === 'grid' ? '' : 'none';
        document.getElementById('listContainer').style.display = v === 'list' ? '' : 'none';
        document.getElementById('gridBtn').className = `w-9 h-9 flex items-center justify-center rounded-lg ${v==='grid' ? 'bg-white shadow-sm text-[#00ada8]' : 'text-slate-400 hover:text-[#00ada8]'}`;
        document.getElementById('listBtn').className = `w-9 h-9 flex items-center justify-center rounded-lg ${v==='list' ? 'bg-white shadow-sm text-[#00ada8]' : 'text-slate-400 hover:text-[#00ada8]'}`;
        render();
    }

    // ── Edit Modal Logic ──
    const LAW_FIRM_URL   = '{{ route("admin.oracle.law-firms") }}';
    const CHECK_USER_URL = '{{ route("admin.oracle.check-lawyer-user") }}';
    const UPDATE_BASE    = '{{ url("admin/account-lawyer") }}';

    let editId = null, editLawyers = [];

    async function editMapping(id) {
        editId = id;

        try {
            const res = await fetch(EDIT_BASE + '/' + id + '/edit', { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } });
            const json = await res.json();
            if (!json.success) { alert('Failed to load.'); return; }

            const m = json.mapping;
            document.getElementById('editAccountLabel').textContent = m.loan_id + ' — ' + (m.customer_name || '');
            document.getElementById('editAssignDate').value = m.assign_date || '';
            document.getElementById('editSubmittedDate').value = m.case_submitted_date || '';
            document.getElementById('editRegistrationVia').value = m.case_registration_via || '';
            document.getElementById('editCourtFee').value = m.court_fee || '';
            document.getElementById('editCaseFiledDate').value = m.case_filed_date || '';
            document.getElementById('editRemarks').value = m.internal_remarks || '';

            editLawyers = (m.lawyers || []).map(l => ({
                id: l.id, name: l.name, address: l.address || '', email: l.email || '', mobile: l.mobile || '', user_id: l.user_id
            }));
            renderEditLawyers();

            document.getElementById('editLawyerSearch').value = '';
            document.getElementById('editSuggestions').style.display = 'none';
            document.getElementById('editAlertError').style.display = 'none';
            document.getElementById('editModal').classList.add('active');
        } catch (e) {
            alert('Failed to load mapping data.');
        }
    }

    function closeEditModal() {
        document.getElementById('editModal').classList.remove('active');
        editId = null; editLawyers = [];
    }

    function renderEditLawyers() {
        const container = document.getElementById('editLawyersList');
        document.getElementById('editLawyerCount').textContent = editLawyers.length;
        if (editLawyers.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:#94a3b8;font-size:12px;padding:16px 0;">No lawyers assigned</p>';
            return;
        }
        container.innerHTML = editLawyers.map(l => `
            <div class="edit-lawyer-row">
                <div style="flex:1;min-width:0;">
                    <div style="font-size:13px;font-weight:700;color:#1e293b;">${l.name || l.id}</div>
                    <div style="font-size:11px;color:#64748b;">${l.id}</div>
                </div>
                <button class="edit-lawyer-remove" onclick="removeEditLawyer('${l.id.replace(/'/g, "\\'")}')" title="Remove">
                    <i class="fa-solid fa-trash-can"></i>
                </button>
            </div>
        `).join('');
    }

    function removeEditLawyer(id) {
        editLawyers = editLawyers.filter(l => l.id !== id);
        renderEditLawyers();
    }

    // Search lawyer in edit modal — autocomplete
    let editSearchTimer = null;
    document.getElementById('editLawyerSearch').addEventListener('input', () => {
        clearTimeout(editSearchTimer);
        const q = document.getElementById('editLawyerSearch').value.trim();
        if (q.length < 1) { document.getElementById('editSuggestions').style.display = 'none'; return; }
        editSearchTimer = setTimeout(() => doEditLawyerSearch(), 300);
    });

    async function doEditLawyerSearch() {
        const q = document.getElementById('editLawyerSearch').value.trim();
        if (!q) return;
        const sugBox = document.getElementById('editSuggestions');
        document.getElementById('editAlertError').style.display = 'none';
        sugBox.innerHTML = '<div style="padding:10px;font-size:11px;color:#94a3b8;text-align:center;"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Searching...</div>';
        sugBox.style.display = 'block';

        try {
            const res = await fetch(LAW_FIRM_URL + '?q=' + encodeURIComponent(q), { headers: { 'Accept': 'application/json' } });
            const json = await res.json();
            if (!json.success || !json.data?.length) {
                sugBox.innerHTML = '<div style="padding:10px;font-size:11px;color:#94a3b8;text-align:center;">No results</div>';
                return;
            }
            const selectedIds = editLawyers.map(l => l.id);
            sugBox.innerHTML = json.data.map(f => {
                const already = selectedIds.includes(f.id);
                return `<div class="edit-sug-item ${already ? 'opacity-50' : ''}" ${already ? '' : `onclick="addEditLawyer('${f.id.replace(/'/g,"\\'")}','${(f.name||'').replace(/'/g,"\\'")}','${(f.address||'').replace(/'/g,"\\'")}','${(f.email||'').replace(/'/g,"\\'")}','${(f.mobile||'').replace(/'/g,"\\'")}')"`}>
                    <strong style="color:#0f766e;">${f.id}</strong> — ${f.name}
                    ${already ? '<span style="color:#00ada8;font-size:10px;margin-left:6px;">Selected</span>' : ''}
                </div>`;
            }).join('');
        } catch (e) {
            sugBox.innerHTML = '<div style="padding:10px;font-size:11px;color:#ef4444;text-align:center;">Connection error</div>';
        }
    }

    async function addEditLawyer(id, name, address, email, mobile) {
        if (editLawyers.find(l => l.id === id)) return;
        const sugBox = document.getElementById('editSuggestions');
        sugBox.style.display = 'none';
        document.getElementById('editLawyerSearch').value = '';
        document.getElementById('editAlertError').style.display = 'none';

        try {
            const res = await fetch(CHECK_USER_URL + '?law_firm_id=' + encodeURIComponent(id), { headers: { 'Accept': 'application/json' } });
            const json = await res.json();
            if (!json.exists) {
                document.getElementById('editAlertError').style.display = 'block';
                document.getElementById('editAlertMsg').textContent = json.message || 'Lawyer not registered as portal user.';
                return;
            }
            editLawyers.push({ id, name, address, email, mobile, user_id: json.user?.id || null });
            renderEditLawyers();
        } catch (e) {
            document.getElementById('editAlertError').style.display = 'block';
            document.getElementById('editAlertMsg').textContent = 'Error verifying lawyer.';
        }
    }

    // Close suggestions on outside click
    document.addEventListener('click', e => {
        if (!e.target.closest('#editSuggestions') && !e.target.closest('#editLawyerSearch')) {
            document.getElementById('editSuggestions').style.display = 'none';
        }
    });

    async function saveEdit() {
        if (!editId) return;
        if (editLawyers.length === 0) { alert('At least one lawyer is required.'); return; }

        const assignDate = document.getElementById('editAssignDate').value;
        const submittedDate = document.getElementById('editSubmittedDate').value;
        const regVia = document.getElementById('editRegistrationVia').value.trim();
        const courtFee = document.getElementById('editCourtFee').value;
        const caseFiledDate = document.getElementById('editCaseFiledDate').value;

        if (!assignDate || !submittedDate || !regVia || !courtFee) {
            alert('Please fill all required fields.'); return;
        }

        const btn = document.getElementById('btnEditSave');
        btn.disabled = true; btn.textContent = 'Saving...';

        const payload = new FormData();
        payload.append('_token', CSRF_TOKEN);
        payload.append('_method', 'PUT');
        payload.append('assign_date', assignDate);
        payload.append('case_submitted_date', submittedDate);
        payload.append('case_registration_via', regVia);
        payload.append('court_fee', courtFee);
        payload.append('case_filed_date', caseFiledDate || assignDate);
        payload.append('internal_remarks', document.getElementById('editRemarks').value);
        payload.append('lawyers', JSON.stringify(editLawyers));

        try {
            const res = await fetch(UPDATE_BASE + '/' + editId, { method: 'POST', body: payload, headers: { 'Accept': 'application/json' } });
            const data = await res.json();
            if (data.success) {
                closeEditModal();
                window.location.reload();
            } else {
                const err = data.errors ? Object.values(data.errors)[0]?.[0] : (data.message || 'Something went wrong.');
                alert(err);
            }
        } catch (e) { alert('Request failed.'); }
        finally { btn.disabled = false; btn.textContent = 'Submit'; }
    }

    function openDeleteModal(id, accountNo) {
        deleteId = id;
        document.getElementById('deleteInfo').textContent = 'Account: ' + accountNo;
        document.getElementById('deleteModal').classList.add('active');
    }
    function closeDeleteModal() {
        document.getElementById('deleteModal').classList.remove('active');
        deleteId = null;
    }

    async function confirmDelete() {
        if (!deleteId) return;
        const btn = document.getElementById('deleteConfirmBtn');
        btn.disabled = true; btn.textContent = 'Deleting...';

        const payload = new FormData();
        payload.append('_token', CSRF_TOKEN);
        payload.append('_method', 'DELETE');

        try {
            const res  = await fetch(DELETE_BASE + '/' + deleteId, { method: 'POST', body: payload, headers: { 'Accept': 'application/json' } });
            const data = await res.json();
            if (data.success) {
                const idx = rows.findIndex(r => r.id === deleteId);
                if (idx !== -1) rows.splice(idx, 1);
                closeDeleteModal();
                render();
            } else {
                alert(data.message || 'Delete failed.');
            }
        } catch (e) {
            alert('Request failed.');
        } finally {
            btn.disabled = false; btn.textContent = 'Delete';
        }
    }

    if (PERM.view) setView(currentView);
</script>
@endpush
