@php
    /** @var \App\Models\Sale\SaleInvoice|null $invoice — null ise "Yeni Fatura" (quick-create) modu */
    $isEdit = $invoice !== null;
    $snap = $isEdit ? ($invoice->billing_snapshot ?? []) : [];
    $qvTitle = $isEdit ? $invoice->invoice_number : 'Yeni Fatura';
@endphp

<x-quick-view.layout class="qv-invoices-wrapper">

    <x-quick-view.header>
        <x-slot:avatar class="finvqv-avatar">
            <i class="fas fa-file-invoice-dollar"></i>
        </x-slot:avatar>

        <x-slot:title>
            {{ $qvTitle }}
            @if($isEdit)
                <span class="finvqv-status" style="--sc: {{ $invoice->status_color }};">{{ $invoice->status_label }}</span>
                @if($invoice->official_status === 'pending' && $invoice->status !== 'cancelled')
                    <span class="finvqv-official pending" title="Resmi fatura henüz kesilmedi!"><i class="fas fa-hourglass-half"></i> Resmi: Bekliyor</span>
                @else
                    <span class="finvqv-official" style="--sc: {{ $invoice->official_status_color }};">Resmi: {{ $invoice->official_status_label }}</span>
                @endif
            @endif
        </x-slot:title>

        <x-slot:subtitle>
            <span class="text-muted fw-semibold" style="font-size:.82rem;">
                @if($isEdit)
                    @if($invoice->customer_id)
                        {{-- Muhatap → müşteri kartı --}}
                        <a href="javascript:void(0)" class="finvqv-cust-link" title="Müşteri kartını aç"
                           onclick="openCustomerDrawer({{ $invoice->customer_id }})"><i class="fas fa-user-tag me-1"></i>{{ $invoice->billing_name }}</a>
                    @else
                        <i class="fas fa-user-tag me-1"></i>{{ $invoice->billing_name }}
                    @endif
                    <span class="mx-1 opacity-50">•</span>
                    <i class="fas fa-calendar-day me-1"></i>{{ $invoice->issue_date?->format('d.m.Y') }}
                    @if($invoice->sale_id)
                        <span class="mx-1 opacity-50">•</span>
                        {{-- Bağlı satış → satış kartı --}}
                        <a href="javascript:void(0)" class="finvqv-tag finvqv-tag-link" title="Satış kartını aç"
                           onclick="openSaleDrawer({{ $invoice->sale_id }})"><i class="fas fa-receipt me-1"></i>Satış #{{ $invoice->sale?->sale_code ?? $invoice->sale_id }}</a>
                    @endif
                @else
                    <i class="fas fa-wand-magic-sparkles me-1"></i>Muhatabı seçin, kalemleri girin — kaydedince önizleyip PDF indirebilirsiniz.
                @endif
            </span>
        </x-slot:subtitle>

        <x-slot:actions>
            @if($isEdit)
                @if($invoice->official_status === 'pending' && $invoice->status !== 'cancelled')
                    <button type="button" class="finvqv-issue-btn" onclick="finvQvIssueOfficial()" title="Resmi faturayı kes (entegrasyon bağlanana kadar durumu günceller)">
                        <i class="fas fa-stamp"></i> Faturayı Kes
                    </button>
                @endif
                <a href="{{ route('agency.invoices.preview', $invoice) }}" target="_blank" class="qv-action-btn" title="Önizle"><i class="fas fa-eye"></i></a>
                <a href="{{ route('agency.invoices.download', $invoice) }}" class="qv-action-btn" title="PDF indir"><i class="fas fa-file-arrow-down"></i></a>
            @endif
        </x-slot:actions>
    </x-quick-view.header>

    <x-quick-view.content>
        <div class="finvqv-body">
            <input type="hidden" id="finvId" value="{{ $invoice?->id ?? '' }}">
            <input type="hidden" id="finvCustomerId" value="{{ $invoice?->customer_id ?? '' }}">
            <input type="hidden" id="finvSaleId" value="{{ $invoice?->sale_id ?? '' }}">

            <!-- Meta -->
            <div class="finv-m-grid5">
                <div class="finv-field">
                    <label>Fatura No *</label>
                    <input type="text" id="finvNumber" maxlength="100" value="{{ $isEdit ? $invoice->invoice_number : $nextNumber }}">
                </div>
                <div class="finv-field">
                    <label>Tür</label>
                    <select id="finvType">
                        @foreach(\App\Models\Sale\SaleInvoice::TYPES as $tv => $tl)
                            <option value="{{ $tv }}" @selected($isEdit && $invoice->invoice_type === $tv)>{{ $tl }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="finv-field">
                    <label>Kesim Tarihi *</label>
                    <input type="date" id="finvDate" value="{{ $isEdit ? $invoice->issue_date?->format('Y-m-d') : now()->format('Y-m-d') }}">
                </div>
                <div class="finv-field">
                    <label>Para Birimi</label>
                    <select id="finvCurrency">
                        @foreach($currencies as $curr)
                            <option value="{{ $curr->code }}" @selected($isEdit ? $invoice->currency === $curr->code : $curr->code === 'TRY')>{{ $curr->code }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="finv-field">
                    <label>Durum</label>
                    <select id="finvStatus">
                        @foreach(\App\Models\Sale\SaleInvoice::STATUSES as $sv => $sl)
                            <option value="{{ $sv }}" @selected($isEdit ? $invoice->status === $sv : $sv === 'issued')>{{ $sl }}</option>
                        @endforeach
                    </select>
                </div>
            </div>

            @if(!$isEdit)
            <!-- Satıştan fatura kes: muhatap ve kalemler otomatik dolar -->
            <div class="finv-section finv-salepick">
                <div class="finv-section-head">
                    <span><i class="fas fa-cart-shopping me-2"></i>Satıştan Fatura Kes <small>(isteğe bağlı)</small></span>
                    <span class="finv-holdhint"><i class="fas fa-hand-pointer"></i> Tıkla: faturaya bağla · <b>Basılı tut:</b> satış kartını aç</span>
                </div>

                <div class="finv-cust-search" id="finvSaleSearchWrap">
                    <i class="fas fa-magnifying-glass"></i>
                    <input type="text" id="finvSaleInput" placeholder="Satış ara (no, başlık, müşteri)… — faturasız satışlar üstte" autocomplete="off">
                    <div class="finv-cust-results finv-sale-results" id="finvSaleResults" hidden></div>
                </div>

                <div class="finv-sale-chosen" id="finvSaleChosen" hidden>
                    <span class="finv-sale-ic"><i class="fas fa-receipt"></i></span>
                    <div class="finv-sale-txt">
                        <b id="finvSaleChosenTitle">—</b>
                        <small id="finvSaleChosenSub">—</small>
                    </div>
                    <button type="button" class="finv-sale-open" id="finvSaleOpen" title="Satış kartını aç"><i class="fas fa-arrow-up-right-from-square"></i></button>
                    <button type="button" class="finv-sale-x" id="finvSaleClear" title="Bağı kaldır"><i class="fas fa-xmark"></i></button>
                </div>
            </div>
            @endif

            <!-- Muhatap -->
            <div class="finv-section">
                <div class="finv-section-head">
                    <span><i class="fas fa-user-tag me-2"></i>Fatura Muhatabı</span>
                    <div class="finv-btype-toggle" id="finvBillingToggle">
                        <button type="button" class="on" data-type="individual"><i class="fas fa-id-card me-1"></i>Şahıs (TC)</button>
                        <button type="button" data-type="company"><i class="fas fa-building me-1"></i>Şirket</button>
                    </div>
                </div>

                <div class="finv-cust-search">
                    <i class="fas fa-magnifying-glass"></i>
                    <input type="text" id="finvCustInput" placeholder="Müşteri ara (ad, şirket, telefon, TC)… — bilgiler otomatik dolar" autocomplete="off">
                    <div class="finv-cust-results" id="finvCustResults" hidden></div>
                </div>
                <div class="finv-hint" id="finvTcHint" hidden>
                    <i class="fas fa-circle-info"></i> Bu müşterinin şirket fatura bilgisi eksik — fatura <b>TC kimlik numarasına (şahıs)</b> kesilecek.
                </div>

                <div class="finv-m-grid3 mt-2">
                    <div class="finv-field" id="finvCompanyNameField" hidden>
                        <label>Şirket Unvanı</label>
                        <input type="text" id="finvBCompany" maxlength="255" value="{{ $snap['company_name'] ?? '' }}">
                    </div>
                    <div class="finv-field">
                        <label>Ad Soyad</label>
                        <input type="text" id="finvBName" maxlength="255" value="{{ $snap['name'] ?? '' }}">
                    </div>
                    <div class="finv-field">
                        <label id="finvTaxNoLabel">TC Kimlik No</label>
                        <input type="text" id="finvBTaxNo" maxlength="50" value="{{ $snap['tax_number'] ?? '' }}">
                    </div>
                    <div class="finv-field" id="finvTaxOfficeField" hidden>
                        <label>Vergi Dairesi</label>
                        <input type="text" id="finvBTaxOffice" maxlength="255" value="{{ $snap['tax_office'] ?? '' }}">
                    </div>
                    <div class="finv-field">
                        <label>Telefon</label>
                        <input type="text" id="finvBPhone" maxlength="50" value="{{ $snap['phone'] ?? '' }}">
                    </div>
                    <div class="finv-field">
                        <label>E-posta</label>
                        <input type="text" id="finvBEmail" maxlength="255" value="{{ $snap['email'] ?? '' }}">
                    </div>
                    <div class="finv-field" style="grid-column: 1 / -1;">
                        <label>Adres</label>
                        <input type="text" id="finvBAddress" maxlength="1000" value="{{ $snap['address'] ?? '' }}">
                    </div>
                </div>
            </div>

            <!-- Kalemler -->
            <div class="finv-section">
                <div class="finv-section-head">
                    <span><i class="fas fa-list-ul me-2"></i>Fatura Kalemleri</span>
                    <button type="button" class="finv-mini" onclick="finvAddItem()"><i class="fas fa-plus"></i> Kalem Ekle</button>
                </div>
                <div class="table-responsive">
                    <table class="table align-middle mb-2" style="min-width: 760px;">
                        <thead>
                            <tr class="finv-thead sm">
                                <th>Açıklama</th>
                                <th class="text-center" style="width:80px;">Adet</th>
                                <th class="text-end" style="width:120px;">Birim Fiyat</th>
                                <th class="text-center" style="width:130px;">İndirim</th>
                                <th class="text-center" style="width:90px;">KDV %</th>
                                <th class="text-end" style="width:120px;">Tutar</th>
                                <th style="width:34px;"></th>
                            </tr>
                        </thead>
                        <tbody id="finvItems"></tbody>
                    </table>
                </div>

                <div class="d-flex justify-content-end">
                    <div class="finv-totals">
                        <div><span>Ara Toplam</span><b id="finvTSub">0,00</b></div>
                        <div class="disc"><span>İndirim</span><b id="finvTDisc">−0,00</b></div>
                        <div><span>KDV</span><b id="finvTTax">0,00</b></div>
                        <div class="grand"><span>Genel Toplam</span><b id="finvTGrand">0,00</b></div>
                    </div>
                </div>
            </div>

            <div class="finv-field">
                <label>Notlar <small>(ops. — şablondaki notlar alanında görünür)</small></label>
                <input type="text" id="finvNotes" maxlength="1000" placeholder="Örn: e-Arşiv, GİB no…" value="{{ $invoice?->notes ?? '' }}">
            </div>

            {{-- Zengin metin açıklama: hizmet kapsamı, koşullar… şablonda "aciklama" tokenıyla basılır --}}
            <div class="finv-field">
                <label>Açıklama <small>(ops. — biçimlendirilebilir; fatura şablonunda <code>&#123;&#123;aciklama&#125;&#125;</code> ile basılır)</small></label>
                <div class="finv-rte">
                    <div id="finvDescEditor"></div>
                </div>
            </div>

            @if($isEdit)
                <!-- Tahsilat durumu: ödemeler defterinden beslenir -->
                <div class="finvqv-payments">
                    <div class="finvqv-payhead">
                        <span><i class="fas fa-money-bill-transfer"></i> Tahsilat</span>
                        <span class="finvqv-paybar">
                            @php
                                $paidRatio = (float) $invoice->amount > 0
                                    ? min(100, round((float) $invoice->paid_amount / (float) $invoice->amount * 100))
                                    : 0;
                            @endphp
                            <span class="finvqv-paybar-fill" style="width: {{ $paidRatio }}%"></span>
                        </span>
                        <b>{{ number_format((float) $invoice->paid_amount, 2, ',', '.') }} / {{ number_format((float) $invoice->amount, 2, ',', '.') }} {{ $invoice->currency }}</b>
                    </div>
                    @include('agency.payments.partials.payment-list', [
                        'payments' => $invoice->payments()->withCount('documents')->get(),
                        'createUrl' => route('agency.payments.quick-create', array_filter([
                            'sale' => $invoice->sale_id,
                            'invoice' => $invoice->id,
                            'direction' => 'in',
                            'amount' => $invoice->remaining_amount ?: null,
                        ])),
                        'emptyText' => 'Bu faturaya işlenmiş tahsilat yok. Ödeme eklediğinizde fatura otomatik kapanır.',
                    ])
                </div>
            @endif

            <!-- Alt aksiyon çubuğu -->
            <div class="finvqv-foot">
                <button type="button" class="finv-btn ghost" onclick="closeQuickView()">Vazgeç</button>
                <button type="button" class="finv-btn solid" id="finvSubmit" onclick="finvSubmit()">
                    <i class="fas fa-file-circle-check"></i> <span id="finvSubmitText">{{ $isEdit ? 'Değişiklikleri Kaydet' : 'Faturayı Kes' }}</span>
                </button>
            </div>
        </div>
    </x-quick-view.content>
</x-quick-view.layout>

<style>
    .qv-invoices-wrapper { font-family: 'Manrope', 'Inter', system-ui, sans-serif; }
    .finvqv-avatar { background: linear-gradient(135deg, #059669, #047857) !important; box-shadow: 0 10px 25px rgba(5, 150, 105, .25) !important; font-size: 1.5rem !important; }
    .finvqv-status {
        font-size: .68rem; font-weight: 800; padding: 3px 12px; border-radius: 999px; vertical-align: middle;
        color: var(--sc); background: color-mix(in srgb, var(--sc) 10%, white); border: 1px solid color-mix(in srgb, var(--sc) 28%, white);
    }
    .finvqv-tag { display: inline-block; font-size: .68rem; font-weight: 800; padding: 1px 8px; border-radius: 999px; color: #4f46e5; background: #eef2ff; }
    /* Çapraz linkler: satış rozeti ve muhatap adı tıklanabilir */
    .finvqv-tag-link { text-decoration: none; transition: all .15s; }
    .finvqv-tag-link:hover { color: #fff; background: #4f46e5; }
    .finvqv-cust-link { color: #059669; font-weight: 700; text-decoration: none; border-bottom: 1px dotted #a7f3d0; transition: all .15s; }
    .finvqv-cust-link:hover { color: #047857; border-bottom-color: #047857; }
    .finvqv-official {
        display: inline-flex; align-items: center; gap: 5px; font-size: .66rem; font-weight: 800; padding: 3px 11px; border-radius: 999px; vertical-align: middle;
        color: var(--sc, #64748b); background: color-mix(in srgb, var(--sc, #64748b) 10%, white); border: 1px solid color-mix(in srgb, var(--sc, #64748b) 28%, white);
    }
    .finvqv-official.pending {
        color: #92400e; background: #fef3c7; border: 1px solid #fcd34d;
        animation: finvqvPulse 2.2s ease-in-out infinite;
    }
    @keyframes finvqvPulse {
        0%, 100% { box-shadow: 0 0 0 0 rgba(217, 119, 6, .35); }
        50% { box-shadow: 0 0 0 5px rgba(217, 119, 6, 0); }
    }
    .finvqv-issue-btn {
        display: inline-flex; align-items: center; gap: 6px; border: none; cursor: pointer;
        font-family: inherit; font-size: .76rem; font-weight: 800; padding: .55rem 1rem; border-radius: 12px;
        color: white; background: linear-gradient(135deg, #d97706, #b45309);
        box-shadow: 0 8px 18px -8px rgba(217, 119, 6, .6); transition: all .16s ease; white-space: nowrap;
    }
    .finvqv-issue-btn:hover { transform: translateY(-1px); filter: brightness(1.08); }

    /* Kart drawer genişliğini tam kullanır; sağda boşluk kalmasın */
    .finvqv-body { padding: 1.4rem 2.5rem 2rem; display: flex; flex-direction: column; gap: 1rem; width: 100%; }
    /* Zengin metin açıklama */
    .finv-rte { border: 1.5px solid #e2e8f0; border-radius: 10px; overflow: hidden; background: #fff; }
    .finv-rte .ql-toolbar.ql-snow { border: none; border-bottom: 1px solid #eef2f7; background: #f8fafc; }
    .finv-rte .ql-container.ql-snow { border: none; }
    .finv-rte .ql-editor { min-height: 110px; font-size: .88rem; line-height: 1.6; color: #334155; }
    .finv-rte .ql-editor.ql-blank::before { color: #b6bfd0; font-style: normal; }
    .finv-field label code { background: #f1f5f9; border-radius: 5px; padding: 0 4px; font-size: .9em; }

    /* Satış seçici */
    .finv-salepick .finv-section-head small { font-weight: 600; color: #94a3b8; font-size: .72rem; }
    .finv-sale-results { max-height: 340px; }
    .finv-sale-row { align-items: center; gap: .6rem; }
    .finv-sale-amount {
        font-family: 'JetBrains Mono', monospace; font-size: .78rem; font-weight: 700; color: #0f172a; white-space: nowrap;
    }
    .finv-sbadge {
        font-size: .63rem; font-weight: 800; padding: 3px 8px; border-radius: 999px; white-space: nowrap; flex-shrink: 0;
    }
    .finv-sbadge.none { background: #ecfdf5; color: #047857; border: 1px solid #a7f3d0; }
    .finv-sbadge.has { background: #fffbeb; color: #b45309; border: 1px solid #fde68a; }
    .finv-sbadge.official { background: #eef2ff; color: #4338ca; border: 1px solid #c7d2fe; }
    .finv-sale-empty { padding: .9rem; text-align: center; font-size: .8rem; color: #94a3b8; }
    .finv-holdhint { font-size: .68rem; font-weight: 600; color: #94a3b8; white-space: nowrap; }
    .finv-holdhint i { margin-right: 4px; color: #cbd5e1; }
    .finv-holdhint b { color: #059669; }

    /* Basılı tutma geri bildirimi: satır hafifçe içeri çöker ve yeşil şerit dolar */
    .finv-sale-row { position: relative; user-select: none; overflow: hidden; }
    .finv-sale-row.is-holding { background: #f0fdf4; transform: scale(.995); }
    .finv-sale-row.is-holding::after {
        content: ''; position: absolute; left: 0; bottom: 0; height: 2px; width: 0;
        background: linear-gradient(90deg, #34d399, #059669);
        animation: finvHold .42s linear forwards;
    }
    @keyframes finvHold { to { width: 100%; } }

    .finv-sale-chosen {
        display: flex; align-items: center; gap: .7rem; padding: .65rem .8rem;
        background: #f0fdf4; border: 1.5px solid #a7f3d0; border-radius: 12px;
    }
    .finv-sale-chosen[hidden] { display: none; }
    .finv-sale-ic {
        width: 32px; height: 32px; flex: none; border-radius: 10px; display: grid; place-items: center;
        background: #dcfce7; color: #059669; font-size: .82rem;
    }
    .finv-sale-txt { flex: 1; min-width: 0; }
    .finv-sale-txt b { display: block; font-size: .84rem; font-weight: 700; color: #0f172a; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .finv-sale-txt small { display: block; font-size: .7rem; color: #64748b; }
    .finv-sale-open, .finv-sale-x {
        width: 28px; height: 28px; flex: none; border-radius: 9px; display: grid; place-items: center;
        border: 1px solid #d1fae5; background: #fff; color: #64748b; cursor: pointer; font-size: .72rem; transition: .15s;
    }
    .finv-sale-open:hover { color: #059669; border-color: #6ee7b7; }
    .finv-sale-x:hover { color: #dc2626; border-color: #fca5a5; background: #fef2f2; }

    /* Tahsilat bloğu */
    .finvqv-payments { margin: 1.1rem 0; padding-top: 1rem; border-top: 1px solid #f1f5f9; }
    .finvqv-payhead { display: flex; align-items: center; gap: .8rem; margin-bottom: .8rem; font-size: .8rem; font-weight: 800; color: #334155; }
    .finvqv-payhead i { color: #059669; margin-right: 5px; }
    .finvqv-payhead b { font-family: 'JetBrains Mono', monospace; font-size: .82rem; color: #0f172a; white-space: nowrap; }
    .finvqv-paybar { flex: 1; height: 7px; border-radius: 999px; background: #eef2f7; overflow: hidden; min-width: 60px; }
    .finvqv-paybar-fill { display: block; height: 100%; border-radius: 999px; background: linear-gradient(90deg, #10b981, #059669); transition: width .3s ease; }

    .finvqv-foot { display: flex; justify-content: flex-end; gap: .6rem; padding-top: .5rem; border-top: 1px solid #f1f5f9; }

    .finv-btn {
        display: inline-flex; align-items: center; gap: .5rem; border: none; cursor: pointer; text-decoration: none;
        font-family: inherit; font-size: .84rem; font-weight: 800; padding: .62rem 1.3rem; border-radius: 12px; transition: all .18s ease;
    }
    .finv-btn.solid { background: linear-gradient(135deg, #059669, #047857); color: white; box-shadow: 0 10px 22px -10px rgba(5, 150, 105, .6); }
    .finv-btn.solid:hover { transform: translateY(-1px); filter: brightness(1.07); color: white; }
    .finv-btn.ghost { background: white; border: 1px solid #e2e8f0; color: #64748b; }
    .finv-btn.ghost:hover { color: #0f172a; background: #f8fafc; }

    .finv-field label { display: block; font-size: .62rem; font-weight: 800; letter-spacing: .09em; text-transform: uppercase; color: #94a3b8; margin-bottom: 4px; }
    .finv-field label small { text-transform: none; letter-spacing: 0; font-weight: 600; }
    .finv-field input, .finv-field select {
        width: 100%; border: 1px solid #e2e8f0; border-radius: 10px; padding: 7px 11px;
        font-size: .82rem; font-family: inherit; color: #1e293b; background: #fbfcfe; outline: none; transition: all .16s ease;
    }
    .finv-field input:focus, .finv-field select:focus { border-color: #34d399; background: white; box-shadow: 0 0 0 3px rgba(52, 211, 153, .14); }

    .finv-m-grid5 { display: grid; grid-template-columns: 1.3fr 1fr 1fr .8fr 1fr; gap: 10px; }
    .finv-m-grid3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
    @media (max-width: 900px) { .finv-m-grid5, .finv-m-grid3 { grid-template-columns: 1fr 1fr; } }

    .finv-section { border: 1px solid #e8edf4; border-radius: 14px; padding: 14px 16px; background: white; }
    .finv-section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; font-size: .8rem; font-weight: 800; color: #334155; }
    .finv-section-head i { color: #059669; }

    .finv-btype-toggle { display: inline-flex; background: #f1f5f9; border-radius: 10px; padding: 3px; gap: 3px; }
    .finv-btype-toggle button {
        border: none; background: transparent; font-family: inherit; font-size: .74rem; font-weight: 800;
        color: #64748b; padding: .35rem .85rem; border-radius: 8px; cursor: pointer; transition: all .15s ease;
    }
    .finv-btype-toggle button.on { background: white; color: #065f46; box-shadow: 0 2px 6px rgba(15, 23, 42, .08); }

    .finv-cust-search { position: relative; }
    .finv-cust-search > i { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: .8rem; }
    .finv-cust-search input {
        width: 100%; border: 1.5px dashed #cbd5e1; border-radius: 11px; padding: 9px 12px 9px 34px;
        font-size: .84rem; font-family: inherit; background: #fbfcfe; outline: none; transition: all .16s ease;
    }
    .finv-cust-search input:focus { border-color: #34d399; border-style: solid; background: white; box-shadow: 0 0 0 3px rgba(52, 211, 153, .14); }
    .finv-cust-results {
        position: absolute; top: calc(100% + 4px); left: 0; right: 0; z-index: 30;
        background: white; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden;
        box-shadow: 0 18px 40px -12px rgba(15, 23, 42, .2); max-height: 260px; overflow-y: auto;
    }
    .finv-cust-row { display: flex; align-items: center; gap: .6rem; padding: .55rem .8rem; cursor: pointer; transition: background .12s; }
    .finv-cust-row:hover { background: #f0fdf4; }
    .finv-cust-row b { font-size: .8rem; color: #0f172a; }
    .finv-cust-row small { font-size: .68rem; color: #94a3b8; display: block; }

    .finv-btype { width: 30px; height: 30px; border-radius: 9px; display: inline-flex; align-items: center; justify-content: center; font-size: .74rem; flex-shrink: 0; }
    .finv-btype.company { color: #4f46e5; background: #eef2ff; }
    .finv-btype.individual { color: #059669; background: #ecfdf5; }

    .finv-hint {
        margin-top: 8px; font-size: .74rem; font-weight: 600; color: #92400e;
        background: #fffbeb; border: 1px dashed #fcd34d; border-radius: 10px; padding: .5rem .75rem;
    }
    .finv-hint i { margin-right: .3rem; }

    .finv-mini {
        display: inline-flex; align-items: center; gap: .35rem; border: 1px solid #e2e8f0; background: white;
        color: #059669; font-size: .72rem; font-weight: 800; padding: .32rem .75rem; border-radius: 9px;
        cursor: pointer; transition: all .15s ease; font-family: inherit;
    }
    .finv-mini:hover { background: #ecfdf5; border-color: #a7f3d0; }

    .finv-thead.sm th {
        font-size: .64rem; text-transform: uppercase; letter-spacing: .06em; color: #64748b;
        background: #f8fafc; border-bottom: 2px solid #eef2f7; padding: 8px 10px; font-weight: 800;
    }
    #finvItems td { padding: 6px 8px; border-bottom: 1px solid #f1f5f9; }
    #finvItems input, #finvItems select {
        width: 100%; border: 1px solid #e8edf4; border-radius: 8px; padding: 5px 8px;
        font-size: .8rem; font-family: inherit; background: #fbfcfe; outline: none;
    }
    #finvItems input:focus, #finvItems select:focus { border-color: #34d399; background: white; }
    .finv-item-total { font-family: 'JetBrains Mono', monospace; font-weight: 600; font-size: .8rem; color: #0f172a; text-align: right; display: block; }
    .finv-item-x { border: none; background: transparent; color: #cbd5e1; cursor: pointer; font-size: .78rem; }
    .finv-item-x:hover { color: #dc2626; }

    .finv-totals { width: 280px; font-size: .82rem; }
    .finv-totals > div { display: flex; justify-content: space-between; padding: 4px 2px; }
    .finv-totals b { font-family: 'JetBrains Mono', monospace; font-weight: 600; }
    .finv-totals .disc { color: #e11d48; }
    .finv-totals .grand { border-top: 2px solid #065f46; margin-top: 4px; padding-top: 8px; font-size: .95rem; font-weight: 800; color: #065f46; }
</style>

<script>
    // Fatura quick-view/quick-create — kart her enjekte edildiğinde yeniden tanımlanır.
    // Aktif olmayan kartların id'leri drawer tarafından soyulur; getElementById hep aktif kartı bulur.
    window.FINV = {
        storeUrl: "{{ route('agency.invoices.store') }}",
        searchUrl: "{{ route('agency.invoices.customers.search') }}",
        saleSearchUrl: "{{ route('agency.invoices.sales.search') }}",
        baseUrl: "{{ url('agency/invoices') }}",
        csrf: document.querySelector('meta[name="csrf-token"]')?.content || "{{ csrf_token() }}",
        taxRates: @json($taxRates->map(fn ($t) => (float) $t->rate)->values()),
        billingType: @json($isEdit ? ($invoice->billing_type ?? 'individual') : 'individual'),
        customerBilling: null,
        editId: @json($invoice?->id),
        selfUrl: @json($isEdit ? '/agency/invoices/' . $invoice->id . '/quick-view' : '/agency/invoices/quick-create'),
        initialItems: @json($isEdit ? ($invoice->items ?? []) : []),
        description: @json($invoice->description ?? ''),
        descEditor: null,
        prefillSaleId: @json($prefillSaleId ?? null),
    };

    // ── Muhatap tipi ──
    function setBillingType(type) {
        FINV.billingType = type;
        document.querySelectorAll('#finvBillingToggle button').forEach(b => b.classList.toggle('on', b.dataset.type === type));
        const isCompany = type === 'company';
        const cnf = document.getElementById('finvCompanyNameField');
        const tof = document.getElementById('finvTaxOfficeField');
        const lbl = document.getElementById('finvTaxNoLabel');
        const hint = document.getElementById('finvTcHint');
        if (cnf) cnf.hidden = !isCompany;
        if (tof) tof.hidden = !isCompany;
        if (lbl) lbl.textContent = isCompany ? 'Vergi No' : 'TC Kimlik No';
        if (hint) hint.hidden = true;

        if (FINV.customerBilling) {
            if (isCompany && !FINV.customerBilling.company) {
                if (hint) hint.hidden = false;
                setBillingType('individual');
                return;
            }
            applyBilling(isCompany ? FINV.customerBilling.company : FINV.customerBilling.individual);
        }
    }

    /**
     * Muhatap seçenekleri: kurumsal profiller (müşterinin kendi şirket kartı
     * ya da bağlı olduğu şirketler) + şahıs profili. Butonlar sunucudan gelen
     * listeye göre yeniden çizilir; vergi bilgisi eksik olan kurumsal seçenek
     * uyarıyla işaretlenir ve varsayılan şahsa (TC) düşer.
     */
    function applyProfiles(profiles, suggestedKey) {
        const bar = document.getElementById('finvBillingToggle');
        if (!bar || !profiles?.length) return;

        FINV.profiles = profiles;
        bar.innerHTML = profiles.map(p => {
            const label = p.type === 'company'
                ? (p.label.length > 22 ? p.label.slice(0, 22) + '…' : p.label)
                : 'Şahıs (TC)';
            const icon = p.type === 'company' ? 'fa-building' : 'fa-id-card';
            const warn = p.complete ? '' : ' <i class="fas fa-triangle-exclamation" title="Vergi/TC numarası eksik"></i>';
            return `<button type="button" data-key="${p.key}" data-type="${p.type}" title="${p.sub || ''}">
                        <i class="fas ${icon} me-1"></i>${label}${warn}
                    </button>`;
        }).join('');

        const pick = profiles.find(p => p.key === suggestedKey) || profiles[profiles.length - 1];
        selectProfile(pick.key);
    }

    function selectProfile(key) {
        const p = (FINV.profiles || []).find(x => x.key === key);
        if (!p) return;

        document.querySelectorAll('#finvBillingToggle button').forEach(b => b.classList.toggle('on', b.dataset.key === key));
        FINV.billingType = p.type;
        FINV.selectedProfileKey = key;

        const isCompany = p.type === 'company';
        const cnf = document.getElementById('finvCompanyNameField');
        const tof = document.getElementById('finvTaxOfficeField');
        const lbl = document.getElementById('finvTaxNoLabel');
        const hint = document.getElementById('finvTcHint');
        if (cnf) cnf.hidden = !isCompany;
        if (tof) tof.hidden = !isCompany;
        if (lbl) lbl.textContent = isCompany ? 'Vergi No' : 'TC Kimlik No';
        // Vergi bilgisi eksik kurumsal seçenekte uyarı gösterilir
        if (hint) hint.hidden = !(isCompany && !p.complete);

        applyBilling(p.billing);
    }

    // Dinamik butonlar delege dinleyiciyle çalışır
    document.addEventListener('click', function (e) {
        const btn = e.target.closest('#finvBillingToggle button[data-key]');
        if (btn) selectProfile(btn.dataset.key);
    });

    function applyBilling(b) {
        if (!b) return;
        document.getElementById('finvBName').value = b.name || '';
        document.getElementById('finvBCompany').value = b.company_name || '';
        document.getElementById('finvBTaxNo').value = b.tax_number || '';
        document.getElementById('finvBTaxOffice').value = b.tax_office || '';
        document.getElementById('finvBPhone').value = b.phone || '';
        document.getElementById('finvBEmail').value = b.email || '';
        document.getElementById('finvBAddress').value = b.address || '';
    }

    // ── Kalemler ──
    function finvAddItem(it = null) {
        const tbody = document.getElementById('finvItems');
        if (!tbody) return;
        const tr = document.createElement('tr');
        const taxOptions = FINV.taxRates.map(r => `<option value="${r}" ${it && parseFloat(it.tax_rate) === r ? 'selected' : (!it && r === 20 ? 'selected' : '')}>%${r % 1 === 0 ? r : r.toFixed(2)}</option>`).join('');
        tr.innerHTML = `
            <td><input type="text" class="fi-name" maxlength="255" placeholder="Ürün / hizmet açıklaması"></td>
            <td><input type="number" class="fi-qty text-center" min="0" step="any" value="1"></td>
            <td><input type="number" class="fi-price text-end" min="0" step="any" value="0"></td>
            <td>
                <div class="d-flex gap-1">
                    <input type="number" class="fi-disc text-end" min="0" step="any" placeholder="0">
                    <select class="fi-disc-type" style="width:52px;">
                        <option value="percent">%</option>
                        <option value="amount">₺</option>
                    </select>
                </div>
            </td>
            <td><select class="fi-tax">${taxOptions}</select></td>
            <td><span class="finv-item-total">0,00</span></td>
            <td><button type="button" class="finv-item-x" onclick="this.closest('tr').remove(); finvRecalc();"><i class="fas fa-trash-can"></i></button></td>
        `;
        if (it) {
            tr.querySelector('.fi-name').value = it.name || '';
            tr.querySelector('.fi-qty').value = it.quantity ?? 1;
            tr.querySelector('.fi-price').value = it.unit_price ?? 0;
            tr.querySelector('.fi-disc').value = it.discount_value || '';
            tr.querySelector('.fi-disc-type').value = it.discount_type || 'percent';
        }
        tr.querySelectorAll('input, select').forEach(el => el.addEventListener('input', finvRecalc));
        tbody.appendChild(tr);
        if (!it) tr.querySelector('.fi-name').focus();
    }

    function finvItemBreakdown(tr) {
        const qty = parseFloat(tr.querySelector('.fi-qty').value) || 0;
        const price = parseFloat(tr.querySelector('.fi-price').value) || 0;
        const taxRate = parseFloat(tr.querySelector('.fi-tax').value) || 0;
        const dVal = parseFloat(tr.querySelector('.fi-disc').value) || 0;
        const dType = tr.querySelector('.fi-disc-type').value;

        const gross = qty * price;
        let discount = dType === 'amount' ? Math.min(dVal, gross) : gross * (Math.min(dVal, 100) / 100);
        discount = Math.max(0, discount);
        const base = gross - discount;
        const tax = base * (taxRate / 100);
        return { subtotal: base, discount, tax, total: base + tax };
    }

    function finvRecalc() {
        let sub = 0, disc = 0, tax = 0, grand = 0;
        document.querySelectorAll('#finvItems tr').forEach(tr => {
            const b = finvItemBreakdown(tr);
            sub += b.subtotal; disc += b.discount; tax += b.tax; grand += b.total;
            tr.querySelector('.finv-item-total').textContent = b.total.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        });
        const f = (v) => v.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        const set = (id, t) => { const el = document.getElementById(id); if (el) el.textContent = t; };
        set('finvTSub', f(sub));
        set('finvTDisc', '−' + f(disc));
        set('finvTTax', f(tax));
        set('finvTGrand', f(grand));
    }

    // ── Resmi faturayı kes (durum güncelle — entegrasyon ileride bağlanacak) ──
    function finvQvIssueOfficial() {
        if (!FINV.editId) return;
        Swal.fire({
            title: 'Resmi fatura kesildi mi?',
            html: 'Resmi fatura durumu <b>"Kesildi"</b> olarak işaretlenecek.<br><small class="text-muted">Entegrasyon bağlandığında bu işlem resmi faturayı otomatik kesecek.</small>',
            icon: 'question', showCancelButton: true,
            confirmButtonText: 'Evet, kesildi olarak işaretle', cancelButtonText: 'Vazgeç', confirmButtonColor: '#d97706'
        }).then(r => {
            if (!r.isConfirmed) return;
            fetch(`${FINV.baseUrl}/${FINV.editId}/official-status`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': FINV.csrf, 'Accept': 'application/json' },
                body: JSON.stringify({ official_status: 'issued' })
            })
            .then(r2 => r2.json())
            .then(d => {
                if (d.success) {
                    Swal.fire({ title: 'Kesildi', text: d.message, icon: 'success', timer: 1300, showConfirmButton: false })
                        .then(() => window.location.reload());
                } else {
                    Swal.fire('Hata', d.message || 'Güncellenemedi.', 'error');
                }
            })
            .catch(() => Swal.fire('Hata', 'Bağlantı hatası oluştu.', 'error'));
        });
    }

    // ── Kaydet ──
    function finvSubmit() {
        const items = [];
        let valid = true;
        document.querySelectorAll('#finvItems tr').forEach(tr => {
            const name = tr.querySelector('.fi-name').value.trim();
            if (!name) { valid = false; tr.querySelector('.fi-name').style.borderColor = '#f87171'; return; }
            tr.querySelector('.fi-name').style.borderColor = '';
            items.push({
                name: name,
                quantity: parseFloat(tr.querySelector('.fi-qty').value) || 0,
                unit_price: parseFloat(tr.querySelector('.fi-price').value) || 0,
                tax_rate: parseFloat(tr.querySelector('.fi-tax').value) || 0,
                discount_type: tr.querySelector('.fi-disc-type').value,
                discount_value: parseFloat(tr.querySelector('.fi-disc').value) || 0,
            });
        });

        if (!valid || !items.length) {
            Swal.fire('Eksik bilgi', 'En az bir kalem girin ve tüm kalem açıklamalarını doldurun.', 'warning');
            return;
        }
        if (!document.getElementById('finvNumber').value.trim()) {
            Swal.fire('Eksik bilgi', 'Fatura numarası zorunludur.', 'warning');
            return;
        }

        const payload = {
            invoice_number: document.getElementById('finvNumber').value.trim(),
            invoice_type: document.getElementById('finvType').value,
            billing_type: FINV.billingType,
            customer_id: document.getElementById('finvCustomerId').value || null,
            sale_id: document.getElementById('finvSaleId').value || null,
            issue_date: document.getElementById('finvDate').value,
            currency: document.getElementById('finvCurrency').value,
            status: document.getElementById('finvStatus').value,
            notes: document.getElementById('finvNotes').value || null,
            description: (FINV.descEditor
                ? FINV.descEditor.root.innerHTML
                : (document.getElementById('finvDescPlain')?.value || '')).replace(/^(<p><br><\/p>)+$/, '') || null,
            billing: {
                name: document.getElementById('finvBName').value || null,
                company_name: document.getElementById('finvBCompany').value || null,
                tax_number: document.getElementById('finvBTaxNo').value || null,
                tax_office: document.getElementById('finvBTaxOffice').value || null,
                address: document.getElementById('finvBAddress').value || null,
                phone: document.getElementById('finvBPhone').value || null,
                email: document.getElementById('finvBEmail').value || null,
            },
            items: items,
        };

        const isEdit = !!FINV.editId;
        if (isEdit) payload._method = 'PUT';

        const btn = document.getElementById('finvSubmit');
        if (btn) btn.disabled = true;

        fetch(isEdit ? `${FINV.baseUrl}/${FINV.editId}` : FINV.storeUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': FINV.csrf, 'Accept': 'application/json' },
            body: JSON.stringify(payload)
        })
        .then(r => r.json())
        .then(d => {
            if (btn) btn.disabled = false;
            if (d.success) {
                // Yeni fatura kartı kapatılır (yeniden yüklemede boş form açılmasın);
                // düzenleme kartı açık kalır ve sayfa yenilenince taze veriyle geri gelir.
                if (!isEdit && typeof closeCard === 'function') closeCard(FINV.selfUrl);
                Swal.fire({ title: 'Başarılı', text: d.message, icon: 'success', timer: 1300, showConfirmButton: false })
                    .then(() => window.location.reload());
            } else {
                Swal.fire('Hata', d.message || 'Kaydedilemedi.', 'error');
            }
        })
        .catch(() => { if (btn) btn.disabled = false; Swal.fire('Hata', 'Bağlantı hatası oluştu.', 'error'); });
    }

    // ── Kart içi kurulum (her enjeksiyonda çalışır) ──
    (function () {
        // Muhatap tipi butonları
        document.querySelectorAll('#finvBillingToggle button').forEach(btn => {
            btn.addEventListener('click', () => setBillingType(btn.dataset.type));
        });
        setBillingType(FINV.billingType);

        // Müşteri arama
        const input = document.getElementById('finvCustInput');
        const results = document.getElementById('finvCustResults');
        if (input && results) {
            let timer = null;
            input.addEventListener('input', () => {
                clearTimeout(timer);
                const term = input.value.trim();
                if (term.length < 2) { results.hidden = true; return; }
                timer = setTimeout(() => {
                    fetch(FINV.searchUrl + '?q=' + encodeURIComponent(term), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                        .then(r => r.json())
                        .then(d => {
                            results.innerHTML = '';
                            (d.items || []).forEach(item => {
                                const row = document.createElement('div');
                                row.className = 'finv-cust-row';
                                row.innerHTML = `<span class="finv-btype ${item.is_corporate ? 'company' : 'individual'}"><i class="fas ${item.is_corporate ? 'fa-building' : 'fa-id-card'}"></i></span><div><b></b><small></small></div>`;
                                row.querySelector('b').textContent = item.label;
                                row.querySelector('small').textContent = item.sub || '';
                                row.addEventListener('click', () => selectCustomer(item));
                                results.appendChild(row);
                            });
                            results.hidden = !(d.items || []).length;
                        })
                        .catch(() => {});
                }, 260);
            });

            document.addEventListener('click', (e) => {
                if (!e.target.closest('.finv-cust-search')) results.hidden = true;
            });
        }

        function selectCustomer(item) {
            results.hidden = true;
            input.value = item.label;
            document.getElementById('finvCustomerId').value = item.id;
            fetch(`${FINV.baseUrl}/customers/${item.id}/billing`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(r => r.json())
                .then(d => {
                    if (!d.success) return;
                    FINV.customerBilling = d;

                    if (d.profiles?.length) {
                        applyProfiles(d.profiles, d.suggested_key);
                        return;
                    }
                    // Sunucu eski biçimde yanıtlarsa geriye dönük davranış
                    setBillingType(d.suggested_type);
                    applyBilling(d.suggested_type === 'company' ? d.company : d.individual);
                });
        }

        // ── Satıştan fatura kesme ──
        // Odaklanınca liste hazır gelir (faturasız + en yeni satışlar üstte),
        // seçilince muhatap ve kalemler satıştan doldurulur.
        const saleInput = document.getElementById('finvSaleInput');
        const saleResults = document.getElementById('finvSaleResults');
        if (saleInput && saleResults) {
            let saleTimer = null;

            const loadSales = (term = '') => {
                fetch(FINV.saleSearchUrl + '?q=' + encodeURIComponent(term), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then(r => r.json())
                    .then(d => {
                        const items = d.items || [];
                        if (!items.length) {
                            saleResults.innerHTML = '<div class="finv-sale-empty">Eşleşen satış yok.</div>';
                            saleResults.hidden = false;
                            return;
                        }
                        saleResults.innerHTML = '';
                        items.forEach(s => {
                            const row = document.createElement('div');
                            row.className = 'finv-cust-row finv-sale-row';

                            let badge = '<span class="finv-sbadge none">Faturasız</span>';
                            if (s.invoice_count > 0) {
                                badge = s.official_issued
                                    ? '<span class="finv-sbadge official"><i class="fas fa-stamp"></i> Resmi kesildi</span>'
                                    : '<span class="finv-sbadge has"><i class="fas fa-file-invoice"></i> ' + s.invoice_count + ' fatura · resmi bekliyor</span>';
                            }

                            row.innerHTML = `
                                <span class="finv-btype individual"><i class="fas fa-receipt"></i></span>
                                <div style="min-width:0;flex:1">
                                    <b></b>
                                    <small></small>
                                </div>
                                <span class="finv-sale-amount"></span>
                                ${badge}`;
                            row.querySelector('b').textContent = '#' + s.code + (s.title ? ' · ' + s.title : '');
                            row.querySelector('small').textContent =
                                [s.customer, s.date, s.status_label].filter(Boolean).join(' · ');
                            row.querySelector('.finv-sale-amount').textContent =
                                Number(s.total).toLocaleString('tr-TR', { minimumFractionDigits: 2 }) + ' ' + s.currency;

                            bindRowGestures(row, s);
                            saleResults.appendChild(row);
                        });
                        saleResults.hidden = false;
                    })
                    .catch(() => {});
            };

            saleInput.addEventListener('focus', () => loadSales(saleInput.value.trim()));
            saleInput.addEventListener('input', () => {
                clearTimeout(saleTimer);
                saleTimer = setTimeout(() => loadSales(saleInput.value.trim()), 260);
            });
            document.addEventListener('click', (e) => {
                if (!e.target.closest('#finvSaleSearchWrap')) saleResults.hidden = true;
            });

            /**
             * Satır jestleri: kısa tık → satışı faturaya bağla,
             * basılı tut → satışın quick-view kartını üstte aç (fatura kartı arkada kalır).
             */
            function bindRowGestures(row, s) {
                const HOLD_MS = 420;
                let timer = null;
                let opened = false;

                const start = () => {
                    opened = false;
                    row.classList.add('is-holding');
                    timer = setTimeout(() => {
                        opened = true;
                        row.classList.remove('is-holding');
                        saleResults.hidden = true;
                        // Kart yığınına eklenir; fatura kartı kapanmaz, arkada kalır
                        openQuickView('/agency/sales/' + s.id + '/quick-view');
                    }, HOLD_MS);
                };
                const cancel = () => {
                    clearTimeout(timer);
                    row.classList.remove('is-holding');
                };

                row.addEventListener('mousedown', e => { if (e.button === 0) start(); });
                row.addEventListener('mouseup', cancel);
                row.addEventListener('mouseleave', cancel);
                row.addEventListener('touchstart', start, { passive: true });
                row.addEventListener('touchend', cancel);
                row.addEventListener('touchmove', cancel, { passive: true });
                // Basılı tutma bittikten sonra gelen tık seçim yapmasın
                row.addEventListener('click', () => { if (!opened) selectSale(s); });
                row.addEventListener('contextmenu', e => e.preventDefault());
            }

            function selectSale(s) {
                saleResults.hidden = true;
                saleInput.value = '';

                fetch(`${FINV.baseUrl}/sales/${s.id}/prefill`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then(r => r.json())
                    .then(d => {
                        if (!d.success) return;

                        document.getElementById('finvSaleId').value = d.sale.id;
                        if (d.customer_id) document.getElementById('finvCustomerId').value = d.customer_id;
                        if (d.customer_label) document.getElementById('finvCustInput').value = d.customer_label;

                        // Muhatap bilgileri (bağlı şirketler dahil)
                        if (d.billing) {
                            FINV.customerBilling = d.billing;
                            if (d.billing.profiles?.length) {
                                applyProfiles(d.billing.profiles, d.billing.suggested_key);
                            } else {
                                setBillingType(d.billing.suggested_type);
                                applyBilling(d.billing.suggested_type === 'company' ? d.billing.company : d.billing.individual);
                            }
                        }

                        // Para birimi + kalemler satıştan taşınır
                        const curr = document.getElementById('finvCurrency');
                        if (curr && d.sale.currency) curr.value = d.sale.currency;

                        const tb = document.getElementById('finvItems');
                        if (tb && (d.items || []).length) {
                            tb.innerHTML = '';
                            d.items.forEach(it => finvAddItem(it));
                            finvRecalc();
                        }

                        // Seçim kutusu
                        document.getElementById('finvSaleChosenTitle').textContent =
                            '#' + d.sale.code + (d.sale.title ? ' · ' + d.sale.title : '');
                        document.getElementById('finvSaleChosenSub').textContent =
                            [d.customer_label, (d.items || []).length + ' kalem aktarıldı'].filter(Boolean).join(' · ');
                        document.getElementById('finvSaleChosen').hidden = false;
                        document.getElementById('finvSaleSearchWrap').hidden = true;

                        const openBtn = document.getElementById('finvSaleOpen');
                        if (openBtn) openBtn.onclick = () => openQuickView('/agency/sales/' + d.sale.id + '/quick-view');
                    })
                    .catch(() => {});
            }

            // ?sale=… ile açıldıysa satışı hemen bağla (ödeme ekranından gelen kısayol)
            if (FINV.prefillSaleId) {
                selectSale({ id: FINV.prefillSaleId });
            }

            const clearBtn = document.getElementById('finvSaleClear');
            if (clearBtn) {
                clearBtn.addEventListener('click', () => {
                    document.getElementById('finvSaleId').value = '';
                    document.getElementById('finvSaleChosen').hidden = true;
                    document.getElementById('finvSaleSearchWrap').hidden = false;
                });
            }
        }

        // ── Açıklama (zengin metin) ──
        // Quill layout'tan global geliyor; yoksa düz metin alanına düşülür.
        const descHost = document.getElementById('finvDescEditor');
        if (descHost && !descHost.dataset.ready) {
            descHost.dataset.ready = '1';
            if (typeof Quill !== 'undefined') {
                FINV.descEditor = new Quill(descHost, {
                    theme: 'snow',
                    placeholder: 'Hizmet kapsamı, iptal koşulları, ödeme planı…',
                    modules: {
                        toolbar: [
                            [{ header: [2, 3, false] }],
                            ['bold', 'italic', 'underline'],
                            [{ list: 'ordered' }, { list: 'bullet' }],
                            ['link', 'clean'],
                        ],
                    },
                });
                FINV.descEditor.root.innerHTML = FINV.description || '';
            } else {
                descHost.innerHTML = '<textarea id="finvDescPlain" rows="4" style="width:100%;border:none;outline:none;padding:10px;"></textarea>';
                document.getElementById('finvDescPlain').value = FINV.description || '';
            }
        }

        // Kalemleri yükle
        const tbody = document.getElementById('finvItems');
        if (tbody && !tbody.children.length) {
            if (FINV.initialItems.length) {
                FINV.initialItems.forEach(it => finvAddItem(it));
            } else {
                finvAddItem();
            }
            finvRecalc();
        }
    })();
</script>
