@extends('admin.layouts.app')

@section('title', 'FMP CORE - Select Lawyer')

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

@push('styles')
<style>
    .page {
        width: 100%; max-width: 100%; background: #ffffff; border-radius: 24px;
        box-shadow: 0 22px 60px rgba(15, 23, 42, 0.16); padding: 28px 32px 32px; border: 1px solid #e2e8f0;
    }
    .page-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 24px; }
    .page-title { font-size: 18px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase; color: #0f172a; }
    .page-subtitle { font-size: 13px; color: #64748b; }
    .layout { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1.75fr); gap: 28px; align-items: flex-start; }
    .search-panel { padding-right: 8px; }
    .field-label { font-size: 13px; font-weight: 600; color: #475569; margin-bottom: 6px; }
    .field-label span { color: #d63031; }
    .search-row { display: flex; gap: 10px; align-items: center; }
    .input-wrapper { position: relative; flex: 1; }
    .input-text {
        width: 100%; border-radius: 999px; border: 1px solid #cbd5e1; padding: 10px 38px 10px 14px;
        font-size: 14px; outline: none; transition: border-color 0.15s ease, box-shadow 0.15s ease; background: #ffffff;
    }
    .input-text:focus { border-color: #00ada8; box-shadow: 0 0 0 3px rgba(0, 173, 168, 0.16); background: #f8fafc; }
    .input-text::placeholder { color: #94a3b8; }
    .icon-search {
        position: absolute; right: 12px; top: 50%; transform: translateY(-50%);
        font-size: 11px; color: #64748b; pointer-events: none;
    }
    .btn {
        border: none; border-radius: 999px; padding: 10px 30px; font-size: 14px; font-weight: 500;
        cursor: pointer; transition: all 0.15s ease; white-space: nowrap;
    }
    .btn-primary {
        background: radial-gradient(circle at top left, #00ada8 0%, #007d79 100%);
        color: #ffffff; box-shadow: 0 10px 25px rgba(0, 173, 168, 0.35);
    }
    .btn-primary:hover { transform: translateY(-1px); }
    .btn-primary:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
    .helper-text { margin-top: 12px; font-size: 12px; color: #94a3b8; }
    .suggestions-box {
        margin-top: 8px; border-radius: 14px; border: 1.5px solid #e2e8f0; background: #fff;
        box-shadow: 0 12px 36px rgba(15,23,42,0.12); max-height: 260px; overflow-y: auto; display: none;
    }
    .sug-item {
        padding: 10px 14px; cursor: pointer; border-bottom: 1px solid #f8fafc; transition: background 0.1s;
        display: flex; align-items: center; gap: 10px;
    }
    .sug-item:hover { background: #f0fdfb; }
    .sug-icon {
        width: 34px; height: 34px; border-radius: 10px; background: #e6f7f6;
        display: flex; align-items: center; justify-content: center; flex-shrink: 0;
    }
    .result-panel {
        background: linear-gradient(135deg, #ffffff 0%, #f0fdfa 100%); border-radius: 18px;
        border: 1px solid #e2e8f0; padding: 22px; min-height: 260px; display: flex; flex-direction: column; gap: 14px;
    }
    .summary-card {
        background: #ffffff; border-radius: 16px; padding: 20px 24px; border: 2px solid #e2e8f0;
        box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08); transition: all 0.3s ease;
    }
    .summary-card:hover { border-color: #00ada8; transform: translateY(-2px); }
    .summary-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; }
    .summary-title { font-size: 14px; font-weight: 800; color: #0f172a; margin-bottom: 6px; }
    .summary-title span { color: #00ada8; font-weight: 900; }
    .summary-meta { font-size: 13px; color: #64748b; font-weight: 500; }
    .summary-meta span { color: #1e293b; font-weight: 700; }
    .detail-btn {
        display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px;
        background: linear-gradient(135deg, #00ada8 0%, #007d79 100%); color: white; border-radius: 20px;
        font-size: 11px; font-weight: 700; text-transform: uppercase; border: none; cursor: pointer;
    }
    .lawyer-chip {
        background: #f0fdfb; border: 1.5px solid #99f6e4; border-radius: 14px; padding: 14px 16px;
        display: flex; align-items: flex-start; gap: 12px; transition: all 0.2s ease; position: relative;
    }
    .lawyer-chip:hover { border-color: #00ada8; box-shadow: 0 4px 12px rgba(0,173,168,0.12); }
    .lawyer-chip .remove-btn {
        position: absolute; top: 8px; right: 8px; width: 22px; height: 22px; border-radius: 50%;
        background: #fee2e2; color: #b91c1c; border: none; cursor: pointer; font-size: 10px;
        display: flex; align-items: center; justify-content: center; transition: all 0.15s;
    }
    .lawyer-chip .remove-btn:hover { background: #fecaca; transform: scale(1.1); }
    .lawyer-avatar {
        width: 44px; height: 44px; border-radius: 12px; background: #00ada8;
        color: #fff; font-size: 14px; font-weight: 800; display: flex; align-items: center;
        justify-content: center; flex-shrink: 0;
    }
    .result-footer { display: flex; justify-content: flex-end; margin-top: 4px; }
    .btn-outline {
        background: transparent; color: #00ada8; border-radius: 999px; border: 1px solid rgba(0, 173, 168, 0.6);
        padding: 9px 24px; font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.15s ease;
    }
    .btn-outline:hover { background: rgba(0, 173, 168, 0.06); }
    .btn-outline:disabled { opacity: 0.5; cursor: not-allowed; }
    .note-bar {
        margin-top: 22px; border-radius: 10px; padding: 10px 12px; background: #fef9e7;
        border: 1px dashed #f1c40f; display: flex; align-items: flex-start; gap: 10px; font-size: 12px; color: #8a6d1f;
    }
    .note-label { font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; font-size: 11px; }
    .note-dot { margin-top: 4px; width: 6px; height: 6px; border-radius: 50%; background: #f1c40f; }
    .alert-error {
        background: #fef2f2; border: 1px solid #fecaca; border-radius: 12px; padding: 12px 16px;
        color: #b91c1c; font-size: 12px; font-weight: 500; display: none; margin-top: 10px;
    }
    @media (max-width: 900px) { .layout { grid-template-columns: minmax(0, 1fr); } }
</style>
@endpush

@section('content')
    <div class="page">
        <header class="page-header">
            <div>
                <h1 class="page-title">Lawyer Code – Mapping</h1>
                <p class="page-subtitle">Search lawyer by code or name for the selected account. You can select multiple lawyers.</p>
            </div>
        </header>

        <section class="layout">
            <!-- Left: Lawyer search -->
            <div class="search-panel">
                <label class="field-label" for="lawyerCode">Lawyer Code <span>*</span></label>
                <div class="search-row">
                    <div class="input-wrapper">
                        <input type="text" id="lawyerCode" class="input-text" placeholder="Search by Lawyer Code or Name" autocomplete="off" />
                        <span class="icon-search"><i class="fa-solid fa-magnifying-glass" style="font-size:10px;"></i></span>
                    </div>
                    <button id="btnSearchLawyer" class="btn btn-primary" type="button">Search</button>
                </div>
                <p class="helper-text">
                    Enter a valid <strong>Lawyer Code</strong> or name and click <strong>Search</strong> to fetch lawyer details from the Oracle database.
                </p>

                <!-- Search results / suggestions -->
                <div id="suggestions" class="suggestions-box"></div>

                <!-- Error alert -->
                <div id="alertError" class="alert-error">
                    <i class="fa-solid fa-circle-exclamation mr-1"></i>
                    <span id="alertErrorMsg"></span>
                </div>

                <!-- Selected lawyers count -->
                <div id="selectedCount" style="margin-top:14px;font-size:12px;font-weight:700;color:#00ada8;display:none;">
                    <i class="fa-solid fa-check-circle mr-1"></i> <span id="countText"></span>
                </div>
            </div>

            <!-- Right: Account + selected lawyers -->
            <aside class="result-panel">
                <!-- Account summary -->
                <section class="summary-card">
                    <header class="summary-header">
                        <div class="flex-1">
                            <div class="summary-title">Account No (Loan ID): <span id="accountIdText">{{ $accountNo }}</span></div>
                            <div class="summary-meta mt-1">Account Name: <span id="accountNameText">{{ $customerName }}</span></div>
                        </div>
                        <button class="detail-btn" type="button">
                            <i class="fa-solid fa-circle-check text-[10px]"></i> Account Details
                        </button>
                    </header>
                </section>

                <!-- Selected lawyers list -->
                <div id="lawyersContainer">
                    <p id="noLawyerMsg" class="text-center text-sm text-slate-400 py-6">
                        <i class="fa-solid fa-scale-balanced mr-2 text-slate-300"></i>
                        Search and select lawyers to add to this account mapping.
                    </p>
                </div>

                <footer class="result-footer">
                    <button id="btnConfirmLawyer" class="btn-outline" type="button" disabled>
                        Confirm Lawyer &amp; Continue
                    </button>
                </footer>
            </aside>
        </section>

        <section class="note-bar" aria-label="Important note">
            <span class="note-dot" aria-hidden="true"></span>
            <div>
                <div class="note-label">Note</div>
                <div>After confirming the lawyer(s), you will move to the final step to capture case-level information and create the mapping.</div>
            </div>
        </section>
    </div>
@endsection

@push('scripts')
<script>
    const LAW_FIRM_URL   = '{{ route("admin.oracle.law-firms") }}';
    const CHECK_USER_URL = '{{ route("admin.oracle.check-lawyer-user") }}';
    const CREATE_URL     = '{{ route("admin.account-lawyer.create") }}';

    // Account data passed from step 1
    const accountNo    = @json($accountNo);
    const customerName = @json($customerName);
    const principal    = @json($principal);
    const odi          = @json($odi);
    const crc          = @json($crc);
    const stmtDate     = @json($stmtDate);
    const stmtAmount   = @json($stmtAmount);

    const lawyerInput  = document.getElementById('lawyerCode');
    const btnSearch    = document.getElementById('btnSearchLawyer');
    const sugBox       = document.getElementById('suggestions');
    const alertError   = document.getElementById('alertError');
    const alertErrorMsg= document.getElementById('alertErrorMsg');
    const btnConfirm   = document.getElementById('btnConfirmLawyer');

    let selectedLawyers = []; // Array of {id, name, address, email, mobile, user_id}

    // Search
    btnSearch.addEventListener('click', () => doSearch());
    lawyerInput.addEventListener('keydown', e => { if (e.key === 'Enter') doSearch(); });

    let searchTimer = null;
    lawyerInput.addEventListener('input', () => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            if (lawyerInput.value.trim().length >= 1) doSearch();
        }, 400);
    });

    async function doSearch() {
        const q = lawyerInput.value.trim();
        if (!q) { lawyerInput.focus(); return; }

        alertError.style.display = 'none';
        sugBox.innerHTML = '<div style="padding:12px 14px;font-size:11px;color:#94a3b8;text-align:center;"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Searching Oracle...</div>';
        sugBox.style.display = 'block';

        try {
            const res  = await fetch(LAW_FIRM_URL + '?q=' + encodeURIComponent(q), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            });
            const json = await res.json();

            if (!json.success) {
                sugBox.innerHTML = `<div style="padding:12px 14px;font-size:11px;color:#ef4444;text-align:center;"><i class="fa-solid fa-circle-exclamation mr-1"></i> ${json.message || 'Error'}</div>`;
                return;
            }

            if (!json.data || !json.data.length) {
                sugBox.innerHTML = '<div style="padding:12px 14px;font-size:11px;color:#94a3b8;text-align:center;">No results found</div>';
                return;
            }

            // Filter out already selected
            const selectedIds = selectedLawyers.map(l => l.id);

            sugBox.innerHTML = json.data.map(f => {
                const alreadySelected = selectedIds.includes(f.id);
                return `<div class="sug-item ${alreadySelected ? 'opacity-50' : ''}" onclick="${alreadySelected ? '' : `selectLawyer('${escapeJs(f.id)}','${escapeJs(f.name)}','${escapeJs(f.address)}','${escapeJs(f.email)}','${escapeJs(f.mobile)}')`}" style="${alreadySelected ? 'cursor:default;' : ''}">
                    <div class="sug-icon"><i class="fa-solid fa-scale-balanced" style="color:#00ada8;font-size:12px;"></i></div>
                    <div>
                        <div style="font-size:11px;font-weight:800;color:#0f766e;">${f.id}</div>
                        <div style="font-size:11px;color:#374151;font-weight:600;">${f.name}</div>
                        ${f.address ? `<div style="font-size:10px;color:#94a3b8;">${f.address}</div>` : ''}
                        ${alreadySelected ? '<div style="font-size:10px;color:#00ada8;font-weight:700;">Already selected</div>' : ''}
                    </div>
                </div>`;
            }).join('');
        } catch (e) {
            sugBox.innerHTML = '<div style="padding:12px 14px;font-size:11px;color:#ef4444;text-align:center;"><i class="fa-solid fa-wifi mr-1"></i> Connection error</div>';
        }
    }

    function escapeJs(str) {
        return (str || '').replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\"');
    }

    async function selectLawyer(id, name, address, email, mobile) {
        // Check if already selected
        if (selectedLawyers.find(l => l.id === id)) return;

        sugBox.style.display = 'none';
        lawyerInput.value = '';
        alertError.style.display = 'none';

        // Check if this lawyer exists in our user table
        try {
            const res  = await fetch(CHECK_USER_URL + '?law_firm_id=' + encodeURIComponent(id), {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            });
            const json = await res.json();

            if (!json.exists) {
                alertError.style.display = 'block';
                alertErrorMsg.textContent = json.message || 'This lawyer is not registered as a portal user.';
                return;
            }

            selectedLawyers.push({
                id, name, address, email, mobile,
                user_id: json.user?.id || null,
                user_name: json.user?.name || name,
            });

            renderSelectedLawyers();
        } catch (e) {
            alertError.style.display = 'block';
            alertErrorMsg.textContent = 'Error verifying lawyer. Please try again.';
        }
    }

    function removeLawyer(id) {
        selectedLawyers = selectedLawyers.filter(l => l.id !== id);
        renderSelectedLawyers();
    }

    function renderSelectedLawyers() {
        const container = document.getElementById('lawyersContainer');
        const noMsg     = document.getElementById('noLawyerMsg');
        const countEl   = document.getElementById('selectedCount');
        const countText = document.getElementById('countText');

        if (selectedLawyers.length === 0) {
            container.innerHTML = '<p id="noLawyerMsg" class="text-center text-sm text-slate-400 py-6"><i class="fa-solid fa-scale-balanced mr-2 text-slate-300"></i> Search and select lawyers to add to this account mapping.</p>';
            countEl.style.display = 'none';
            btnConfirm.disabled = true;
            return;
        }

        countEl.style.display = 'block';
        countText.textContent = selectedLawyers.length + ' lawyer(s) selected';
        btnConfirm.disabled = false;

        container.innerHTML = selectedLawyers.map(l => {
            const initials = (l.name || 'L').split(' ').map(w => w[0]).join('').substring(0, 2).toUpperCase();
            return `<div class="lawyer-chip" style="margin-bottom:10px;">
                <button class="remove-btn" onclick="removeLawyer('${escapeJs(l.id)}')" title="Remove"><i class="fa-solid fa-xmark"></i></button>
                <div class="lawyer-avatar">${initials}</div>
                <div style="flex:1;min-width:0;">
                    <div style="font-size:13px;font-weight:800;color:#0f766e;">${l.name}</div>
                    <div style="font-size:11px;color:#475569;margin-top:2px;"><strong>Code:</strong> ${l.id}</div>
                    ${l.address ? `<div style="font-size:11px;color:#64748b;margin-top:1px;"><strong>Address:</strong> ${l.address}</div>` : ''}
                    ${l.email ? `<div style="font-size:11px;color:#64748b;margin-top:1px;"><strong>Email:</strong> ${l.email}</div>` : ''}
                    ${l.mobile ? `<div style="font-size:11px;color:#64748b;margin-top:1px;"><strong>Mobile:</strong> ${l.mobile}</div>` : ''}
                </div>
            </div>`;
        }).join('');
    }

    // Close suggestions on outside click
    document.addEventListener('click', e => {
        if (!e.target.closest('.search-panel')) sugBox.style.display = 'none';
    });

    // Confirm & continue
    btnConfirm.addEventListener('click', () => {
        if (selectedLawyers.length === 0) return;

        const url = new URL(CREATE_URL, window.location.href);
        url.searchParams.set('accountNo',    accountNo);
        url.searchParams.set('customerName', customerName);
        url.searchParams.set('principal',    principal);
        url.searchParams.set('odi',          odi);
        url.searchParams.set('crc',          crc);
        url.searchParams.set('stmtDate',     stmtDate);
        url.searchParams.set('stmtAmount',   stmtAmount);
        url.searchParams.set('lawyers',      JSON.stringify(selectedLawyers));
        window.location.href = url.toString();
    });
</script>
@endpush
