@php
    $quickBranchIds = $branches->pluck('id');
    $quickBusinessIds = \App\Models\Branch::whereIn('id', $quickBranchIds)->pluck('business_id')->unique();
    $quickCategories = \App\Models\CollateralCategory::whereIn('business_id', $quickBusinessIds)
        ->where('status', 'active')
        ->orderBy('name')
        ->get();
    $quickReceivers = \App\Models\User::whereHas('branches', fn($q) => $q->whereIn('branches.id', $quickBranchIds))
        ->where('status', 'active')
        ->orderBy('name')
        ->get();
    $quickCollateralStatuses = \App\Models\Collateral::STATUSES;
@endphp

<style>
    .mf-quick-dialog {
        width: min(980px, calc(100vw - 28px));
        max-height: 88vh;
        margin: auto;
        padding: 0;
        border: 1px solid var(--border);
        border-radius: 8px;
        background: var(--background);
        color: var(--foreground);
        box-shadow: 0 24px 70px rgb(0 0 0 / .22)
    }

    .mf-quick-dialog::backdrop {
        background: rgb(0 0 0 / .42);
        backdrop-filter: blur(2px)
    }

    .mf-quick-head {
        position: sticky;
        top: 0;
        z-index: 2;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 16px;
        padding: 14px 16px;
        border-bottom: 1px solid var(--border);
        background: var(--background)
    }

    .mf-quick-head h2 {
        font-size: 1rem;
        font-weight: 650
    }

    .mf-quick-head p {
        margin-top: 2px;
        font-size: .75rem;
        color: var(--muted-foreground)
    }

    .mf-quick-body {
        padding: 16px
    }

    .mf-quick-body .mf-form-section {
        margin-bottom: 16px
    }

    .mf-quick-actions {
        position: sticky;
        bottom: 0;
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        padding: 12px 16px;
        border-top: 1px solid var(--border);
        background: var(--background)
    }

    .mf-quick-close {
        width: 34px;
        height: 34px;
        flex: 0 0 auto
    }

    .mf-quick-errors {
        display: none;
        margin-bottom: 12px;
        padding: 10px 12px;
        border: 1px solid color-mix(in oklab, var(--destructive) 28%, transparent);
        border-radius: 6px;
        background: color-mix(in oklab, var(--destructive) 8%, transparent);
        font-size: .75rem;
        color: var(--destructive)
    }

    .mf-quick-errors.is-visible {
        display: block
    }

    .mf-quick-add {
        width: 40px;
        height: 40px;
        padding: 0;
        font-size: 1.1rem;
        font-weight: 600
    }

    .mf-quick-collateral-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 8px
    }

    @media(max-width:720px) {
        .mf-quick-dialog {
            width: calc(100vw - 16px);
            max-height: 94vh
        }

        .mf-quick-body {
            padding: 12px
        }

        .mf-quick-head,
        .mf-quick-actions {
            padding: 12px
        }
    }
</style>

@if (auth()->user()->can('customers.create'))
    <dialog id="quick-customer-dialog" class="mf-quick-dialog">
        <div class="mf-quick-head">
            <div>
                <h2>Register Customer</h2>
                <p>Same fields as the standard customer registration form.</p>
            </div><button type="button" class="mf-btn mf-quick-close" data-quick-close aria-label="Close">×</button>
        </div>
        <form id="quick-customer-form" method="POST" enctype="multipart/form-data" action="{{ route('customers.store') }}">
            @csrf
            <div class="mf-quick-body">
                <div class="mf-quick-errors" data-quick-errors></div>
                <x-ui.form-section title="Registration & identity"
                    description="Branch ownership, identification method and primary legal identity details."><x-ui.form-grid>
                        <div class="mf-col-3"><label class="mf-field-label">Branch</label><select
                                id="quick-customer-branch" class="mf-input" name="branch_id" required>
                                @foreach ($branches as $branch)
                                    <option value="{{ $branch->id }}">{{ $branch->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mf-col-2"><label class="mf-field-label">Registration mode</label><select
                                id="quick_identity_mode" class="mf-input" name="identity_mode">
                                <option value="without_nin">Without NIN</option>
                                <option value="with_nin">With NIN</option>
                            </select></div>
                        <div class="mf-col-4"><label class="mf-field-label">NIN</label>
                            <div class="mf-form-inline"><input id="quick_nin" class="mf-input" name="nin"><button
                                    id="quick_nin_lookup" type="button" class="mf-btn">Fetch</button></div>
                            <p id="quick_nin_result" class="mf-field-help"></p>
                        </div>
                        <div class="mf-col-3"><label class="mf-field-label">Customer status</label><select
                                class="mf-input" name="status">
                                @foreach (['active', 'inactive', 'deceased'] as $v)
                                    <option value="{{ $v }}" @selected($v === 'active')>{{ ucfirst($v) }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mf-col-4"><label class="mf-field-label">First name</label><input
                                id="quick_first_name" class="mf-input" name="first_name" required></div>
                        <div class="mf-col-4"><label class="mf-field-label">Middle name</label><input
                                id="quick_middle_name" class="mf-input" name="middle_name"></div>
                        <div class="mf-col-4"><label class="mf-field-label">Last name</label><input id="quick_last_name"
                                class="mf-input" name="last_name" required></div>
                        <div class="mf-col-2"><label class="mf-field-label">Gender</label><select id="quick_gender"
                                class="mf-input" name="gender">
                                <option value="">Select</option>
                                @foreach (['male', 'female', 'other'] as $v)
                                    <option value="{{ $v }}">{{ ucfirst($v) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mf-col-3"><label class="mf-field-label">Date of birth</label><input
                                id="quick_date_of_birth" type="date" class="mf-input" name="date_of_birth"></div>
                        <div class="mf-col-5"><label class="mf-field-label">Customer photograph</label><input
                                class="mf-input" type="file" name="photo" accept="image/png,image/jpeg,image/webp">
                            <p class="mf-field-help">JPEG, PNG or WebP. Stored privately as part of the customer KYC
                                record.</p>
                        </div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Contact & economic profile"
                    description="Communication channels and information used to understand employment and repayment capacity."><x-ui.form-grid>
                        <div class="mf-col-3"><label class="mf-field-label">Primary phone</label><input class="mf-input"
                                name="phone" required></div>
                        <div class="mf-col-3"><label class="mf-field-label">Alternative phone</label><input
                                class="mf-input" name="alternative_phone"></div>
                        <div class="mf-col-6"><label class="mf-field-label">Email</label><input type="email"
                                class="mf-input" name="email"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Occupation</label><input class="mf-input"
                                name="occupation"></div>
                        <div class="mf-col-4"><label class="mf-field-label">Employer / Business</label><input
                                class="mf-input" name="employer_business"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Monthly income</label><input
                                type="number" step="0.01" min="0" class="mf-input"
                                name="monthly_income"></div>
                        <div class="mf-col-2"><label class="mf-field-label">Marital status</label><select
                                class="mf-input" name="marital_status">
                                <option value="">Select</option>
                                @foreach (['single', 'married', 'divorced', 'widowed', 'other'] as $v)
                                    <option value="{{ $v }}">{{ ucfirst($v) }}</option>
                                @endforeach
                            </select>
                        </div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Residential address"
                    description="Administrative location and optional GPS coordinates for field verification."><x-ui.form-grid>
                        <div class="mf-col-3"><label class="mf-field-label">Region</label><input class="mf-input"
                                name="region"></div>
                        <div class="mf-col-3"><label class="mf-field-label">District</label><input class="mf-input"
                                name="district"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Ward</label><input class="mf-input"
                                name="ward"></div>
                        <div class="mf-col-3"><label class="mf-field-label">House number</label><input
                                class="mf-input" name="house_number"></div>
                        <div class="mf-col-6"><label class="mf-field-label">Street / Village</label><input
                                class="mf-input" name="street_village"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Latitude</label><input type="number"
                                step="0.0000001" class="mf-input" name="latitude"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Longitude</label><input type="number"
                                step="0.0000001" class="mf-input" name="longitude"></div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Primary next of kin"
                    description="The principal emergency or family contact associated with this customer."><x-ui.form-grid>
                        <div class="mf-col-4"><label class="mf-field-label">Full name</label><input class="mf-input"
                                name="next_of_kin_name"></div>
                        <div class="mf-col-2"><label class="mf-field-label">Relationship</label><input
                                class="mf-input" name="next_of_kin_relationship"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Phone</label><input class="mf-input"
                                name="next_of_kin_phone"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Address</label><input class="mf-input"
                                name="next_of_kin_address"></div>
                    </x-ui.form-grid></x-ui.form-section>
            </div>
            <div class="mf-quick-actions"><button type="button" class="mf-btn"
                    data-quick-close>Cancel</button><button class="mf-btn mf-btn-primary" type="submit">Register
                    customer</button></div>
        </form>
    </dialog>
@endif

@if (auth()->user()->can('customers.guarantors'))
    <dialog id="quick-guarantor-dialog" class="mf-quick-dialog">
        <div class="mf-quick-head">
            <div>
                <h2>Add Guarantor</h2>
                <p>Same fields as the guarantor form on the customer profile.</p>
            </div><button type="button" class="mf-btn mf-quick-close" data-quick-close>×</button>
        </div>
        <form id="quick-guarantor-form" method="POST" enctype="multipart/form-data"
            data-action-template="{{ url('/customers/__customer__/guarantors') }}">@csrf
            <div class="mf-quick-body">
                <div class="mf-quick-errors" data-quick-errors></div><x-ui.form-grid>
                    <div class="mf-col-4"><label class="mf-field-label">Full name</label><input class="mf-input"
                            name="full_name" required></div>
                    <div class="mf-col-2"><label class="mf-field-label">NIN</label><input class="mf-input"
                            name="nin"></div>
                    <div class="mf-col-2"><label class="mf-field-label">Phone</label><input class="mf-input"
                            name="phone" required></div>
                    <div class="mf-col-2"><label class="mf-field-label">Relationship</label><input class="mf-input"
                            name="relationship"></div>
                    <div class="mf-col-2"><label class="mf-field-label">Occupation</label><input class="mf-input"
                            name="occupation"></div>
                    <div class="mf-col-6"><label class="mf-field-label">Address</label><input class="mf-input"
                            name="address"></div>
                    <div class="mf-col-6"><label class="mf-field-label">Signed guarantee document</label><input
                            type="file" class="mf-input" name="signed_guarantee"></div>
                </x-ui.form-grid>
            </div>
            <div class="mf-quick-actions"><button type="button" class="mf-btn"
                    data-quick-close>Cancel</button><button class="mf-btn mf-btn-primary" type="submit">Add
                    guarantor</button></div>
        </form>
    </dialog>
@endif

@if (auth()->user()->can('collateral.manage'))
    <dialog id="quick-collateral-dialog" class="mf-quick-dialog">
        <div class="mf-quick-head">
            <div>
                <h2>Register Collateral</h2>
                <p>Same fields as the standard collateral registration form.</p>
            </div><button type="button" class="mf-btn mf-quick-close" data-quick-close>×</button>
        </div>
        <form id="quick-collateral-form" method="POST" enctype="multipart/form-data"
            action="{{ route('collateral.store') }}">@csrf
            <div class="mf-quick-body">
                <div class="mf-quick-errors" data-quick-errors></div>
                <x-ui.form-section title="Ownership & identification"
                    description="Connect the asset to the correct customer, branch and collateral category."><x-ui.form-grid>
                        <div class="mf-col-4"><label class="mf-field-label">Customer</label><select
                                id="quick-collateral-customer" name="customer_id" class="mf-input" required>
                                <option value="">Select customer</option>
                                @foreach ($customers as $customer)
                                    <option value="{{ $customer->id }}" data-branch="{{ $customer->branch_id }}">
                                        {{ $customer->customer_number }} — {{ $customer->full_name }} —
                                        {{ $customer->branch->name ?? '' }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mf-col-4"><label class="mf-field-label">Branch</label><select
                                id="quick-collateral-branch" name="branch_id" class="mf-input" required>
                                <option value="">Select branch</option>
                                @foreach ($branches as $branch)
                                    <option value="{{ $branch->id }}">{{ $branch->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mf-col-4"><label class="mf-field-label">Category</label><select
                                name="category_id" class="mf-input" required>
                                <option value="">Select category</option>
                                @foreach ($quickCategories as $category)
                                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Item details"
                    description="Describe the physical asset clearly enough that staff can identify it without ambiguity."><x-ui.form-grid>
                        <div class="mf-col-4"><label class="mf-field-label">Item</label><input name="item"
                                class="mf-input" placeholder="e.g. 55-inch Smart TV" required></div>
                        <div class="mf-col-2"><label class="mf-field-label">Brand</label><input name="brand"
                                class="mf-input"></div>
                        <div class="mf-col-2"><label class="mf-field-label">Model</label><input name="model"
                                class="mf-input"></div>
                        <div class="mf-col-2"><label class="mf-field-label">Serial number</label><input
                                name="serial_number" class="mf-input"></div>
                        <div class="mf-col-2"><label class="mf-field-label">Colour</label><input name="colour"
                                class="mf-input"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Condition</label><input name="condition"
                                class="mf-input" placeholder="Good / Fair / New"></div>
                        <div class="mf-col-9"><label class="mf-field-label">Description</label>
                            <textarea name="description" class="mf-input" rows="3"></textarea>
                        </div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Valuation & receipt"
                    description="Record assessed values and who physically received the collateral."><x-ui.form-grid>
                        <div class="mf-col-3"><label class="mf-field-label">Estimated value</label><input
                                name="estimated_value" inputmode="decimal" class="mf-input"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Accepted value</label><input
                                name="accepted_value" inputmode="decimal" class="mf-input"></div>
                        <div class="mf-col-3"><label class="mf-field-label">Date received</label><input
                                type="date" name="received_at" class="mf-input"
                                value="{{ now()->format('Y-m-d') }}" required></div>
                        <div class="mf-col-3"><label class="mf-field-label">Received by</label><select
                                name="received_by" class="mf-input">
                                <option value="">Current user / unassigned</option>
                                @foreach ($quickReceivers as $receiver)
                                    <option value="{{ $receiver->id }}">{{ $receiver->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Custody & storage"
                    description="Track the exact physical location. Future movements are recorded permanently from the collateral profile."><x-ui.form-grid>
                        <div class="mf-col-4"><label class="mf-field-label">Status</label><select name="status"
                                class="mf-input" required>
                                @foreach ($quickCollateralStatuses as $status)
                                    <option value="{{ $status }}" @selected($status === 'pending_inspection')>
                                        {{ str($status)->replace('_', ' ')->title() }}</option>
                                @endforeach
                            </select></div>
                        <div class="mf-col-4"><label class="mf-field-label">Store room</label><input
                                name="store_room" class="mf-input"></div>
                        <div class="mf-col-4"><label class="mf-field-label">Shelf / position</label><input
                                name="shelf" class="mf-input"></div>
                    </x-ui.form-grid></x-ui.form-section>
                <x-ui.form-section title="Photos & supporting documents"
                    description="Files are stored privately. You can add more attachments after registration."><x-ui.form-grid>
                        <div class="mf-col-6"><label class="mf-field-label">Photos</label><input type="file"
                                name="photos[]" multiple accept="image/png,image/jpeg,image/webp" class="mf-input">
                            <p class="mf-field-help">JPEG, PNG or WebP, up to 8 MB each.</p>
                        </div>
                        <div class="mf-col-6"><label class="mf-field-label">Documents</label><input type="file"
                                name="documents[]" multiple accept=".pdf,.doc,.docx,image/png,image/jpeg,image/webp"
                                class="mf-input">
                            <p class="mf-field-help">Ownership papers, receipts, valuation reports or other evidence.
                            </p>
                        </div>
                    </x-ui.form-grid></x-ui.form-section>
            </div>
            <div class="mf-quick-actions"><button type="button" class="mf-btn"
                    data-quick-close>Cancel</button><button class="mf-btn mf-btn-primary" type="submit">Register
                    collateral</button></div>
        </form>
    </dialog>
@endif

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const loanBranch = document.getElementById('loan-branch');
        const loanCustomer = document.getElementById('loan-customer');
        const loanGuarantor = document.getElementById('loan-guarantor');
        const collateralOptions = document.getElementById('collateral-options');
        const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';

        function plusButton(kind, title) {
            const b = document.createElement('button');
            b.type = 'button';
            b.className = 'mf-btn mf-quick-add';
            b.textContent = '+';
            b.title = title;
            b.setAttribute('aria-label', title);
            b.dataset.quickOpen = kind;
            return b;
        }
        @if (auth()->user()->can('customers.create'))
            if (loanCustomer) {
                const wrap = document.createElement('div');
                wrap.className = 'mf-form-inline';
                loanCustomer.parentNode.insertBefore(wrap, loanCustomer);
                wrap.append(loanCustomer, plusButton('customer', 'Add customer'));
            }
        @endif
        @if (auth()->user()->can('customers.guarantors'))
            if (loanGuarantor) {
                const wrap = document.createElement('div');
                wrap.className = 'mf-form-inline';
                loanGuarantor.parentNode.insertBefore(wrap, loanGuarantor);
                wrap.append(loanGuarantor, plusButton('guarantor', 'Add guarantor'));
            }
        @endif
        @if (auth()->user()->can('collateral.manage'))
            if (collateralOptions) {
                const row = document.createElement('div');
                row.className = 'mf-quick-collateral-row';
                row.innerHTML =
                    '<span class="text-xs text-muted-foreground">Select existing collateral or register a new item.</span>';
                row.appendChild(plusButton('collateral', 'Add collateral'));
                collateralOptions.parentNode.insertBefore(row, collateralOptions);
            }
        @endif

        const dialogs = {
            customer: document.getElementById('quick-customer-dialog'),
            guarantor: document.getElementById('quick-guarantor-dialog'),
            collateral: document.getElementById('quick-collateral-dialog')
        };
        document.addEventListener('click', e => {
            const open = e.target.closest('[data-quick-open]');
            if (open) {
                const kind = open.dataset.quickOpen;
                if ((kind === 'guarantor' || kind === 'collateral') && !loanCustomer?.value) {
                    alert('Select a customer first.');
                    return;
                }
                if (kind === 'customer' && loanBranch?.value) document.getElementById(
                    'quick-customer-branch').value = loanBranch.value;
                if (kind === 'guarantor') {
                    const f = document.getElementById('quick-guarantor-form');
                    f.action = f.dataset.actionTemplate.replace('__customer__', loanCustomer.value);
                }
                if (kind === 'collateral') {
                    document.getElementById('quick-collateral-customer').value = loanCustomer.value;
                    document.getElementById('quick-collateral-branch').value = loanBranch?.value ||
                        loanCustomer.selectedOptions[0]?.dataset.branch || '';
                }
                dialogs[kind]?.showModal();
            }
            if (e.target.closest('[data-quick-close]')) e.target.closest('dialog')?.close();
        });

        function showErrors(form, payload) {
            const box = form.querySelector('[data-quick-errors]');
            const messages = payload?.errors ? Object.values(payload.errors).flat() : [payload?.message ||
                'Unable to save.'
            ];
            box.innerHTML = messages.map(m =>
                `<div>${String(m).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]))}</div>`
                ).join('');
            box.classList.add('is-visible');
        }

        function clearErrors(form) {
            const box = form.querySelector('[data-quick-errors]');
            box.innerHTML = '';
            box.classList.remove('is-visible');
        }
        async function submitForm(form) {
            clearErrors(form);
            const response = await fetch(form.action, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrf
                },
                body: new FormData(form)
            });
            if (!response.ok) {
                let p = {};
                try {
                    p = await response.json();
                } catch {}
                showErrors(form, p);
                return null;
            }
            return response;
        }

        document.getElementById('quick-customer-form')?.addEventListener('submit', async e => {
            e.preventDefault();
            const form = e.currentTarget;
            const fd = new FormData(form);
            const response = await submitForm(form);
            if (!response) return;
            const match = response.url.match(/\/customers\/(\d+)(?:\?|$)/);
            if (!match) {
                showErrors(form, {
                    message: 'Customer was saved but could not be selected automatically. Refresh the page to continue.'
                });
                return;
            }
            const id = match[1],
                branchId = String(fd.get('branch_id') || ''),
                first = String(fd.get('first_name') || ''),
                middle = String(fd.get('middle_name') || ''),
                last = String(fd.get('last_name') || ''),
                phone = String(fd.get('phone') || '');
            const name = [first, middle, last].filter(Boolean).join(' ');
            const option = new Option(`${name} · ${phone}`, id, true, true);
            option.dataset.branch = branchId;
            loanCustomer.add(option);
            if (loanBranch) loanBranch.value = branchId;
            const qc = document.getElementById('quick-collateral-customer');
            if (qc) {
                const o = new Option(`${name} — ${phone}`, id);
                o.dataset.branch = branchId;
                qc.add(o);
            }
            loanCustomer.dispatchEvent(new Event('change', {
                bubbles: true
            }));
            dialogs.customer.close();
            form.reset();
        });

        document.getElementById('quick-guarantor-form')?.addEventListener('submit', async e => {
            e.preventDefault();
            const form = e.currentTarget;
            const response = await submitForm(form);
            if (!response) return;
            const payload = await response.json();
            const g = payload.guarantor;
            const option = new Option(`${g.full_name} · ${g.phone}`, g.id, true, true);
            option.dataset.customer = String(g.customer_id);
            loanGuarantor.add(option);
            dialogs.guarantor.close();
            form.reset();
        });

        document.getElementById('quick-collateral-form')?.addEventListener('submit', async e => {
            e.preventDefault();
            const form = e.currentTarget;
            const fd = new FormData(form);
            const response = await submitForm(form);
            if (!response) return;
            const match = response.url.match(/\/collateral\/(\d+)(?:\?|$)/);
            if (!match) {
                showErrors(form, {
                    message: 'Collateral was saved but could not be selected automatically. Refresh the page to continue.'
                });
                return;
            }
            const id = match[1],
                customerId = String(fd.get('customer_id') || ''),
                branchId = String(fd.get('branch_id') || ''),
                item = String(fd.get('item') || ''),
                status = String(fd.get('status') || ''),
                value = String(fd.get('accepted_value') || '0');
            const label = document.createElement('label');
            label.className = 'mf-option quick-created-collateral';
            label.dataset.customer = customerId;
            label.dataset.branch = branchId;
            label.innerHTML =
                `<input type="checkbox" name="collateral_ids[]" value="${id}" checked><span><strong>New collateral</strong><small class="block text-muted-foreground"></small></span>`;
            label.querySelector('small').textContent =
                `${item} · ${status.replaceAll('_',' ')} · value ${value||'0'}`;
            collateralOptions.append(label);
            dialogs.collateral.close();
            form.reset();
        });

        function filterQuickCollateral() {
            const customerId = loanCustomer?.value || '',
                branchId = loanBranch?.value || '';
            document.querySelectorAll('.quick-created-collateral').forEach(el => {
                el.hidden = (customerId && el.dataset.customer !== customerId) || (branchId && el
                    .dataset.branch !== branchId);
                if (el.hidden) el.querySelector('input').checked = false;
            });
        }
        loanCustomer?.addEventListener('change', filterQuickCollateral);
        loanBranch?.addEventListener('change', filterQuickCollateral);

        document.getElementById('quick_nin_lookup')?.addEventListener('click', async () => {
            const nin = document.getElementById('quick_nin').value.trim(),
                out = document.getElementById('quick_nin_result');
            if (!nin) {
                out.textContent = 'Enter a NIN first.';
                return;
            }
            out.textContent = 'Checking…';
            try {
                const r = await fetch(@json(route('customers.nin-lookup')), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': csrf
                    },
                    body: JSON.stringify({
                        nin
                    })
                });
                const p = await r.json();
                out.textContent = p.message || 'Lookup completed.';
                if (p.found && p.data) {
                    ['first_name', 'middle_name', 'last_name', 'gender', 'date_of_birth'].forEach(
                        k => {
                            const el = document.getElementById('quick_' + k);
                            if (p.data[k] && el) el.value = p.data[k];
                        });
                }
            } catch {
                out.textContent = 'Lookup unavailable. Continue with manual entry.';
            }
        });
    });
</script>
