@extends('admin.layouts.app')

@section('title', 'FILE APP PORTAL - Create Mapping')

@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">Create Mapping</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.5fr) minmax(0, 1.85fr); gap: 28px; align-items: flex-start; }
    .form-scroll { max-height: calc(100vh - 260px); overflow-y: auto; padding-right: 6px; }
    .field-group { margin-bottom: 14px; }
    .field-label { display: block; font-size: 13px; font-weight: 600; color: #475569; margin-bottom: 6px; }
    .field-label span { color: #d63031; }
    .input-text, .input-select {
        width: 100%; border-radius: 14px; border: 1px solid #cbd5e1; padding: 10px 14px;
        font-size: 14px; outline: none; background: #ffffff; transition: border-color 0.15s ease, box-shadow 0.15s ease;
    }
    .input-text:focus, .input-select:focus { border-color: #00ada8; box-shadow: 0 0 0 3px rgba(0, 173, 168, 0.16); background: #f8fafc; }
    .input-text::placeholder { color: #94a3b8; }
    .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; }
    .btn-secondary { background: #ffffff; color: #64748b; border: 2px solid #e2e8f0; }
    .btn-secondary:hover { background: #f8fafc; border-color: #cbd5e1; }
    .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;
        max-height: calc(100vh - 260px); overflow-y: auto;
    }
    .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; }
    .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;
    }
    .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;
    }
    .actions-row {
        display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;
        padding-top: 20px; border-top: 1px solid #e2e8f0;
    }
    @keyframes successPop {
        0% { transform: scale(0.6); opacity: 0; }
        60% { transform: scale(1.08); opacity: 1; }
        100% { transform: scale(1); opacity: 1; }
    }
    @keyframes successZoom {
        0% { transform: scale(0.9); opacity: 0; }
        100% { transform: scale(1); opacity: 1; }
    }
    @media (max-width: 900px) {
        .layout { grid-template-columns: minmax(0, 1fr); }
        .form-scroll { max-height: none; overflow-y: visible; }
        .result-panel { max-height: none; overflow-y: visible; }
    }
</style>
@endpush

@section('content')
    <div class="page">
        <header class="page-header">
            <div>
                <h1 class="page-title">Create Account – Lawyer Mapping</h1>
                <p class="page-subtitle">Review account and lawyer details, capture legal case information, then create the mapping.</p>
            </div>
        </header>

        <section class="layout">
            <!-- Left: Case details form -->
            <form id="createForm" class="form-scroll">
                <div class="field-group">
                    <label class="field-label" for="assignDate">Assign Date <span>*</span></label>
                    <input type="date" id="assignDate" class="input-text" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="submittedDate">Case Submitted Date <span>*</span></label>
                    <input type="date" id="submittedDate" class="input-text" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="registrationVia">Case Registration Via <span>*</span></label>
                    <input type="text" id="registrationVia" class="input-text" placeholder="Enter (e.g. E-Case, Court Portal, Physical)" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="courtFee">Court Fee <span>*</span></label>
                    <input type="number" step="0.001" id="courtFee" class="input-text" placeholder="Enter amount" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="caseFiledDate">Case Filed Date <span>*</span></label>
                    <input type="date" id="caseFiledDate" class="input-text" required />
                </div>
                <div class="field-group">
                    <label class="field-label" for="remarks">Internal Remarks</label>
                    <textarea id="remarks" rows="3" class="input-text" style="border-radius:16px;resize:none;" placeholder="Optional notes for internal tracking"></textarea>
                </div>
            </form>

            <!-- Right: Summary cards -->
            <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="summaryAccountId"></span></div>
                            <div class="summary-meta mt-1">Account Name: <span id="summaryAccountName"></span></div>
                        </div>
                        <button class="detail-btn" type="button">
                            <i class="fa-solid fa-circle-check text-[10px]"></i> Account Details
                        </button>
                    </header>
                </section>

                <!-- Lawyers summary -->
                <div id="lawyersSummary"></div>

                <div class="actions-row">
                    <button type="button" class="btn btn-secondary" id="btnCancel">Cancel</button>
                    <button type="button" class="btn btn-primary" id="btnCreate">Create Mapping</button>
                </div>
            </aside>
        </section>
    </div>

    <!-- Success Modal -->
    <div id="successModal" style="position:fixed;inset:0;z-index:500;display:none;align-items:center;justify-content:center;padding:16px;">
        <div style="position:absolute;inset:0;background:rgba(15,23,42,0.5);backdrop-filter:blur(6px);"></div>
        <div style="position:relative;background:#fff;padding:46px 40px 38px;border-radius:2.5rem;box-shadow:0 22px 60px rgba(0,0,0,0.25);max-width:520px;width:100%;text-align:center;animation:successZoom 0.4s ease-out forwards;">
            <div style="width:80px;height:80px;border-radius:50%;background:radial-gradient(circle at top left,#00ada8 0%,#007d79 100%);box-shadow:0 20px 40px rgba(0,125,121,0.4);display:flex;align-items:center;justify-content:center;margin:0 auto;animation:successPop 0.6s cubic-bezier(0.175,0.885,0.32,1.275) forwards;">
                <i class="fa-solid fa-check text-white text-3xl"></i>
            </div>
            <h1 style="margin-top:32px;font-size:24px;font-weight:900;color:#1e293b;letter-spacing:-0.02em;">Lawyer Assigned Successfully</h1>
            <p style="margin-top:12px;font-size:11px;font-weight:900;color:#94a3b8;text-transform:uppercase;letter-spacing:0.2em;">
                Account No: <span id="successAccountNo" style="color:#00ada8;margin-left:4px;"></span>
            </p>
            <button id="btnDone" type="button" style="margin-top:36px;display:inline-flex;align-items:center;justify-content:center;border-radius:999px;padding:11px 40px;border:none;cursor:pointer;font-size:15px;font-weight:600;background:radial-gradient(circle at top left,#062a27 0%,#0f172a 45%,#1e293b 100%);color:#fff;box-shadow:0 12px 30px rgba(15,23,42,0.45);transition:transform 0.08s ease;">
                Done
            </button>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    const CSRF_TOKEN = '{{ csrf_token() }}';
    const STORE_URL  = '{{ route("admin.account-lawyer.store") }}';
    const INDEX_URL  = '{{ route("admin.account-lawyer.index") }}';
    const BACK_URL   = '{{ route("admin.account-lawyer.search-lawyer") }}';

    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);

    let lawyers = [];
    try { lawyers = JSON.parse(@json($lawyers) || '[]'); } catch(e) {}

    // Populate account summary
    document.getElementById('summaryAccountId').textContent   = accountNo;
    document.getElementById('summaryAccountName').textContent = customerName;

    // Render lawyers
    const lawyersSummary = document.getElementById('lawyersSummary');
    lawyers.forEach(l => {
        const initials = (l.name || 'L').split(' ').map(w => w[0]).join('').substring(0, 2).toUpperCase();
        const div = document.createElement('div');
        div.className = 'lawyer-chip';
        div.style.marginBottom = '10px';
        div.innerHTML = `
            <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>` : ''}
            </div>
            <button class="detail-btn" type="button" style="flex-shrink:0;">
                <i class="fa-solid fa-circle-check text-[10px]"></i> Lawyer Details
            </button>
        `;
        lawyersSummary.appendChild(div);
    });

    // Cancel
    document.getElementById('btnCancel').addEventListener('click', () => {
        const url = new URL(BACK_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);
        window.location.href = url.toString();
    });

    // Create
    document.getElementById('btnCreate').addEventListener('click', async () => {
        const form = document.getElementById('createForm');
        if (!form.reportValidity()) return;

        const btn = document.getElementById('btnCreate');
        btn.disabled = true;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i> Creating...';

        const payload = new FormData();
        payload.append('_token',                CSRF_TOKEN);
        payload.append('loan_id',               accountNo);
        payload.append('customer_name',         customerName);
        payload.append('principal_os_amount',   principal);
        payload.append('odi_amount',            odi);
        payload.append('crc_amount',            crc);
        payload.append('statement_date',        stmtDate);
        payload.append('statement_amount',      stmtAmount);
        payload.append('assign_date',           document.getElementById('assignDate').value);
        payload.append('case_submitted_date',   document.getElementById('submittedDate').value);
        payload.append('case_registration_via', document.getElementById('registrationVia').value);
        payload.append('court_fee',             document.getElementById('courtFee').value);
        payload.append('case_filed_date',       document.getElementById('caseFiledDate').value);
        payload.append('internal_remarks',      document.getElementById('remarks').value);
        payload.append('lawyers',               JSON.stringify(lawyers));

        try {
            const res  = await fetch(STORE_URL, { method: 'POST', body: payload, headers: { 'Accept': 'application/json' } });
            const data = await res.json();

            if (data.success) {
                document.getElementById('successAccountNo').textContent = accountNo;
                const modal = document.getElementById('successModal');
                modal.style.display = 'flex';
                document.getElementById('btnDone').addEventListener('click', () => {
                    window.location.href = INDEX_URL;
                });
            } else {
                const err = data.errors ? Object.values(data.errors)[0]?.[0] : (data.message || 'Something went wrong.');
                alert(err);
            }
        } catch (e) {
            alert('Request failed. Please try again.');
        } finally {
            btn.disabled = false;
            btn.innerHTML = 'Create Mapping';
        }
    });
</script>
@endpush
