@php
    // Acentede tanımlı para birimleri (currencies tablosu) → kod => sembol
    $currencySymbols = $activeCurrencies->pluck('symbol', 'code')->all();
    $saleSymbol = $currencySymbols[$sale->currency] ?? ($sale->currency ?: '₺');

    $statusSteps = [
        'potential' => ['label' => 'Potansiyel'],
        'offer_sent' => ['label' => 'Teklif Verildi'],
        'revised' => ['label' => 'Revize Edildi'],
        'confirmed' => ['label' => 'Satış Tamamlandı'],
        'in_progress' => ['label' => 'Devam Ediyor'],
        'completed' => ['label' => 'Kapanan'],
    ];
    $currentStatus = $sale->status;
    $statusKeys = array_keys($statusSteps);
    $statusIndex = array_search($currentStatus, $statusKeys);
    if ($statusIndex === false)
        $statusIndex = -1;
    $isCancelled = in_array($currentStatus, ['cancelled', 'refunded']);
@endphp

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

    {{-- ═══ HEADER ═══ --}}
    <div class="sqv-header">
        <div class="sqv-header-left">
            <div class="sqv-icon"
                style="background:{{ $sale->status_color }}15; color:{{ $sale->status_color }}">
                <i class="fas {{ $sale->productType->icon ?? 'fa-shopping-cart' }}"></i>
            </div>
            <div class="sqv-title-group">
                <h3 class="sqv-title inline-editable" data-field="title" data-id="{{ $sale->id }}"
                    data-url="{{ route('agency.sales.update-field', $sale) }}">
                    {{ $sale->title ?? $sale->sale_code }}
                </h3>
                <div class="sqv-subtitle">
                    <span class="sqv-code">{{ $sale->sale_code }}</span>
                    <span class="sqv-dot">•</span>
                    <a href="javascript:void(0)" onclick="openCustomerDrawer({{ $sale->customer_id }})"
                        class="sqv-customer-link"><i class="fas fa-user"></i>
                        {{ $sale->customer->full_name }}</a>
                    <span class="sqv-dot">•</span>
                    <span><i
                            class="fas fa-calendar-alt me-1"></i>{{ $sale->start_date->translatedFormat('d M Y') }}</span>
                    @if($sale->end_date && $sale->end_date->ne($sale->start_date))
                        <span>→ {{ $sale->end_date->translatedFormat('d M Y') }}</span>
                    @endif
                </div>
            </div>
        </div>
        <div class="sqv-header-right">
            @if($sale->customer->phone)
                <a href="tel:{{ $sale->customer->phone }}" class="sqv-quick-btn" title="Ara"><i
                        class="fas fa-phone"></i></a>
                <a href="https://wa.me/{{ preg_replace('/[^0-9]/', '', $sale->customer->phone) }}" target="_blank"
                    class="sqv-quick-btn whatsapp" title="WhatsApp"><i class="fab fa-whatsapp"></i></a>
            @endif
            @if($sale->customer->emails)
                <a href="mailto:{{ is_array($sale->customer->emails) ? ($sale->customer->emails[0] ?? '') : $sale->customer->emails }}"
                    class="sqv-quick-btn" title="E-posta"><i class="fas fa-envelope"></i></a>
            @endif
            <a href="{{ route('agency.sales.edit', $sale) }}" class="sqv-quick-btn edit" title="Tam Düzenleme"><i
                    class="fas fa-pen"></i></a>
            <button class="qv-action-btn qv-share" onclick="openQvShare()" title="Mesaj olarak gönder"><i
                    class="fas fa-paper-plane"></i></button>
            <button class="qv-action-btn qv-minimize" onclick="minimizeQuickView()" title="Küçült"><i
                    class="fas fa-minus"></i></button>
            <button class="qv-action-btn qv-close" onclick="closeQuickView()" title="Kapat"><i
                    class="fas fa-times"></i></button>
        </div>
    </div>

    {{-- ═══ PIPELINE (Bitrix Style) ═══ --}}
    <div class="sqv-pipeline-wrap">
        @if($isCancelled)
            <div class="sqv-cancelled-bar"><i class="fas fa-ban me-2"></i> Bu satış
                <strong>{{ $sale->status_label }}</strong> durumundadır.@if($sale->cancellation_reason)<span
                class="ms-2 opacity-75">— {{ $sale->cancellation_reason }}</span>@endif
            </div>
        @else
            <div class="sqv-pipeline">
                @foreach($statusSteps as $key => $step)
                    @php
                        $stepIdx = array_search($key, $statusKeys);
                        $isCompleted = $stepIdx < $statusIndex;
                        $isCurrent = $key === $currentStatus;
                        $cls = $isCurrent ? 'current' : ($isCompleted ? 'done' : 'future');
                    @endphp
                    <div class="sqv-seg {{ $cls }}" onclick="updateSaleStatus('{{ $key }}')" title="{{ $step['label'] }}">
                        <span class="sqv-seg-label">{{ $step['label'] }}</span>
                    </div>
                @endforeach
            </div>
        @endif
    </div>

    {{-- ═══ METRICS ═══ --}}
    <div class="sqv-metrics-bar">
        <div class="sqv-metric-item"><span class="sqv-metric-label">TOPLAM</span><span
                class="sqv-metric-val">{{ $saleSymbol }}{{ number_format($sale->total_amount, 2, ',', '.') }}</span></div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item"><span class="sqv-metric-label">ÖDENEN</span><span
                class="sqv-metric-val text-success">{{ $saleSymbol }}{{ number_format($sale->paid_amount, 2, ',', '.') }}</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item"><span class="sqv-metric-label">KALAN</span><span
                class="sqv-metric-val {{ $sale->remaining_amount > 0 ? 'text-danger' : 'text-muted' }}">{{ $saleSymbol }}{{ number_format($sale->remaining_amount, 2, ',', '.') }}</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item"><span class="sqv-metric-label">KİŞİ</span><span
                class="sqv-metric-val">{{ $sale->adult_count + $sale->child_count + $sale->infant_count }}</span>
        </div>
        <div class="sqv-metric-divider"></div>
        <div class="sqv-metric-item"><span class="sqv-metric-label">ÖDEME</span><span class="sqv-metric-val"
                style="font-size:0.8rem">{{ $sale->payment_status_label }}</span></div>
    </div>

    {{-- ═══ TABS ═══ --}}
    <x-quick-view.header>
        <x-slot:tabs>
            <x-quick-view.tab id="general" label="Genel" icon="fas fa-th-large" active="true" />
            <x-quick-view.tab id="products" label="Ürünler" icon="fas fa-box" :count="$sale->items->count()" />
            <x-quick-view.tab id="activities" label="Geçmiş" icon="fas fa-history"
                :count="$sale->activities->count()" />
            <x-quick-view.tab id="documents" label="Belgeler" icon="fas fa-folder-open" :count="$sale->documents->count()" />
        </x-slot:tabs>
    </x-quick-view.header>

    {{-- ═══ CONTENT ═══ --}}
    <x-quick-view.content>
        {{-- TAB: GENEL --}}
        <div id="qv-tab-general" class="qv-tab-panel active">
            <div class="p-4">
                <div class="row g-4">
                    {{-- LEFT COLUMN: DEAL & SERVICE INFO --}}
                    <div class="col-md-7">
                        {{-- ANLAŞMA HAKKINDA --}}
                        <div class="sqv-card mb-4">
                            <h6 class="sqv-card-title"><i class="fas fa-handshake me-2 text-primary"></i>Anlaşma Hakkında</h6>
                            <div class="row g-3">
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Tutar ve Para Birimi</label>
                                        <div class="fw-extrabold text-primary" style="font-size: 1.25rem;">
                                            {{ $saleSymbol }}{{ number_format($sale->total_amount, 2, ',', '.') }}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>ID</label>
                                        <div>{{ $sale->id }}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Rezervasyon Kodu</label>
                                        <div class="sqv-code bg-light text-dark border p-1 rounded" style="font-size: 0.75rem;">
                                            {{ $sale->sale_code }}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Durum</label>
                                        <div class="inline-editable fw-bold" data-field="status" data-type="select"
                                            data-id="{{ $sale->id }}"
                                            data-options='@json(collect($statusSteps)->map(fn($v, $k) => ["value" => $k, "label" => $v["label"]])->values())'
                                            data-url="{{ route('agency.sales.update-field', $sale) }}"
                                            style="color: {{ $sale->status_color }}">
                                            {{ $sale->status_label }}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Başlangıç Tarihi</label>
                                        <div class="inline-editable" data-field="start_date" data-type="date"
                                            data-id="{{ $sale->id }}"
                                            data-url="{{ route('agency.sales.update-field', $sale) }}">
                                            {{ $sale->start_date->format('Y-m-d') }}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Bitiş Tarihi</label>
                                        <div class="inline-editable" data-field="end_date" data-type="date"
                                            data-id="{{ $sale->id }}"
                                            data-url="{{ route('agency.sales.update-field', $sale) }}">
                                            {{ $sale->end_date ? $sale->end_date->format('Y-m-d') : '—' }}
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Sorumlu Personel</label>
                                        <div class="inline-editable" data-field="assigned_to" data-type="select"
                                            data-id="{{ $sale->id }}"
                                            data-options='@json($agents->map(fn($u) => ["value" => $u->id, "label" => $u->full_name])->values())'
                                            data-url="{{ route('agency.sales.update-field', $sale) }}">
                                            {{ $sale->assignedAgent->full_name ?? 'Atanmamış' }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- TUR BİLGİLERİ --}}
                        <div class="sqv-card mb-4">
                            <h6 class="sqv-card-title"><i class="fas fa-info-circle me-2 text-info"></i>Tur / Hizmet Bilgileri</h6>
                            <div class="row g-3">
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Ürün Tipi</label>
                                        <div>{{ $sale->productType->name ?? '—' }}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Ürün / Hizmet</label>
                                        <div>{{ $sale->product->name ?? ($sale->reservable->name ?? '—') }}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Katılımcılar</label>
                                        <div class="small fw-bold text-dark">
                                            {{ $sale->adult_count }} Yetişkin
                                            @if($sale->child_count > 0)
                                                , {{ $sale->child_count }} Çocuk
                                            @endif
                                            @if($sale->infant_count > 0)
                                                , {{ $sale->infant_count }} Bebek
                                            @endif
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="sqv-field">
                                        <label>Ödeme Durumu</label>
                                        <span class="badge {{ $sale->payment_status === 'paid' ? 'bg-success' : ($sale->payment_status === 'partial' ? 'bg-warning text-dark' : 'bg-danger') }}" style="font-size: 0.72rem; border-radius: 6px;">
                                            {{ $sale->payment_status_label }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- ÖZEL ALANLAR --}}
                        <div class="sqv-card mb-4" id="sqv-custom-fields-card" style="border-radius: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.02); border: 1px solid #e2e8f0; background: #fff;">
                            <div class="d-flex justify-content-between align-items-center mb-3 border-bottom pb-2">
                                <h6 class="sqv-card-title mb-0" style="font-weight: 800; font-size: 0.88rem; color: #1e293b;"><i class="fas fa-tags me-2 text-warning"></i>Özel Alanlar</h6>
                                <button type="button" class="btn btn-sm btn-outline-primary py-1 px-2 border-0" onclick="showAddCustomFieldModal()" style="font-size: 0.72rem; border-radius: 6px; font-weight: 700;">
                                    <i class="fas fa-plus me-1"></i> Yeni Alan Ekle
                                </button>
                            </div>
                            <div class="row g-3" id="sqv-custom-fields-container">
                                @forelse($customFieldDefinitions as $definition)
                                    @php
                                        $valRecord = $sale->customFields->where('field_definition_id', $definition->id)->first();
                                        $val = $valRecord ? $valRecord->value : '';
                                        $opts = [];
                                        if ($definition->field_type === 'select' && is_array($definition->options)) {
                                            foreach ($definition->options as $opt) {
                                                $opts[] = ['value' => $opt, 'label' => $opt];
                                            }
                                        }
                                    @endphp
                                    <div class="col-6 custom-field-item-wrap" data-definition-id="{{ $definition->id }}">
                                        <div class="sqv-field">
                                            <label class="d-flex justify-content-between align-items-center" style="font-size: 0.72rem; color: #64748b; font-weight: 700; text-transform: uppercase; margin-bottom: 6px;">
                                                <span>{{ $definition->label }}</span>
                                                <a href="javascript:void(0)" onclick="editCustomFieldDefinition({{ $definition->id }}, '{{ addslashes($definition->label) }}', '{{ $definition->field_type }}', @json($definition->options))" class="text-muted text-hover-primary ms-2" style="font-size: 0.68rem;" title="Alanı Düzenle">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            </label>
                                            <div class="inline-editable w-100 fw-bold" 
                                                 data-field="custom_field_{{ $definition->id }}" 
                                                 data-type="{{ $definition->field_type === 'select' ? 'select' : ($definition->field_type === 'textarea' ? 'textarea' : 'text') }}"
                                                 data-options='@json($opts)'
                                                 data-id="{{ $sale->id }}"
                                                 data-url="{{ route('agency.sales.update-field', $sale) }}"
                                                 data-value="{{ $val }}"
                                                 style="font-size: 0.85rem; color: #334155; border-bottom: 1px dashed #cbd5e1; cursor: pointer; transition: all 0.2s;">
                                                {{ $val ?: '—' }}
                                            </div>
                                        </div>
                                    </div>
                                @empty
                                    <div class="col-12 text-center py-3 text-muted" id="no-custom-fields-msg" style="font-size: 0.8rem;">
                                        <i class="fas fa-info-circle me-1"></i> Tanımlı özel alan bulunmuyor.
                                    </div>
                                @endforelse
                            </div>
                        </div>

                        {{-- NOTLAR --}}
                        <div class="sqv-card sqv-notes-card">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="sqv-card-title mb-0"><i class="fas fa-sticky-note me-2 text-warning"></i>Dahili ve Müşteri Notları</h6>
                                <button type="button" id="qv-sale-notes-save-btn" class="btn btn-sm px-3 text-white" style="border-radius:9px;font-size:0.74rem;font-weight:700;background:linear-gradient(135deg,#f59e0b,#d97706);border:none;"><i class="fas fa-save me-1"></i>Notları Kaydet</button>
                            </div>
                            <div class="sqv-note-section mb-3">
                                <label class="fw-bold" style="color: #b45309; font-size: 0.7rem;">Müşteri Notu</label>
                                <div class="rte-wrap mt-1">
                                    <div id="qv-sale-customer-note-editor" data-placeholder="Müşteriye iletilecek notlar...">{!! $sale->customer_note !!}</div>
                                </div>
                            </div>
                            <hr style="border-color:#fde68a">
                            <div class="sqv-note-section">
                                <label class="fw-bold" style="color: #b45309; font-size: 0.7rem;">Dahili Not</label>
                                <div class="rte-wrap mt-1">
                                    <div id="qv-sale-internal-note-editor" data-placeholder="Sadece çalışanlar görebilir...">{!! $sale->internal_note !!}</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- RIGHT COLUMN: ACTIVITY COMPOSER & TIMELINE --}}
                    <div class="col-md-5">
                        {{-- Composer Tabbed Card --}}
                        <div class="sqv-activity-composer border p-3 bg-white mb-4" style="border-radius: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.02);">
                            {{-- Composer Sub-Tabs --}}
                            <ul class="nav nav-tabs border-0 gap-1 mb-3" id="composerTabs" role="tablist" style="font-size: 0.76rem; font-weight: 700; border-bottom: 1px solid #f1f5f9 !important; padding-bottom: 8px;">
                                <li class="nav-item">
                                    <button type="button" class="nav-link active border-0 px-2 py-1 bg-transparent text-primary" data-type="comment" onclick="setComposerType('comment', this)"><i class="fas fa-comment-alt me-1 text-primary"></i> Yorum</button>
                                </li>
                                <li class="nav-item">
                                    <button type="button" class="nav-link border-0 px-2 py-1 bg-transparent text-muted" data-type="task" onclick="setComposerType('task', this)"><i class="fas fa-check-square me-1 text-danger"></i> Görev</button>
                                </li>
                                <li class="nav-item">
                                    <button type="button" class="nav-link border-0 px-2 py-1 bg-transparent text-muted" data-type="email" onclick="setComposerType('email', this)"><i class="fas fa-envelope me-1 text-warning"></i> E-Posta</button>
                                </li>
                                <li class="nav-item">
                                    <button type="button" class="nav-link border-0 px-2 py-1 bg-transparent text-muted" data-type="call" onclick="setComposerType('call', this)"><i class="fas fa-phone me-1 text-success"></i> Arama</button>
                                </li>
                                <li class="nav-item">
                                    <button type="button" class="nav-link border-0 px-2 py-1 bg-transparent text-muted" data-type="meeting" onclick="setComposerType('meeting', this)"><i class="fas fa-users me-1 text-primary"></i> Toplantı</button>
                                </li>
                                <li class="nav-item dropdown">
                                    <button class="nav-link border-0 px-2 py-1 bg-transparent text-muted dropdown-toggle" data-bs-toggle="dropdown" type="button" aria-expanded="false" style="padding-right: 15px;">
                                        <i class="fas fa-plus-circle me-1 text-secondary"></i> Diğer
                                    </button>
                                    <ul class="dropdown-menu shadow-sm" style="font-size: 0.8rem; border-radius: 10px; z-index: 1050;">
                                        <li><button type="button" class="dropdown-item py-2" data-type="whatsapp" onclick="setComposerType('whatsapp', this)"><i class="fab fa-whatsapp me-2 text-success"></i> WhatsApp</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="sms" onclick="setComposerType('sms', this)"><i class="fas fa-sms me-2 text-info"></i> SMS</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="offer" onclick="setComposerType('offer', this, 'Teklif Sunumu')"><i class="fas fa-handshake me-2 text-warning"></i> Teklif</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="payment" onclick="setComposerType('payment', this, 'Ödeme ve Tahsilat')"><i class="fas fa-credit-card me-2 text-success"></i> Ödeme</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="visit" onclick="setComposerType('visit', this, 'Müşteri Ziyareti')"><i class="fas fa-map-marker-alt me-2 text-danger"></i> Ziyaret</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="complaint" onclick="setComposerType('complaint', this, 'Şikayet / Destek Talebi')"><i class="fas fa-exclamation-triangle me-2 text-danger"></i> Şikayet</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="document" onclick="setComposerType('document', this, 'Belge / Evrak İşlemi')"><i class="fas fa-file-alt me-2 text-info"></i> Belge</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="marketing" onclick="setComposerType('marketing', this, 'Pazarlama / Kampanya')"><i class="fas fa-bullhorn me-2 text-purple"></i> Pazarlama</button></li>
                                        <li><button type="button" class="dropdown-item py-2" data-type="support" onclick="setComposerType('support', this, 'Teknik Destek')"><i class="fas fa-life-ring me-2 text-danger"></i> Destek</button></li>
                                    </ul>
                                </li>
                            </ul>

                            {{-- Composer Input Form --}}
                            <form id="activityComposerForm" enctype="multipart/form-data">
                                @csrf
                                <input type="hidden" name="activity_type" id="composer_type" value="comment">
                                
                                {{-- Dynamic Subject Input --}}
                                <div class="mb-2 d-none" id="composerSubjectGroup">
                                    <input type="text" name="subject" class="form-control form-control-sm border bg-light p-2" placeholder="Konu / Başlık girin..." style="border-radius: 10px; font-size: 0.82rem;">
                                </div>

                                {{-- Dynamic Due Date Input --}}
                                <div class="mb-2 d-none" id="composerDueDateGroup">
                                    <div class="d-flex align-items-center gap-2 bg-light p-2 border rounded" style="border-radius: 10px;">
                                        <span class="text-muted small fw-bold" style="font-size: 0.72rem; white-space: nowrap;"><i class="fas fa-clock me-1 text-danger"></i> Bitiş Tarihi:</span>
                                        <input type="datetime-local" name="due_date" class="form-control form-control-sm border-0 bg-transparent p-0" style="font-size: 0.82rem; font-weight: 600;">
                                    </div>
                                </div>

                                {{-- Body TextArea --}}
                                <div class="mb-3">
                                    <textarea name="description" id="composerDescription" class="form-control border p-2" placeholder="Yapılacakları veya yorumları buraya yazın..." rows="3" style="font-size: 0.85rem; background: #fafafa; border-radius: 12px; resize: none;" required></textarea>
                                </div>

                                {{-- Attachment Preview Card --}}
                                <div id="composerAttachmentPreview" class="mb-3 d-none">
                                    <div class="d-flex align-items-center justify-content-between p-2 rounded border bg-light" style="font-size: 0.8rem; border-radius: 10px !important;">
                                        <div class="d-flex align-items-center gap-2 overflow-hidden">
                                            <i class="far fa-file-alt text-primary" style="font-size: 1rem;"></i>
                                            <span class="text-truncate fw-bold text-dark" id="composerAttachmentName" style="max-width: 200px;"></span>
                                        </div>
                                        <button type="button" class="btn-close" style="font-size: 0.65rem;" onclick="clearComposerAttachment()"></button>
                                    </div>
                                </div>

                                {{-- Footer Actions Bar --}}
                                <div class="d-flex justify-content-between align-items-center pt-2 border-top">
                                    <div class="d-flex align-items-center gap-2">
                                        {{-- File Upload Label/Button --}}
                                        <label for="activityAttachmentInput" class="btn btn-light btn-sm border-0 p-0 d-flex align-items-center justify-content-center shadow-none" style="width: 32px; height: 32px; border-radius: 8px; cursor: pointer; background: #f1f5f9;" title="Dosya Ekle">
                                            <i class="fas fa-paperclip text-secondary" style="font-size: 0.95rem;"></i>
                                        </label>
                                        <input type="file" id="activityAttachmentInput" name="attachment" class="d-none" onchange="handleComposerAttachmentChange(this)">

                                        {{-- Important Flag Button --}}
                                        <button type="button" id="composerImportantBtn" class="btn btn-light btn-sm border-0 p-0 d-flex align-items-center justify-content-center shadow-none" style="width: 32px; height: 32px; border-radius: 8px; background: #f1f5f9;" onclick="toggleComposerImportant()" title="Önemli İşaretle">
                                            <i class="fas fa-star text-muted" style="font-size: 0.9rem;"></i>
                                        </button>
                                    </div>
                                    <button type="submit" class="btn btn-primary btn-sm px-4 fw-bold" style="border-radius: 10px; font-size: 0.8rem; background: linear-gradient(135deg, #6366f1, #4f46e5); border: none;">Gönder</button>
                                </div>
                            </form>
                        </div>

                        {{-- Scrollable Activities Feed --}}
                        <div class="qv-activities-feed-container" id="qv-general-activities-feed" style="max-height: 500px; overflow-y: auto; padding-right: 5px;">
                            @include('agency.sales.partials.activities-feed', ['sale' => $sale])
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- TAB: ÜRÜNLER --}}
        <div id="qv-tab-products" class="qv-tab-panel">
            <div class="p-4">
                <div class="d-flex justify-content-between align-items-center mb-4 pb-2 border-bottom">
                    <div>
                        <h6 class="sqv-card-title mb-0" style="font-weight: 800; font-size: 0.95rem; color: #1e293b;"><i class="fas fa-box me-2 text-primary"></i>Ürün Kataloğu & Satış Kalemleri</h6>
                        <p class="text-muted mb-0" style="font-size: 0.72rem; margin-top: 2px;"><i class="fas fa-keyboard me-1"></i>Adı direkt yazın <span class="mx-1 text-muted">·</span> <i class="fas fa-th-large me-1 text-indigo"></i>veya <strong>Katalog</strong> butonuyla kayıtlı ürünlerinizden seçin</p>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-outline-secondary btn-sm" style="border-radius:10px; font-weight:700;" onclick="addBlankQvProductRow()"><i class="fas fa-plus me-1 text-primary"></i> Satır Ekle</button>
                        <button class="btn btn-success btn-sm" style="border-radius:10px; font-weight:700; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.2);" onclick="saveQvProducts()"><i class="fas fa-save me-1"></i> Kaydet</button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table align-middle" style="font-size:0.88rem; min-width: 900px;">
                        <thead>
                            <tr style="font-size:0.72rem; text-transform:uppercase; letter-spacing:0.04em; color:#64748b; border-bottom: 2px solid #f1f5f9;">
                                <th>Ürün / Hizmet Adı</th>
                                <th class="text-center" style="width: 95px;">Adet</th>
                                <th class="text-end" style="width: 160px;">Birim Fiyat</th>
                                <th class="text-center" style="width: 90px;">KDV</th>
                                <th class="text-end" style="width: 110px;">KDV Tutarı</th>
                                <th class="text-end" style="width: 140px;">Toplam</th>
                                <th style="width: 36px;"></th>
                            </tr>
                        </thead>
                        <tbody id="qv-products-tbody">
                            @forelse($sale->items as $item)
                                <tr class="qv-product-row" data-id="{{ $item->id }}">
                                    <input type="hidden" class="row-id" value="{{ $item->id }}">
                                    <input type="hidden" class="row-product-id" value="{{ $item->product_id }}">
                                    <td>
                                        <div class="qv-product-name-cell">
                                            <input type="text" class="form-control bg-transparent fw-bold text-dark qv-product-name" value="{{ $item->name }}" placeholder="Ürün / hizmet adını yazın..." autocomplete="off">
                                            <button type="button" class="btn-catalog-pick" onclick="openProductCatalog(this.closest('.qv-product-row'))" title="Katalogdan seç">
                                                <i class="fas fa-th-large"></i>
                                                <span>Katalog</span>
                                            </button>
                                        </div>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control bg-transparent text-center fw-bold qv-product-qty" value="{{ (float) $item->quantity }}" min="0.01" step="any" oninput="calculateQvProductTotals()">
                                    </td>
                                    <td>
                                        <div class="input-group input-group-sm">
                                            <input type="number" class="form-control bg-transparent text-end fw-semibold qv-product-price" value="{{ (float) $item->unit_price }}" min="0" step="any" oninput="calculateQvProductTotals()">
                                            <select class="form-select bg-transparent text-muted qv-product-currency" style="max-width: 70px; border: none; font-size: 0.72rem;" onchange="calculateQvProductTotals()">
                                                @foreach($activeCurrencies as $curr)
                                                    <option value="{{ $curr->code }}" {{ $item->currency == $curr->code ? 'selected' : '' }}>{{ $curr->code }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </td>
                                    <td>
                                        <select class="form-select bg-transparent text-center fw-bold qv-product-tax" onchange="calculateQvProductTotals()">
                                            @foreach($taxRates as $tax)
                                                <option value="{{ (float) $tax->rate }}" @selected((float) $item->tax_rate === (float) $tax->rate)>%{{ rtrim(rtrim(number_format((float) $tax->rate, 2, '.', ''), '0'), '.') }}</option>
                                            @endforeach
                                            {{-- Kaydedilmiş oran artık tanımlı değilse (ör. silinmiş) kaybolmasın --}}
                                            @unless($taxRates->contains(fn($t) => (float) $t->rate === (float) $item->tax_rate))
                                                <option value="{{ (float) $item->tax_rate }}" selected>%{{ rtrim(rtrim(number_format((float) $item->tax_rate, 2, '.', ''), '0'), '.') }}</option>
                                            @endunless
                                        </select>
                                    </td>
                                    <td class="text-end text-muted fw-bold">
                                        <span class="qv-row-tax-amount">{{ $currencySymbols[$item->currency] ?? $item->currency }}{{ number_format($item->tax_amount, 2, ',', '.') }}</span>
                                    </td>
                                    <td class="text-end fw-bold text-primary">
                                        <span class="qv-row-total-price">{{ $currencySymbols[$item->currency] ?? $item->currency }}{{ number_format($item->total_price, 2, ',', '.') }}</span>
                                    </td>
                                    <td class="text-end">
                                        <button type="button" class="btn btn-link btn-sm text-danger p-0 shadow-none border-0" onclick="removeQvProductRow(this)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            @empty
                                <!-- Empty state is handled by automatically adding a row via JS if needed -->
                            @endforelse
                        </tbody>
                    </table>
                </div>

                {{-- Summary Block --}}
                <div class="d-flex justify-content-between align-items-center mt-4 border-top pt-3">
                    <span class="text-muted small"><i class="fas fa-info-circle me-1"></i> Kalemleri düzenledikten sonra sağ üstteki <strong>Kaydet</strong> butonuna basın.</span>
                    <div class="card border-0 bg-light p-3" style="width: 350px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.02);">
                        <div class="d-flex justify-content-between mb-2" style="font-size: 0.82rem;">
                            <span class="text-muted fw-semibold">Ara Toplam:</span>
                            <span class="fw-bold text-dark" id="qv-summary-subtotal">{{ $saleSymbol }}{{ number_format($sale->subtotal, 2, ',', '.') }}</span>
                        </div>
                        <div class="d-flex justify-content-between mb-2" style="font-size: 0.82rem;">
                            <span class="text-muted fw-semibold">KDV Toplamı:</span>
                            <span class="fw-bold text-muted" id="qv-summary-tax">{{ $saleSymbol }}{{ number_format($sale->tax_amount, 2, ',', '.') }}</span>
                        </div>
                        <div class="border-top my-2"></div>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="text-dark fw-bold" style="font-size: 0.95rem;">Genel Toplam:</span>
                            <span class="text-primary fw-extrabold" style="font-size: 1.25rem;" id="qv-summary-total">{{ $saleSymbol }}{{ number_format($sale->total_amount, 2, ',', '.') }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- PRODUCT CATALOG MODAL --}}
        <div class="modal fade" id="qvProductCatalogModal" tabindex="-1" aria-labelledby="qvProductCatalogModalLabel" aria-hidden="true" style="z-index: 1065;">
            <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
                <div class="modal-content" style="border-radius: 20px; border: none; box-shadow: 0 25px 60px rgba(0,0,0,0.18); overflow: hidden;">
                    {{-- Modal Header --}}
                    <div class="modal-header border-0 pb-0" style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); padding: 1.5rem 1.75rem 1rem;">
                        <div class="d-flex align-items-center gap-3 flex-grow-1">
                            <div style="width: 42px; height: 42px; background: rgba(99,102,241,0.2); border-radius: 12px; display:flex; align-items:center; justify-content:center; flex-shrink:0;">
                                <i class="fas fa-th-large text-indigo" style="color: #818cf8; font-size: 1.1rem;"></i>
                            </div>
                            <div>
                                <h5 class="modal-title mb-0" id="qvProductCatalogModalLabel" style="color:#fff; font-weight: 800; font-size: 1.05rem;">Ürün Kataloğu</h5>
                                <p class="mb-0" style="color: #94a3b8; font-size: 0.72rem; margin-top: 2px;">Kayıtlı ürün veya hizmetlerinizden seçin</p>
                            </div>
                        </div>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    {{-- Search + Filter Bar --}}
                    <div class="border-0" style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); padding: 0.75rem 1.75rem 1.25rem;">
                        <div class="d-flex gap-2">
                            <div class="position-relative flex-grow-1">
                                <i class="fas fa-search position-absolute" style="left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: 0.85rem; pointer-events:none;"></i>
                                <input type="text" id="catalogSearchInput" class="form-control" placeholder="Ürün adı ile ara..." oninput="filterCatalogProducts()" style="border-radius: 12px; padding-left: 36px; background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.12); color: #fff; font-size: 0.88rem;">
                            </div>
                            <select id="catalogTypeFilter" class="form-select" onchange="filterCatalogProducts()" style="max-width: 180px; border-radius: 12px; background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.12); color: #fff; font-size: 0.82rem;">
                                <option value="">Tüm Tipler</option>
                                @php
                                    $productTypes = $products->pluck('productType')->filter()->unique('id');
                                @endphp
                                @foreach($productTypes as $pt)
                                    <option value="{{ $pt->id }}">{{ $pt->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    {{-- Modal Body --}}
                    <div class="modal-body p-0" style="background: #f8fafc; max-height: 480px; overflow-y: auto;">
                        <div id="catalogProductGrid" class="p-3">
                            @php
                                $productsByType = $products->groupBy(fn($p) => $p->productType?->name ?? 'Diğer');
                            @endphp

                            @forelse($productsByType as $typeName => $typeProducts)
                                <div class="catalog-type-group mb-4" data-type-name="{{ $typeName }}">
                                    <div class="d-flex align-items-center gap-2 mb-2" style="padding: 0 4px;">
                                        <span class="catalog-type-badge" style="font-size: 0.68rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; color: #6366f1; background: #ede9fe; padding: 3px 10px; border-radius: 20px;">{{ $typeName }}</span>
                                        <div style="flex:1; height: 1px; background: #e2e8f0;"></div>
                                    </div>
                                    <div class="row g-2">
                                        @foreach($typeProducts as $p)
                                            <div class="col-md-6 catalog-product-item"
                                                 data-name="{{ strtolower($p->name) }}"
                                                 data-type-id="{{ $p->productType?->id }}"
                                                 data-id="{{ $p->id }}"
                                                 data-price="{{ $p->base_price }}"
                                                 data-currency="{{ $p->currency }}">
                                                <div class="catalog-product-card" onclick="selectFromCatalog({{ $p->id }}, '{{ addslashes($p->name) }}', {{ $p->base_price ?? 0 }}, '{{ $p->currency }}')">
                                                    <div class="d-flex align-items-start gap-3">
                                                        <div class="catalog-product-icon">
                                                            <i class="fas {{ $p->productType?->icon ?? 'fa-box' }}"></i>
                                                        </div>
                                                        <div class="flex-grow-1 min-width-0">
                                                            <div class="catalog-product-name">{{ $p->name }}</div>
                                                            @if($p->description)
                                                                <div class="catalog-product-desc">{{ Str::limit($p->description, 60) }}</div>
                                                            @endif
                                                        </div>
                                                        <div class="text-end flex-shrink-0">
                                                            @if($p->base_price)
                                                                <div class="catalog-product-price">{{ number_format($p->base_price, 0, ',', '.') }} {{ $p->currency }}</div>
                                                            @else
                                                                <div class="catalog-product-price text-muted" style="font-size: 0.72rem;">Fiyat Yok</div>
                                                            @endif
                                                            <div class="catalog-product-select-btn">Seç <i class="fas fa-arrow-right ms-1" style="font-size: 0.65rem;"></i></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            @empty
                                <div class="text-center py-5">
                                    <i class="fas fa-box-open text-muted mb-3" style="font-size: 2.5rem; opacity: 0.4;"></i>
                                    <p class="text-muted">Tanımlı ürün bulunamadı.</p>
                                </div>
                            @endforelse

                            {{-- No results state --}}
                            <div id="catalogNoResults" class="text-center py-5 d-none">
                                <i class="fas fa-search text-muted mb-3" style="font-size: 2rem; opacity: 0.3;"></i>
                                <p class="text-muted fw-semibold">Arama kriterlerine uygun ürün bulunamadı.</p>
                                <p class="text-muted small">Ürün adını tabloya direkt yazabilirsiniz.</p>
                            </div>
                        </div>
                    </div>
                    {{-- Modal Footer --}}
                    <div class="modal-footer border-0" style="background: #f8fafc; padding: 0.75rem 1.25rem;">
                        <p class="text-muted small mb-0 me-auto"><i class="fas fa-info-circle me-1"></i> Seçim yapmadan tabloya da direkt yazabilirsiniz.</p>
                        <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal" style="border-radius: 10px; font-weight: 600;">Kapat</button>
                    </div>
                </div>
            </div>
        </div>

        {{-- TAB: GEÇMİŞ --}}
        <div id="qv-tab-activities" class="qv-tab-panel">
            <div class="p-4">
                <div class="qv-activities-feed-container" id="qv-tab-activities-feed">
                    @include('agency.sales.partials.activities-feed', ['sale' => $sale])
                </div>
            </div>
        </div>

        {{-- TAB: BELGELER --}}
        <div id="qv-tab-documents" class="qv-tab-panel">
            <div class="p-4">
                <div class="row g-4">
                    {{-- LEFT: Upload Form --}}
                    <div class="col-md-4">
                        <div class="sqv-card p-3 border shadow-none" style="border-radius: 16px; background: #f8fafc; border: 1px solid #e2e8f0 !important;">
                            <h6 class="sqv-card-title mb-3" style="font-weight: 800; font-size: 0.85rem; color: #1e293b;"><i class="fas fa-cloud-upload-alt me-2 text-primary"></i>Belge Yükle</h6>
                            <form id="qvDocUploadForm" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label class="form-label small fw-bold text-secondary">Dosya Seçin</label>
                                    <div class="border border-dashed p-4 rounded text-center bg-white position-relative hover-border-primary" style="cursor: pointer; border-radius: 12px; transition: all 0.2s;" id="drag-drop-zone">
                                        <input type="file" name="file" id="qv_doc_file" class="position-absolute top-0 start-0 w-100 h-100 opacity-0" style="cursor: pointer; z-index: 10;" required onchange="handleDocFileSelect(this)">
                                        <i class="fas fa-file-invoice text-muted mb-2" style="font-size: 1.8rem;" id="upload-icon"></i>
                                        <div class="small text-dark fw-bold" id="upload-filename">Dosyayı sürükleyin veya tıklayın</div>
                                        <div class="text-muted" style="font-size: 0.68rem; margin-top: 4px;">En fazla: 10MB</div>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label small fw-bold text-secondary">Açıklama / Not</label>
                                    <textarea name="notes" id="qv_doc_notes" class="form-control" placeholder="Örn: Uçuş Bileti, Kimlik Fotokopisi" rows="2" style="font-size: 0.8rem; border-radius: 8px;"></textarea>
                                </div>
                                <button type="button" class="btn btn-primary btn-sm w-100 py-2" onclick="submitUploadDocument()" style="border-radius: 8px; font-weight: 700; background: #2563eb; border: none;" id="upload-doc-btn">
                                    <i class="fas fa-upload me-1"></i> Yükle
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    {{-- RIGHT: Document List --}}
                    <div class="col-md-8">
                        <div class="sqv-card p-3 border shadow-none" style="border-radius: 16px; background: #fff; border: 1px solid #e2e8f0 !important;">
                            <h6 class="sqv-card-title mb-3" style="font-weight: 800; font-size: 0.85rem; color: #1e293b;"><i class="fas fa-file-alt me-2 text-warning"></i>Kayıtlı Belgeler (<span id="qv-doc-count-badge">{{ $sale->documents->count() }}</span>)</h6>
                            <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                                <table class="table align-middle" style="font-size: 0.8rem;">
                                    <thead class="table-light position-sticky top-0" style="z-index: 1;">
                                        <tr>
                                            <th>Belge Adı</th>
                                            <th>Boyut</th>
                                            <th>Ekleyen</th>
                                            <th class="text-end">İşlemler</th>
                                        </tr>
                                    </thead>
                                    <tbody id="qv-documents-list">
                                        @forelse($sale->documents as $doc)
                                            @php
                                                $ext = pathinfo($doc->file_name, PATHINFO_EXTENSION);
                                                $icon = match(strtolower($ext)) {
                                                    'pdf' => 'fa-file-pdf text-danger',
                                                    'jpg', 'jpeg', 'png', 'gif' => 'fa-file-image text-success',
                                                    'doc', 'docx' => 'fa-file-word text-primary',
                                                    'xls', 'xlsx' => 'fa-file-excel text-success',
                                                    'zip', 'rar' => 'fa-file-archive text-warning',
                                                    default => 'fa-file-alt text-secondary'
                                                };
                                            @endphp
                                            <tr data-doc-id="{{ $doc->id }}">
                                                <td>
                                                    <div class="d-flex align-items-center gap-2">
                                                        <i class="fas {{ $icon }}" style="font-size: 1.1rem;"></i>
                                                        <div style="min-width: 0; max-width: 250px;">
                                                            <div class="fw-bold text-dark text-truncate" title="{{ $doc->file_name }}">{{ $doc->file_name }}</div>
                                                            @if($doc->notes)
                                                                <div class="text-muted small text-truncate" style="font-size: 0.7rem;" title="{{ $doc->notes }}">{{ $doc->notes }}</div>
                                                            @endif
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-muted">{{ $doc->formatted_size }}</td>
                                                <td>
                                                    <span class="small fw-600 text-dark">{{ $doc->creator->full_name ?? 'Sistem' }}</span>
                                                    <div class="text-muted" style="font-size: 0.68rem;">{{ $doc->created_at->format('d.m.Y H:i') }}</div>
                                                </td>
                                                <td class="text-end">
                                                    <div class="d-flex gap-1 justify-content-end">
                                                        @php
                                                            $isImageOrPdf = in_array(strtolower($ext), ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']);
                                                        @endphp
                                                        @if($isImageOrPdf)
                                                            <button type="button" class="btn btn-sm btn-light border-0" onclick="previewSaleDocument('{{ Storage::url($doc->file_path) }}', '{{ addslashes($doc->file_name) }}', '{{ $doc->mime_type }}')" style="padding: 4px 8px; border-radius: 6px;" title="Önizle">
                                                                <i class="fas fa-eye text-primary"></i>
                                                            </button>
                                                        @endif
                                                        <a href="{{ Storage::url($doc->file_path) }}" target="_blank" class="btn btn-sm btn-light border-0" style="padding: 4px 8px; border-radius: 6px;" title="Görüntüle/İndir">
                                                            <i class="fas fa-download text-dark"></i>
                                                        </a>
                                                        <button type="button" class="btn btn-sm btn-light border-0" onclick="deleteSaleDocument({{ $doc->id }})" style="padding: 4px 8px; border-radius: 6px;" title="Sil">
                                                            <i class="fas fa-trash text-danger"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        @empty
                                            <tr id="qv-no-docs-row">
                                                <td colspan="4" class="text-center py-5 text-muted">
                                                    <i class="fas fa-folder-open mb-2" style="font-size: 2rem; opacity: 0.3;"></i>
                                                    <div>Kayıtlı belge bulunmuyor.</div>
                                                </td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </x-quick-view.content>

    {{-- MODAL --}}
    <div class="modal fade" id="qvAddItemModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Yeni Ürün Ekle</h5><button type="button" class="btn-close"
                        data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="qvAddItemForm">
                        <div class="mb-3">
                            <label class="form-label">Ürün / Hizmet Türü</label>
                            <select id="qv_product_select" class="form-select" onchange="handleProductSelectChange(this)">
                                <option value="custom" selected>-- Tanımlı Olmayan Ürün (Anlık Giriş) --</option>
                                @foreach($products as $p)
                                    <option value="{{ $p->id }}" data-name="{{ $p->name }}" data-price="{{ $p->base_price }}" data-currency="{{ $p->currency }}">{{ $p->name }} ({{ number_format($p->base_price, 2) }} {{ $p->currency }})</option>
                                @endforeach
                            </select>
                        </div>
                        <input type="hidden" name="product_id" id="qv_product_id" value="">

                        <div class="mb-3">
                            <label class="form-label">Ürün / Hizmet Adı</label>
                            <input type="text" name="name" id="qv_item_name" class="form-control" required placeholder="Örn: Balon Turu veya Transfer Hizmeti">
                        </div>

                        <div class="row mb-3">
                            <div class="col-6">
                                <label class="form-label">Adet</label>
                                <input type="number" name="quantity" class="form-control" value="{{ max(1, $sale->adult_count + $sale->child_count) }}" step="0.01" required>
                            </div>
                            <div class="col-6">
                                <label class="form-label">Birim Fiyat</label>
                                <div class="input-group">
                                    <input type="number" name="unit_price" id="qv_item_price" class="form-control" step="0.01" required>
                                    <select name="currency" id="qv_item_currency" class="form-select" style="max-width:80px">
                                        @foreach($activeCurrencies as $curr)
                                            <option value="{{ $curr->code }}">{{ $curr->code }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-6">
                                <label class="form-label">KDV Oranı (%)</label>
                                <select name="tax_rate" class="form-select">
                                    @foreach($taxRates as $tax)
                                        <option value="{{ (float) $tax->rate }}" @selected($tax->is_default)>{{ $tax->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-light"
                        data-bs-dismiss="modal">İptal</button><button type="button" class="btn btn-primary"
                        onclick="submitAddItem()">Ekle</button></div>
            </div>
        </div>
    </div>

    {{-- CUSTOM FIELD MODAL --}}
    <div class="modal fade" id="qvCustomFieldModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content" style="border-radius: 16px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.15);">
                <div class="modal-header" style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: white; border-top-left-radius: 16px; border-top-right-radius: 16px;">
                    <h5 class="modal-title" id="cfModalTitle" style="font-weight: 700; font-size: 1.1rem;"><i class="fas fa-tags me-2 text-warning"></i>Yeni Özel Alan Ekle</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <form id="qvCustomFieldForm">
                        <input type="hidden" name="id" id="cf_field_id" value="">
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold" style="font-size: 0.8rem; color: #475569;">Alan Başlığı (Label)</label>
                            <input type="text" name="label" id="cf_label" class="form-control" required placeholder="Örn: Rehber Notu, Uçuş Saati, vb." style="border-radius: 8px;">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold" style="font-size: 0.8rem; color: #475569;">Alan Tipi (Type)</label>
                            <select name="field_type" id="cf_type" class="form-select" onchange="toggleCfOptionsField()" style="border-radius: 8px;">
                                <option value="text">Kısa Metin (Text)</option>
                                <option value="select">Seçenekli (Dropdown/Select)</option>
                                <option value="textarea">Uzun Metin (Textarea)</option>
                                <option value="number">Sayı (Number)</option>
                                <option value="date">Tarih (Date)</option>
                            </select>
                        </div>

                        <div class="mb-3 d-none" id="cf_options_group">
                            <label class="form-label fw-bold" style="font-size: 0.8rem; color: #475569;">Seçenekler (Virgülle ayırın)</label>
                            <textarea name="options" id="cf_options" class="form-control" placeholder="Örn: Seçenek 1, Seçenek 2, Seçenek 3" rows="3" style="border-radius: 8px;"></textarea>
                            <div class="form-text text-muted" style="font-size: 0.72rem;">Her bir seçeneği virgül (,) ile ayırarak yazın.</div>
                        </div>

                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" name="is_required" id="cf_is_required" value="1">
                            <label class="form-check-label fw-bold" for="cf_is_required" style="font-size: 0.8rem; color: #475569;">Zorunlu Alan</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer border-0 p-3 bg-light" style="border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal" style="border-radius: 8px; font-weight: 600;">İptal</button>
                    <button type="button" class="btn btn-primary" onclick="submitCustomField()" style="border-radius: 8px; font-weight: 600; background: #2563eb; border: none; padding: 6px 16px;">Kaydet</button>
                </div>
            </div>
        </div>
    </div>

    {{-- DOCUMENT PREVIEW MODAL --}}
    <div class="modal fade" id="qvDocPreviewModal" tabindex="-1" style="z-index: 1060;">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content" style="border-radius: 16px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.15); overflow: hidden;">
                <div class="modal-header style-header" style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: white; border-top-left-radius: 16px; border-top-right-radius: 16px; border-bottom: none;">
                    <h5 class="modal-title" id="previewDocTitle" style="font-weight: 700; font-size: 1rem; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; max-width: 80%;"><i class="fas fa-eye me-2 text-warning"></i>Belge Önizleme</h5>
                    <div class="d-flex gap-2 align-items-center">
                        <a href="" id="previewDocDownloadBtn" download class="btn btn-sm btn-outline-light border-0" title="İndir"><i class="fas fa-download"></i></a>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                </div>
                <div class="modal-body p-0 text-center bg-dark d-flex align-items-center justify-content-center" style="min-height: 450px;" id="previewDocBody">
                    <!-- Dynamic content will go here (img or iframe) -->
                </div>
            </div>
        </div>
    </div>

    {{-- FOOTER --}}
    <x-quick-view.footer>
        <div class="text-muted small"><i class="fas fa-clock me-1"></i>
            {{ $sale->created_at->format('d.m.Y H:i') }} — {{ $sale->creator->full_name ?? 'Sistem' }}
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-outline-secondary btn-sm" onclick="closeQuickView()"
                style="border-radius:10px">Kapat</button>
            <a href="{{ route('agency.sales.edit', $sale) }}" class="btn btn-primary btn-sm"
                style="border-radius:10px;font-weight:700">Tam Düzenleme</a>
        </div>
    </x-quick-view.footer>
</x-quick-view.layout>

<script>
    // --- SALE PRODUCTS SPREADSHEET JAVASCRIPT ---
    window.exchangeRates = {
        @foreach($activeCurrencies as $curr)
            "{{ $curr->code }}": {{ (float)$curr->exchange_rate }},
        @endforeach
    };
    window.currencySymbols = {
        @foreach($activeCurrencies as $curr)
            "{{ $curr->code }}": "{{ $curr->symbol }}",
        @endforeach
    };
    window.saleCurrency = "{{ $sale->currency ?: 'TRY' }}";

    // --- PRODUCT CATALOG MODAL ---
    let _catalogTargetRow = null;

    function openProductCatalog(row) {
        _catalogTargetRow = row;
        // Reset search/filter
        const searchInput = document.getElementById('catalogSearchInput');
        const typeFilter = document.getElementById('catalogTypeFilter');
        if (searchInput) searchInput.value = '';
        if (typeFilter) typeFilter.value = '';
        filterCatalogProducts();
        const modal = new bootstrap.Modal(document.getElementById('qvProductCatalogModal'), { backdrop: true });
        modal.show();
    }

    function filterCatalogProducts() {
        const query = (document.getElementById('catalogSearchInput')?.value || '').toLowerCase().trim();
        const typeId = document.getElementById('catalogTypeFilter')?.value || '';
        let visibleCount = 0;

        document.querySelectorAll('.catalog-product-item').forEach(item => {
            const name = item.dataset.name || '';
            const itemTypeId = item.dataset.typeId || '';
            const nameMatch = !query || name.includes(query);
            const typeMatch = !typeId || itemTypeId === typeId;
            const visible = nameMatch && typeMatch;
            item.style.display = visible ? '' : 'none';
            if (visible) visibleCount++;
        });

        // Show/hide type group headers
        document.querySelectorAll('.catalog-type-group').forEach(group => {
            const visibleInGroup = group.querySelectorAll('.catalog-product-item:not([style*="none"])').length;
            group.style.display = visibleInGroup > 0 ? '' : 'none';
        });

        const noResults = document.getElementById('catalogNoResults');
        if (noResults) noResults.classList.toggle('d-none', visibleCount > 0);
    }

    function selectFromCatalog(id, name, price, currency) {
        if (!_catalogTargetRow) return;
        _catalogTargetRow.querySelector('.row-product-id').value = id;
        _catalogTargetRow.querySelector('.qv-product-name').value = name;
        _catalogTargetRow.querySelector('.qv-product-price').value = price;
        const currencyEl = _catalogTargetRow.querySelector('.qv-product-currency');
        if (currencyEl) currencyEl.value = currency;
        calculateQvProductTotals();

        // Close modal with animation
        const modal = bootstrap.Modal.getInstance(document.getElementById('qvProductCatalogModal'));
        if (modal) modal.hide();
        _catalogTargetRow = null;
    }

    function addBlankQvProductRow() {
        const tbody = document.getElementById('qv-products-tbody');
        if (!tbody) return;
        
        const emptyRow = document.getElementById('qv-no-products-row');
        if (emptyRow) emptyRow.remove();

        const tr = document.createElement('tr');
        tr.className = 'qv-product-row';
        tr.innerHTML = `
            <input type="hidden" class="row-id" value="">
            <input type="hidden" class="row-product-id" value="">
            <td>
                <div class="qv-product-name-cell">
                    <input type="text" class="form-control bg-transparent fw-bold text-dark qv-product-name" value="" placeholder="Ürün / hizmet adını yazın..." autocomplete="off">
                    <button type="button" class="btn-catalog-pick" onclick="openProductCatalog(this.closest('.qv-product-row'))" title="Katalogdan seç">
                        <i class="fas fa-th-large"></i>
                        <span>Katalog</span>
                    </button>
                </div>
            </td>
            <td>
                <input type="number" class="form-control bg-transparent text-center fw-bold qv-product-qty" value="1" min="0.01" step="any" oninput="calculateQvProductTotals()">
            </td>
            <td>
                <div class="input-group input-group-sm">
                    <input type="number" class="form-control bg-transparent text-end fw-semibold qv-product-price" value="0" min="0" step="any" oninput="calculateQvProductTotals()">
                    <select class="form-select bg-transparent text-muted qv-product-currency" style="max-width: 70px; border: none; font-size: 0.72rem;" onchange="calculateQvProductTotals()">
                        @foreach($activeCurrencies as $curr)
                            <option value="{{ $curr->code }}">{{ $curr->code }}</option>
                        @endforeach
                    </select>
                </div>
            </td>
            <td>
                <select class="form-select bg-transparent text-center fw-bold qv-product-tax" onchange="calculateQvProductTotals()">
                    <option value="0">%0</option>
                    <option value="1">%1</option>
                    <option value="10">%10</option>
                    <option value="20" selected>%20</option>
                </select>
            </td>
            <td class="text-end text-muted fw-bold">
                <span class="qv-row-tax-amount">₺0,00</span>
            </td>
            <td class="text-end fw-bold text-primary">
                <span class="qv-row-total-price">₺0,00</span>
            </td>
            <td class="text-end">
                <button type="button" class="btn btn-link btn-sm text-danger p-0 shadow-none border-0" onclick="removeQvProductRow(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;

        tbody.appendChild(tr);
        tr.querySelector('.qv-product-name').focus();
    }

    function removeQvProductRow(btn) {
        const row = btn.closest('.qv-product-row');
        row.remove();
        calculateQvProductTotals();
    }

    // Acentede tanımlı TÜM para birimleriyle çalışır (exchange_rate = 1 birimin TRY karşılığı)
    function convertAmount(amount, fromCurr, toCurr) {
        if (fromCurr === toCurr) return amount;
        const rates = window.exchangeRates || {};
        const fromRate = fromCurr === 'TRY' ? 1 : (parseFloat(rates[fromCurr]) || 1);
        const toRate   = toCurr   === 'TRY' ? 1 : (parseFloat(rates[toCurr])   || 1);
        return amount * fromRate / toRate;
    }

    function calculateQvProductTotals() {
        let subtotal = 0;
        let taxTotal = 0;
        let grandTotal = 0;
        const saleCurrency = window.saleCurrency || 'TRY';
        const currencySymbols = window.currencySymbols || {};

        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.qv-product-qty').value) || 0;
            const price = parseFloat(row.querySelector('.qv-product-price').value) || 0;
            const taxRate = parseFloat(row.querySelector('.qv-product-tax').value) || 0;
            const rowCurrency = row.querySelector('.qv-product-currency').value || 'TRY';

            const rowSubtotal = qty * price;
            const rowTax = rowSubtotal * (taxRate / 100);
            const rowTotal = rowSubtotal + rowTax;

            subtotal += convertAmount(rowSubtotal, rowCurrency, saleCurrency);
            taxTotal += convertAmount(rowTax, rowCurrency, saleCurrency);
            grandTotal += convertAmount(rowTotal, rowCurrency, saleCurrency);

            const rowSymbol = currencySymbols[rowCurrency] || rowCurrency;
            row.querySelector('.qv-row-tax-amount').textContent = rowSymbol + rowTax.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            row.querySelector('.qv-row-total-price').textContent = rowSymbol + rowTotal.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        });

        const saleSymbol = currencySymbols[saleCurrency] || saleCurrency;

        const subtotalEl = document.getElementById('qv-summary-subtotal');
        if (subtotalEl) subtotalEl.textContent = saleSymbol + subtotal.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        
        const taxEl = document.getElementById('qv-summary-tax');
        if (taxEl) taxEl.textContent = saleSymbol + taxTotal.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        
        const totalEl = document.getElementById('qv-summary-total');
        if (totalEl) totalEl.textContent = saleSymbol + grandTotal.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function saveQvProducts() {
        const items = [];
        let isValid = true;

        document.querySelectorAll('#qv-products-tbody .qv-product-row').forEach(row => {
            const name = row.querySelector('.qv-product-name').value.trim();
            const qty = parseFloat(row.querySelector('.qv-product-qty').value) || 0;
            const price = parseFloat(row.querySelector('.qv-product-price').value) || 0;

            if (!name) {
                isValid = false;
                row.querySelector('.qv-product-name').classList.add('border-danger');
            } else {
                row.querySelector('.qv-product-name').classList.remove('border-danger');
            }

            items.push({
                id: row.querySelector('.row-id').value || null,
                product_id: row.querySelector('.row-product-id').value || null,
                name: name,
                quantity: qty,
                unit_price: price,
                tax_rate: parseFloat(row.querySelector('.qv-product-tax').value) || 0,
                currency: row.querySelector('.qv-product-currency').value
            });
        });

        if (!isValid) {
            Swal.fire('Hata', 'Lütfen tüm ürün adlarını doldurun.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Kaydediliyor...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch('{{ route("agency.sales.items.bulk", $sale) }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ items: items })
        })
        .then(r => r.json())
        .then(d => {
            Swal.close();
            if (d.success) {
                Swal.fire({
                    title: 'Başarılı',
                    text: d.message,
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false
                });
                openSaleDrawer({{ $sale->id }}, 'products');
            } else {
                Swal.fire('Hata', d.message || 'Kaydedilemedi.', 'error');
            }
        })
        .catch(err => {
            Swal.close();
            console.error(err);
            Swal.fire('Hata', 'Bağlantı hatası oluştu.', 'error');
        });
    }

    // Ensure we have at least one blank row when loading if table is empty
    setTimeout(() => {
        const tbody = document.getElementById('qv-products-tbody');
        if (tbody && tbody.querySelectorAll('.qv-product-row').length === 0) {
            addBlankQvProductRow();
        }
    }, 400);

    // --- SALE DOCUMENTS JAVASCRIPT ---
    function previewSaleDocument(url, name, mime) {
        const modal = new bootstrap.Modal(document.getElementById('qvDocPreviewModal'));
        const title = document.getElementById('previewDocTitle');
        const body = document.getElementById('previewDocBody');
        const downloadBtn = document.getElementById('previewDocDownloadBtn');

        title.innerHTML = `<i class="fas fa-eye me-2 text-warning"></i>${name}`;
        downloadBtn.href = url;
        body.innerHTML = '<span class="spinner-border text-white"></span>';

        const isImage = mime.startsWith('image/') || /\.(jpg|jpeg|png|gif|webp|svg)$/i.test(name);
        const isPdf = mime === 'application/pdf' || /\.pdf$/i.test(name);

        modal.show();

        if (isImage) {
            body.innerHTML = `<img src="${url}" class="img-fluid" style="max-height: 75vh; object-fit: contain;">`;
        } else if (isPdf) {
            body.innerHTML = `<iframe src="${url}" width="100%" height="600px" style="border: none;"></iframe>`;
        } else {
            body.innerHTML = `<div class="p-5 text-white"><i class="fas fa-file-invoice mb-3" style="font-size: 3rem; opacity: 0.5;"></i><h4>Önizleme Desteklenmiyor</h4><p class="text-muted small">Bu dosya tipi doğrudan önizlenemez. İndir butonuna tıklayarak görüntüleyebilirsiniz.</p></div>`;
        }
    }

    function handleDocFileSelect(input) {
        const file = input.files[0];
        const filenameDiv = document.getElementById('upload-filename');
        const icon = document.getElementById('upload-icon');
        
        if (file) {
            filenameDiv.textContent = file.name;
            filenameDiv.classList.remove('text-dark');
            filenameDiv.classList.add('text-primary');
            icon.className = "fas fa-file-invoice text-primary mb-2";
        } else {
            filenameDiv.textContent = "Dosyayı sürükleyin veya tıklayın";
            filenameDiv.classList.remove('text-primary');
            filenameDiv.classList.add('text-dark');
            icon.className = "fas fa-file-invoice text-muted mb-2";
        }
    }

    function submitUploadDocument() {
        const fileInput = document.getElementById('qv_doc_file');
        if (!fileInput.files || fileInput.files.length === 0) {
            Swal.fire('Hata', 'Lütfen yüklenecek bir dosya seçin.', 'warning');
            return;
        }

        const form = document.getElementById('qvDocUploadForm');
        const formData = new FormData(form);
        const btn = document.getElementById('upload-doc-btn');

        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Yükleniyor...';

        fetch('{{ route("agency.sales.documents.store", $sale) }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(r => r.json())
        .then(d => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-upload me-1"></i> Yükle';

            if (d.success) {
                Swal.fire({
                    title: 'Başarılı',
                    text: d.message,
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false
                });
                openSaleDrawer({{ $sale->id }}, 'documents');
            } else {
                Swal.fire('Hata', d.message || 'Yükleme sırasında hata oluştu.', 'error');
            }
        })
        .catch(err => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-upload me-1"></i> Yükle';
            console.error(err);
            Swal.fire('Hata', 'Bağlantı hatası oluştu.', 'error');
        });
    }

    function deleteSaleDocument(docId) {
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu belge kalıcı olarak silinecektir.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'İptal'
        }).then(res => {
            if (res.isConfirmed) {
                fetch(`/agency/sales/{{ $sale->id }}/documents/${docId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    }
                })
                .then(r => r.json())
                .then(d => {
                    if (d.success) {
                        Swal.fire({
                            title: 'Silindi',
                            text: d.message,
                            icon: 'success',
                            timer: 1500,
                            showConfirmButton: false
                        });
                        openSaleDrawer({{ $sale->id }}, 'documents');
                    } else {
                        Swal.fire('Hata', d.message || 'Silme sırasında hata oluştu.', 'error');
                    }
                })
                .catch(err => {
                    console.error(err);
                    Swal.fire('Hata', 'Bağlantı hatası oluştu.', 'error');
                });
            }
        });
    }

    function showAddCustomFieldModal() {
        document.getElementById('qvCustomFieldForm').reset();
        document.getElementById('cf_field_id').value = '';
        document.getElementById('cf_is_required').checked = false;
        document.getElementById('cfModalTitle').innerHTML = '<i class="fas fa-tags me-2 text-warning"></i>Yeni Özel Alan Ekle';
        document.getElementById('cf_options_group').classList.add('d-none');
        new bootstrap.Modal(document.getElementById('qvCustomFieldModal')).show();
    }

    function editCustomFieldDefinition(id, label, type, options) {
        document.getElementById('qvCustomFieldForm').reset();
        document.getElementById('cf_field_id').value = id;
        document.getElementById('cf_label').value = label;
        document.getElementById('cf_type').value = type;
        
        if (type === 'select') {
            document.getElementById('cf_options_group').classList.remove('d-none');
            if (Array.isArray(options)) {
                document.getElementById('cf_options').value = options.join(', ');
            } else {
                document.getElementById('cf_options').value = options || '';
            }
        } else {
            document.getElementById('cf_options_group').classList.add('d-none');
        }

        document.getElementById('cfModalTitle').innerHTML = '<i class="fas fa-tags me-2 text-warning"></i>Özel Alanı Düzenle';
        new bootstrap.Modal(document.getElementById('qvCustomFieldModal')).show();
    }

    function toggleCfOptionsField() {
        const type = document.getElementById('cf_type').value;
        const group = document.getElementById('cf_options_group');
        if (type === 'select') {
            group.classList.remove('d-none');
        } else {
            group.classList.add('d-none');
        }
    }

    function submitCustomField() {
        const id = document.getElementById('cf_field_id').value;
        const data = {
            label: document.getElementById('cf_label').value,
            field_type: document.getElementById('cf_type').value,
            options: document.getElementById('cf_options').value,
            is_required: document.getElementById('cf_is_required').checked ? 1 : 0
        };

        let url = '{{ route("agency.sales.fields.store") }}';
        let method = 'POST';

        if (id) {
            url = '/agency/sales/fields/' + id;
            method = 'PATCH';
        }

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify(data)
        })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                bootstrap.Modal.getInstance(document.getElementById('qvCustomFieldModal')).hide();
                Swal.fire({
                    title: 'Başarılı',
                    text: d.message,
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false
                });
                openSaleDrawer({{ $sale->id }});
            } else {
                Swal.fire('Hata', d.message || 'İşlem sırasında hata oluştu.', 'error');
            }
        })
        .catch(err => {
            console.error(err);
            Swal.fire('Hata', 'Bağlantı hatası oluştu.', 'error');
        });
    }

    function updateSaleStatus(s) { if (s === '{{ $currentStatus }}') return; Swal.fire({ title: 'Durum Güncellensin mi?', text: 'Satış aşaması güncellenecektir.', icon: 'question', showCancelButton: true, confirmButtonText: 'Güncelle', cancelButtonText: 'Vazgeç' }).then(r => { if (r.isConfirmed) { fetch('{{ route("agency.sales.update-field", $sale) }}', { method: 'PATCH', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }, body: JSON.stringify({ field: 'status', value: s }) }).then(r => r.json()).then(d => { if (d.success) openSaleDrawer({{ $sale->id }}) }); } }); }
    function showAddItemModal() { new bootstrap.Modal(document.getElementById('qvAddItemModal')).show(); }
    
    function handleProductSelectChange(select) {
        const option = select.options[select.selectedIndex];
        const nameInput = document.getElementById('qv_item_name');
        const priceInput = document.getElementById('qv_item_price');
        const productIdInput = document.getElementById('qv_product_id');
        const currencySelect = document.getElementById('qv_item_currency');

        if (select.value === 'custom') {
            nameInput.value = '';
            priceInput.value = '';
            productIdInput.value = '';
            nameInput.readOnly = false;
        } else {
            nameInput.value = option.getAttribute('data-name');
            priceInput.value = option.getAttribute('data-price');
            productIdInput.value = select.value;
            nameInput.readOnly = true;

            const currency = option.getAttribute('data-currency');
            if (currency && currencySelect) {
                currencySelect.value = currency;
            }
        }
    }

    function submitAddItem() { var d = Object.fromEntries(new FormData(document.getElementById('qvAddItemForm')).entries()); fetch('{{ route("agency.sales.items.store", $sale) }}', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }, body: JSON.stringify(d) }).then(r => r.json()).then(d => { if (d.success) { Swal.fire('Başarılı', d.message, 'success'); bootstrap.Modal.getInstance(document.getElementById('qvAddItemModal')).hide(); openSaleDrawer({{ $sale->id }}, 'products'); } else Swal.fire('Hata', d.message, 'error'); }); }
    function removeItem(id) { Swal.fire({ title: 'Emin misiniz?', text: 'Bu ürün kaldırılacak!', icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33', confirmButtonText: 'Sil', cancelButtonText: 'İptal' }).then(r => { if (r.isConfirmed) fetch('/agency/sales/items/' + id, { method: 'DELETE', headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' } }).then(r => r.json()).then(d => { if (d.success) { Swal.fire('Silindi', d.message, 'success'); openSaleDrawer({{ $sale->id }}, 'products'); } }); }); }

    // --- CRM ACTIVITY COMPOSER & FEED JAVASCRIPT ---
    
    // Set Composer Type
    function setComposerType(type, btn, defaultSubject = '') {
        document.getElementById('composer_type').value = type;
        
        // Update tab styling
        const tabs = document.querySelectorAll('#composerTabs .nav-link');
        tabs.forEach(t => {
            t.classList.remove('active', 'text-primary');
            t.classList.add('text-muted');
        });

        // If the button is a dropdown-item
        if (btn.classList.contains('dropdown-item')) {
            const parentDropdown = document.querySelector('#composerTabs .dropdown-toggle');
            if (parentDropdown) {
                parentDropdown.classList.add('active', 'text-primary');
                parentDropdown.classList.remove('text-muted');
                parentDropdown.innerHTML = `<i class="${btn.querySelector('i').className}"></i> ${btn.textContent.trim()}`;
            }
        } else {
            // Reset parent dropdown button if normal tab is clicked
            const parentDropdown = document.querySelector('#composerTabs .dropdown-toggle');
            if (parentDropdown) {
                parentDropdown.innerHTML = '<i class="fas fa-plus-circle me-1 text-secondary"></i> Diğer';
            }
            btn.classList.add('active', 'text-primary');
            btn.classList.remove('text-muted');
        }

        // Toggle Fields
        const subjectGroup = document.getElementById('composerSubjectGroup');
        const dueDateGroup = document.getElementById('composerDueDateGroup');
        const descriptionArea = document.getElementById('composerDescription');

        // Hide all first
        subjectGroup.classList.add('d-none');
        dueDateGroup.classList.add('d-none');
        
        // Reset subject input if subject is not visible
        const subjectInput = subjectGroup.querySelector('input');
        if (subjectInput) {
            subjectInput.value = defaultSubject;
        }
        
        // Customize text area placeholder
        let placeholder = "Yapılacakları veya yorumları buraya yazın...";

        if (type === 'task') {
            subjectGroup.classList.remove('d-none');
            dueDateGroup.classList.remove('d-none');
            placeholder = "Görev detaylarını buraya yazın...";
        } else if (type === 'email') {
            subjectGroup.classList.remove('d-none');
            placeholder = "E-posta içeriğini buraya yazın...";
        } else if (type === 'call') {
            placeholder = "Arama detaylarını, görüşme notlarını buraya yazın...";
        } else if (type === 'meeting') {
            subjectGroup.classList.remove('d-none');
            placeholder = "Toplantı notlarını buraya yazın...";
        } else if (['offer', 'payment', 'complaint', 'document', 'marketing', 'support', 'whatsapp', 'sms', 'visit'].includes(type)) {
            subjectGroup.classList.remove('d-none');
            placeholder = `${btn.textContent.trim()} detaylarını ve notlarını buraya yazın...`;
        }

        descriptionArea.setAttribute('placeholder', placeholder);
    }

    // Toggle Important status
    function toggleComposerImportant() {
        const input = document.getElementById('composer_is_important');
        const btn = document.getElementById('composerImportantBtn');
        const icon = document.getElementById('composerImportantIcon');

        if (input.value === "1") {
            input.value = "0";
            btn.style.background = "#f1f5f9";
            icon.className = "fas fa-exclamation-circle text-secondary";
        } else {
            input.value = "1";
            btn.style.background = "#fee2e2";
            icon.className = "fas fa-exclamation-circle text-danger";
        }
    }

    // Handle File Attachment Preview
    function handleComposerAttachmentChange(input) {
        const file = input.files[0];
        if (file) {
            document.getElementById('composerAttachmentName').textContent = file.name;
            document.getElementById('composerAttachmentPreview').classList.remove('d-none');
        }
    }

    // Clear File Attachment
    function clearComposerAttachment() {
        document.getElementById('activityAttachmentInput').value = "";
        document.getElementById('composerAttachmentPreview').classList.add('d-none');
        document.getElementById('composerAttachmentName').textContent = "";
    }

    // Form Submission
    document.getElementById('activityComposerForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const form = this;
        const formData = new FormData(form);

        // Disable submit button
        const submitBtn = form.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.textContent = 'Gönderiliyor...';

        fetch('{{ route("agency.sales.activities.store", $sale) }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Gönder';

            if (data.success) {
                // Reset form
                form.reset();
                clearComposerAttachment();
                
                // Reset composer type default styling
                const commentBtn = document.querySelector('#composerTabs button[data-type="comment"]');
                if (commentBtn) setComposerType('comment', commentBtn);

                // Reset important status
                const importantInput = document.getElementById('composer_is_important');
                if (importantInput && importantInput.value === "1") {
                    toggleComposerImportant();
                }

                // Update both feeds
                document.querySelectorAll('.qv-activities-feed-container').forEach(container => {
                    container.innerHTML = data.html;
                });

                // Update activity counts
                updateActivityTabCount();
                
                Swal.fire({
                    title: 'Başarılı',
                    text: data.message,
                    icon: 'success',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000
                });
            } else {
                Swal.fire('Hata', data.message || 'Bir hata oluştu.', 'error');
            }
        })
        .catch(err => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = 'Gönder';
            console.error(err);
            Swal.fire('Hata', 'İşlem başarısız oldu.', 'error');
        });
    });

    // Toggle Pin Activity
    function togglePinActivity(activityId) {
        fetch(`/agency/sales/{{ $sale->id }}/activities/${activityId}/toggle-pin`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                // Update feeds
                document.querySelectorAll('.qv-activities-feed-container').forEach(container => {
                    container.innerHTML = data.html;
                });
            }
        })
        .catch(err => console.error(err));
    }

    // Delete Activity
    function deleteActivity(activityId) {
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu aktivite kaydı silinecektir.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'İptal'
        }).then(res => {
            if (res.isConfirmed) {
                fetch(`/agency/sales/{{ $sale->id }}/activities/${activityId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    }
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        // Update feeds
                        document.querySelectorAll('.qv-activities-feed-container').forEach(container => {
                            container.innerHTML = data.html;
                        });

                        // Update activity counts
                        updateActivityTabCount();

                        Swal.fire({
                            title: 'Silindi',
                            text: data.message,
                            icon: 'success',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                })
                .catch(err => console.error(err));
            }
        });
    }

    // Update Activity Count Badge on Tab
    function updateActivityTabCount() {
        const count = document.getElementById('qv-tab-activities-feed').querySelectorAll('.sqv-feed-item').length;

        // Find Tab Badge
        const tabEl = document.querySelector('button[onclick*="activities"]');
        if (tabEl) {
            let badge = tabEl.querySelector('.badge');
            if (badge) {
                badge.textContent = count;
                if (count === 0) {
                    badge.classList.add('d-none');
                } else {
                    badge.classList.remove('d-none');
                }
            }
        }
    }

    // ─── NOTLAR: ZENGİN METİN (QUILL) + KAYDET ───────────────────────────────────
    // Müşteri Notu ve Dahili Not alanları Quill editörü; "Notları Kaydet" ile her
    // iki alan update-field üzerinden PATCH'lenir.
    (function initSaleNoteEditors() {
        if (typeof Quill === 'undefined') return;

        function makeNoteQuill(id) {
            const el = document.getElementById(id);
            if (!el || el.__quillInit) return el ? el.__quill : null;
            el.__quillInit = true;
            el.__quill = new Quill(el, {
                theme: 'snow',
                placeholder: el.dataset.placeholder || 'Buraya yazın...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        [{ 'header': [3, 4, false] }],
                        ['link', 'clean']
                    ]
                }
            });
            return el.__quill;
        }

        const custQ = makeNoteQuill('qv-sale-customer-note-editor');
        const intQ = makeNoteQuill('qv-sale-internal-note-editor');

        const btn = document.getElementById('qv-sale-notes-save-btn');
        if (!btn || btn.__bound) return;
        btn.__bound = true;

        btn.addEventListener('click', function () {
            const original = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

            const token = (document.querySelector('meta[name="csrf-token"]') || {}).content;
            const url = '{{ route('agency.sales.update-field', $sale) }}';
            const custHtml = custQ && custQ.getText().trim().length ? custQ.root.innerHTML : '';
            const intHtml = intQ && intQ.getText().trim().length ? intQ.root.innerHTML : '';

            const save = (field, value) => fetch(url, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': token, 'Accept': 'application/json' },
                body: JSON.stringify({ field: field, value: value })
            }).then(r => r.json());

            Promise.all([save('customer_note', custHtml), save('internal_note', intHtml)])
                .then(results => {
                    const ok = results.every(d => d && d.success);
                    btn.disabled = false;
                    btn.innerHTML = original;
                    if (typeof Swal !== 'undefined') {
                        Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 2000 })
                            .fire({ icon: ok ? 'success' : 'error', title: ok ? 'Notlar kaydedildi.' : 'Notlar kaydedilemedi.' });
                    }
                })
                .catch(() => {
                    btn.disabled = false;
                    btn.innerHTML = original;
                    if (typeof Swal !== 'undefined') Swal.fire({ icon: 'error', title: 'Hata', text: 'Notlar kaydedilirken bir hata oluştu.' });
                });
        });
    })();
</script>

<style>
    /* ═══ HEADER ═══ */
    .sqv-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1.5rem 2rem;
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        flex-shrink: 0;
        gap: 1rem;
        position: relative;
        overflow: hidden;
    }

    .sqv-header::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -20%;
        width: 300px;
        height: 300px;
        background: radial-gradient(circle, rgba(99, 102, 241, 0.15) 0%, transparent 70%);
        pointer-events: none;
    }

    .sqv-header-left {
        display: flex;
        align-items: center;
        gap: 1rem;
        flex: 1;
        min-width: 0
    }

    .sqv-icon {
        width: 52px;
        height: 52px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.3rem;
        flex-shrink: 0;
        background: rgba(255, 255, 255, 0.1) !important;
        color: #fff !important;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .sqv-title-group {
        min-width: 0
    }

    .sqv-title {
        font-size: 1.35rem;
        font-weight: 800;
        color: #fff;
        letter-spacing: -0.03em;
        margin: 0;
        line-height: 1.3;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: text;
    }

    .sqv-title:hover {
        color: #a5b4fc
    }

    .sqv-subtitle {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.78rem;
        color: rgba(255, 255, 255, 0.5);
        flex-wrap: wrap;
        margin-top: 4px
    }

    .sqv-code {
        font-weight: 700;
        color: rgba(255, 255, 255, 0.4);
        font-size: 0.7rem;
        background: rgba(255, 255, 255, 0.08);
        padding: 2px 8px;
        border-radius: 6px;
        font-family: monospace
    }

    .sqv-dot {
        color: rgba(255, 255, 255, 0.2)
    }

    .sqv-customer-link {
        color: #818cf8;
        font-weight: 700;
        text-decoration: none;
        transition: all .2s
    }

    .sqv-customer-link:hover {
        color: #a5b4fc;
        text-decoration: underline
    }

    .sqv-header-right {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        flex-shrink: 0
    }

    .sqv-quick-btn {
        width: 36px;
        height: 36px;
        border-radius: 10px;
        border: 1px solid rgba(255, 255, 255, 0.12);
        background: rgba(255, 255, 255, 0.06);
        color: rgba(255, 255, 255, 0.6);
        font-size: .9rem;
        display: flex;
        align-items: center;
        justify-content: center;
        text-decoration: none;
        transition: all .25s;
        cursor: pointer;
        backdrop-filter: blur(6px);
    }

    .sqv-quick-btn:hover {
        background: rgba(255, 255, 255, 0.15);
        color: #fff;
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3)
    }

    .sqv-quick-btn.whatsapp:hover {
        background: rgba(34, 197, 94, 0.2);
        color: #4ade80;
        border-color: rgba(34, 197, 94, 0.3)
    }

    .sqv-quick-btn.edit:hover {
        background: rgba(251, 191, 36, 0.15);
        color: #fbbf24;
        border-color: rgba(251, 191, 36, 0.3)
    }

    .qv-sales-wrapper .qv-action-btn {
        background: rgba(255, 255, 255, 0.06);
        border: 1px solid rgba(255, 255, 255, 0.1);
        color: rgba(255, 255, 255, 0.5)
    }

    .qv-sales-wrapper .qv-action-btn:hover {
        background: rgba(255, 255, 255, 0.12);
        color: #fff
    }

    .qv-sales-wrapper .qv-action-btn.qv-close:hover {
        background: rgba(239, 68, 68, 0.2);
        color: #f87171;
        border-color: rgba(239, 68, 68, 0.3)
    }

    /* ═══ PIPELINE (Bitrix Segment Bar) ═══ */
    .sqv-pipeline-wrap {
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;
        padding: 0.6rem 1.5rem;
        flex-shrink: 0
    }

    .sqv-pipeline {
        display: flex;
        gap: 5px;
        width: 100%
    }

    .sqv-seg {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0.55rem 0.5rem;
        border-radius: 10px;
        cursor: pointer;
        transition: all .3s cubic-bezier(.4, 0, .2, 1);
        position: relative;
        min-height: 38px;
        border: 1.5px solid transparent;
        overflow: hidden
    }

    .sqv-seg::before {
        content: '';
        position: absolute;
        inset: 0;
        opacity: 0;
        transition: opacity .3s;
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.3), transparent);
        pointer-events: none
    }

    .sqv-seg:hover::before {
        opacity: 1
    }

    .sqv-seg-label {
        font-size: 0.68rem;
        font-weight: 700;
        white-space: nowrap;
        letter-spacing: 0.02em;
        position: relative;
        z-index: 1
    }

    .sqv-seg.done {
        background: linear-gradient(135deg, #818cf8, #6366f1);
        border-color: #6366f1
    }

    .sqv-seg.done .sqv-seg-label {
        color: #fff
    }

    .sqv-seg.done:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(99, 102, 241, 0.35)
    }

    .sqv-seg.current {
        background: linear-gradient(135deg, #34d399, #10b981);
        border-color: #059669;
        box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15)
    }

    .sqv-seg.current .sqv-seg-label {
        color: #fff;
        font-weight: 800;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1)
    }

    .sqv-seg.current:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(16, 185, 129, 0.35)
    }

    .sqv-seg.future {
        background: rgba(241, 245, 249, 0.8);
        border-color: #e2e8f0
    }

    .sqv-seg.future .sqv-seg-label {
        color: #94a3b8
    }

    .sqv-seg.future:hover {
        background: #e2e8f0;
        border-color: #cbd5e1;
        transform: translateY(-2px)
    }

    .sqv-cancelled-bar {
        background: linear-gradient(135deg, #fef2f2, #fee2e2);
        color: #991b1b;
        padding: 0.65rem 1.25rem;
        border-radius: 10px;
        font-size: .82rem;
        font-weight: 600;
        border: 1px solid #fecaca;
        text-align: center
    }

    /* ═══ METRICS ═══ */
    .sqv-metrics-bar {
        display: flex;
        align-items: stretch;
        justify-content: center;
        gap: 0;
        padding: 0;
        background: #fff;
        border-bottom: 1px solid #e2e8f0;
        flex-shrink: 0;
    }

    .sqv-metric-item {
        flex: 1;
        text-align: center;
        padding: 1rem 1.25rem;
        border-right: 1px solid #f1f5f9;
        transition: all .2s;
    }

    .sqv-metric-item:last-child {
        border-right: none
    }

    .sqv-metric-item:hover {
        background: #f8fafc
    }

    .sqv-metric-label {
        font-size: .58rem;
        font-weight: 800;
        color: #94a3b8;
        text-transform: uppercase;
        letter-spacing: .08em;
        display: block;
        margin-bottom: 3px
    }

    .sqv-metric-val {
        font-size: 1.05rem;
        font-weight: 800;
        color: #0f172a;
        letter-spacing: -0.02em
    }

    /* ═══ CARDS ═══ */
    .sqv-card {
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
        transition: all .25s;
    }

    .sqv-card:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
        border-color: #cbd5e1
    }

    .sqv-card-title {
        font-size: .82rem;
        font-weight: 800;
        color: #1e293b;
        margin-bottom: 1.25rem;
        display: flex;
        align-items: center
    }

    .sqv-field {
        padding: .65rem 0;
        border-bottom: 1px solid #f8fafc;
        transition: background .2s;
    }

    .sqv-field:hover {
        background: #fafbff;
        border-radius: 8px;
        padding-left: 6px;
        padding-right: 6px
    }

    .sqv-field label {
        font-size: .65rem;
        font-weight: 700;
        color: #94a3b8;
        text-transform: uppercase;
        letter-spacing: .04em;
        display: block;
        margin-bottom: 3px
    }

    .sqv-field div {
        font-size: .88rem;
        color: #1e293b;
        font-weight: 600
    }

    .sqv-notes-card {
        background: linear-gradient(135deg, #fffbeb, #fefce8);
        border-color: #fde68a
    }

    .sqv-notes-card:hover {
        box-shadow: 0 4px 16px rgba(245, 158, 11, 0.08);
        border-color: #fbbf24
    }

    .sqv-note-section label {
        font-size: .65rem;
        font-weight: 700;
        color: #b45309;
        text-transform: uppercase;
        display: block;
        margin-bottom: .5rem
    }

    /* ═══ COMPOSER & TIMELINE FEED ═══ */
    .sqv-activity-composer .nav-tabs .nav-link {
        border-radius: 8px !important;
        transition: all 0.2s;
        border: 1px solid transparent !important;
    }
    
    .sqv-activity-composer .nav-tabs .nav-link.active {
        background: #f1f5f9 !important;
        border: 1px solid #e2e8f0 !important;
    }

    .hover-scale {
        transition: transform 0.2s;
    }
    .hover-scale:hover {
        transform: scale(1.05);
        background: #e2e8f0 !important;
    }
    
    .sqv-feed-item.pinned .sqv-feed-card {
        background: #fffbeb !important;
        border-color: #fde68a !important;
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.05) !important;
    }
    
    .sqv-feed-item.important .sqv-feed-icon-circle {
        border-color: #f87171 !important;
        background: #fef2f2 !important;
        color: #ef4444 !important;
    }

    .sqv-feed-item {
        position: relative;
    }

    .sqv-feed-item:last-child .sqv-feed-line {
        display: none;
    }

    /* HIDE DEFAULT HEADER TOP (we use custom) */
    .qv-sales-wrapper>.qv-header .qv-header-top {
        display: none
    }

    .qv-sales-wrapper>.qv-header {
        padding-top: 0;
        padding-bottom: 0
    }

    @media(max-width:768px) {
        .sqv-header {
            flex-direction: column;
            align-items: flex-start;
            padding: 1rem
        }

        .sqv-header-right {
            width: 100%;
            justify-content: flex-end
        }

        .sqv-pipeline {
            overflow-x: auto;
            justify-content: flex-start
        }

        .sqv-metrics-bar {
            overflow-x: auto;
            justify-content: flex-start;
            gap: 1rem;
        }
    }

    /* ═══ PREMIUM ADD ITEM MODAL ═══ */
    #qvAddItemModal .modal-content {
        border-radius: 24px !important;
        border: none !important;
        box-shadow: 0 20px 50px rgba(15, 23, 42, 0.15) !important;
        overflow: hidden;
    }
    #qvAddItemModal .modal-header {
        border-bottom: 1px solid #f1f5f9 !important;
        background: linear-gradient(to right, #fafbff, #fff) !important;
        padding: 1.25rem 1.5rem !important;
    }
    #qvAddItemModal .modal-title {
        font-weight: 850 !important;
        color: #0f172a !important;
        font-size: 1.2rem !important;
        letter-spacing: -0.03em !important;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    #qvAddItemModal .modal-body {
        padding: 1.75rem 1.5rem !important;
        background: #fff !important;
    }
    #qvAddItemModal .form-label {
        font-size: 0.74rem !important;
        font-weight: 750 !important;
        color: #475569 !important;
        text-transform: uppercase !important;
        letter-spacing: 0.06em !important;
        margin-bottom: 0.45rem !important;
    }
    #qvAddItemModal .form-control, #qvAddItemModal .form-select {
        border-radius: 14px !important;
        border: 1.5px solid #e2e8f0 !important;
        padding: 0.7rem 0.95rem !important;
        font-size: 0.88rem !important;
        font-weight: 550 !important;
        transition: all 0.2s ease-in-out !important;
        background: #fafbff !important;
        color: #1e293b !important;
    }
    #qvAddItemModal .form-control:focus, #qvAddItemModal .form-select:focus {
        border-color: #6366f1 !important;
        box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.12) !important;
        background: #fff !important;
    }
    #qvAddItemModal .modal-footer {
        border-top: 1px solid #f1f5f9 !important;
        padding: 1.25rem 1.5rem !important;
        background: #fafbff !important;
    }
    #qvAddItemModal .modal-footer .btn-light {
        border-radius: 12px !important;
        padding: 0.65rem 1.5rem !important;
        font-weight: 700 !important;
        font-size: 0.85rem !important;
        background: #f1f5f9 !important;
        border: none !important;
        color: #475569 !important;
        transition: all 0.2s !important;
    }
    #qvAddItemModal .modal-footer .btn-light:hover {
        background: #e2e8f0 !important;
        color: #1e293b !important;
    }
    #qvAddItemModal .modal-footer .btn-primary {
        background: linear-gradient(135deg, #6366f1, #4f46e5) !important;
        border: none !important;
        border-radius: 12px !important;
        padding: 0.65rem 1.75rem !important;
        font-weight: 700 !important;
        font-size: 0.85rem !important;
        box-shadow: 0 4px 14px rgba(99, 102, 241, 0.35) !important;
        transition: all 0.2s !important;
    }
    #qvAddItemModal .modal-footer .btn-primary:hover {
        transform: translateY(-1px) !important;
        box-shadow: 0 6px 20px rgba(99, 102, 241, 0.45) !important;
    }

    /* PREMIUM SPREADSHEET PRODUCTS STYLES */
    .qv-product-row input.form-control,
    .qv-product-row select.form-select {
        border-radius: 0;
        box-shadow: none;
        border: none;
        border-bottom: 1px dashed #e2e8f0;
        padding: 6px 8px;
        transition: all 0.2s;
    }
    .qv-product-row input.form-control:hover,
    .qv-product-row select.form-select:hover {
        background: #f8fafc !important;
        border-bottom: 1px solid #cbd5e1 !important;
    }
    .qv-product-row input.form-control:focus,
    .qv-product-row select.form-select:focus {
        background: #fff !important;
        border-bottom: 2px solid #2563eb !important;
    }

    /* PRODUCT NAME CELL - text input + catalog button */
    .qv-product-name-cell {
        display: flex;
        align-items: center;
        gap: 6px;
    }
    .qv-product-name-cell .qv-product-name {
        flex: 1;
        min-width: 0;
    }
    .btn-catalog-pick {
        flex-shrink: 0;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 5px 10px;
        border-radius: 8px;
        background: linear-gradient(135deg, #6366f1, #4f46e5);
        color: #fff;
        font-size: 0.72rem;
        font-weight: 700;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(99,102,241,0.3);
    }
    .btn-catalog-pick:hover {
        background: linear-gradient(135deg, #4f46e5, #3730a3);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(99,102,241,0.4);
        color: #fff;
    }
    .btn-catalog-pick i {
        font-size: 0.7rem;
    }

    /* CATALOG MODAL STYLES */
    #qvProductCatalogModal .modal-content {
        backdrop-filter: blur(10px);
    }
    #catalogSearchInput::placeholder { color: #64748b; }
    #catalogSearchInput:focus {
        background: rgba(255,255,255,0.14) !important;
        border-color: rgba(99,102,241,0.5) !important;
        box-shadow: 0 0 0 3px rgba(99,102,241,0.15) !important;
        outline: none;
        color: #fff !important;
    }
    #catalogTypeFilter option { background: #1e293b; color: #fff; }
    .catalog-product-card {
        background: #fff;
        border-radius: 14px;
        padding: 14px 14px;
        cursor: pointer;
        border: 1.5px solid #f1f5f9;
        transition: all 0.18s cubic-bezier(0.4, 0, 0.2, 1);
        height: 100%;
    }
    .catalog-product-card:hover {
        border-color: #6366f1;
        box-shadow: 0 4px 20px rgba(99,102,241,0.12);
        transform: translateY(-2px);
    }
    .catalog-product-card:hover .catalog-product-select-btn {
        background: #6366f1;
        color: #fff;
    }
    .catalog-product-icon {
        width: 38px;
        height: 38px;
        border-radius: 10px;
        background: linear-gradient(135deg, #ede9fe, #ddd6fe);
        color: #6366f1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1rem;
        flex-shrink: 0;
    }
    .catalog-product-name {
        font-weight: 700;
        font-size: 0.85rem;
        color: #1e293b;
        line-height: 1.3;
        margin-bottom: 3px;
    }
    .catalog-product-desc {
        font-size: 0.72rem;
        color: #94a3b8;
        line-height: 1.4;
    }
    .catalog-product-price {
        font-size: 0.82rem;
        font-weight: 800;
        color: #2563eb;
        white-space: nowrap;
        margin-bottom: 4px;
    }
    .catalog-product-select-btn {
        font-size: 0.68rem;
        font-weight: 700;
        color: #6366f1;
        background: #ede9fe;
        border-radius: 6px;
        padding: 2px 8px;
        display: inline-block;
        transition: all 0.15s;
    }
    .catalog-type-badge {
        display: inline-block;
    }
</style>