{{--
    Kişi ↔ şirket bağı yönetimi (quick-view).

    Aynı bileşen iki yönü de yönetir: şirket kartında "bağlı kişiler",
    kişi kartında "bağlı şirketler". Bağ kurmak drawer'da mümkün değildi;
    yalnızca müşteri ekleme/düzenleme formundan yapılabiliyordu.

    Beklenen: $customer, $linkedCompanies, $members
--}}
@php
    // Kart tipi terminolojisi:
    //   Şirket kartı  → adı/soyadı olmayan, doğrudan firma olan müşteri kaydı
    //   Kişi kartı    → gerçek kişi; bir şirkete bağlıysa "kurumsal müşteri" sayılır
    $isCompanyCard = $customer->customer_type === 'corporate';
    $linked = $isCompanyCard ? ($members ?? collect()) : ($linkedCompanies ?? collect());
    $title = $isCompanyCard ? 'Bu Şirkete Bağlı Kişiler' : 'Şirketler';
    $hint = $isCompanyCard
        ? 'Bu firma altında çalışan kişiler. Bağlanan kişiler kurumsal müşteri sayılır; faturaları bu firmaya kesilebilir.'
        : 'Bu kişinin çalıştığı firmalar. Bağ kurulduğunda kişi kurumsal müşteri sayılır ve faturası firmaya kesilebilir. Yıldızlı firma, faturada varsayılan unvandır.';
@endphp

<div class="qv-card shadow-sm border-0 mt-4 clnk" data-customer="{{ $customer->id }}" style="border-radius: 20px;">
    <div class="clnk-head">
        <h5 class="fw-800 text-dark mb-0">
            <i class="fas {{ $isCompanyCard ? 'fa-users' : 'fa-building' }} me-2 text-primary"></i>
            {{ $title }}
            <span class="clnk-count">{{ $linked->count() }}</span>
        </h5>
        <button type="button" class="clnk-addbtn" onclick="clnkToggle(this)">
            <i class="fas fa-plus"></i> {{ $isCompanyCard ? 'Kişi Bağla' : 'Şirket Bağla' }}
        </button>
    </div>

    <div class="clnk-picker" hidden>
        <div class="clnk-search">
            <i class="fas fa-magnifying-glass"></i>
            <input type="text" class="clnk-input" placeholder="{{ $isCompanyCard ? 'Kişi ara…' : 'Şirket ara…' }}" autocomplete="off">
        </div>
        <div class="clnk-results" hidden></div>
    </div>

    <div class="clnk-list">
        @forelse($linked as $item)
            @php $isPrimary = (bool) ($item->pivot->is_primary ?? false); @endphp
            <div class="clnk-item {{ $isPrimary ? 'is-primary' : '' }}" data-id="{{ $item->id }}">
                <span class="clnk-av {{ $isCompanyCard ? '' : 'is-company' }}">{{ $item->initials }}</span>
                <div class="clnk-txt" onclick="openCustomerDrawer({{ $item->id }})">
                    <b>
                        {{ $isCompanyCard ? $item->full_name : ($item->company_name ?: $item->full_name) }}
                        @if($isPrimary)<span class="clnk-primary-tag">BİRİNCİL</span>@endif
                    </b>
                    <small>
                        {{ $isCompanyCard
                            ? ($item->company_position ?: 'Çalışan')
                            : ($item->company_type_label ?: 'Firma') }}
                    </small>
                </div>
                @unless($isCompanyCard)
                    <button type="button" class="clnk-star {{ $isPrimary ? 'on' : '' }}"
                            onclick="clnkPrimary(this, {{ $item->id }})"
                            title="{{ $isPrimary ? 'Birincil firma' : 'Birincil firma yap (fatura varsayılanı)' }}">
                        <i class="{{ $isPrimary ? 'fas' : 'far' }} fa-star"></i>
                    </button>
                @endunless
                <button type="button" class="clnk-x" onclick="clnkUnlink(this, {{ $item->id }})" title="Bağı kaldır">
                    <i class="fas fa-link-slash"></i>
                </button>
            </div>
        @empty
            <div class="clnk-empty">
                <i class="fas {{ $isCompanyCard ? 'fa-user-plus' : 'fa-building-circle-arrow-right' }}"></i>
                <span>{{ $isCompanyCard ? 'Bu şirkete bağlı kişi yok.' : 'Bu kişi henüz bir şirkete bağlı değil.' }}</span>
            </div>
        @endforelse
    </div>

    <div class="clnk-hint"><i class="fas fa-circle-info"></i> {{ $hint }}</div>
</div>

@once
<style>
    .clnk { padding: 1.25rem 1.4rem; }
    .clnk-head { display: flex; align-items: center; gap: .7rem; margin-bottom: .9rem; }
    .clnk-head h5 { font-size: 1rem; display: flex; align-items: center; gap: .5rem; }
    .clnk-count {
        font-size: .68rem; font-weight: 800; color: #475569; background: #f1f5f9;
        border-radius: 999px; padding: 2px 9px;
    }
    .clnk-addbtn {
        margin-left: auto; display: inline-flex; align-items: center; gap: 6px; cursor: pointer;
        border: 1.5px dashed #c7d2fe; background: #eef2ff; color: #4338ca;
        font-family: inherit; font-size: .76rem; font-weight: 800; padding: .42rem .9rem; border-radius: 10px;
        transition: all .16s;
    }
    .clnk-addbtn:hover { background: #e0e7ff; border-color: #6366f1; }

    .clnk-picker { position: relative; margin-bottom: .8rem; }
    .clnk-picker[hidden] { display: none; }
    .clnk-search { position: relative; }
    .clnk-search > i { position: absolute; left: .8rem; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: .8rem; }
    .clnk-input {
        width: 100%; border: 1.5px solid #e8edf4; background: #fff; border-radius: 11px;
        padding: .55rem .8rem .55rem 2.1rem; font-family: inherit; font-size: .85rem; color: #0f172a; outline: none;
    }
    .clnk-input:focus { border-color: #6366f1; box-shadow: 0 0 0 3px rgba(99, 102, 241, .12); }
    .clnk-results {
        position: absolute; top: calc(100% + 5px); left: 0; right: 0; z-index: 40; max-height: 230px; overflow-y: auto;
        background: #fff; border: 1px solid #e8edf4; border-radius: 12px; box-shadow: 0 18px 40px rgba(15,23,42,.14); padding: 5px;
    }
    .clnk-results[hidden] { display: none; }
    .clnk-results button {
        display: block; width: 100%; text-align: left; border: none; background: none; cursor: pointer;
        padding: .45rem .6rem; border-radius: 9px; font-family: inherit;
    }
    .clnk-results button:hover { background: #eef2ff; }
    .clnk-results b { display: block; font-size: .84rem; font-weight: 700; color: #0f172a; }
    .clnk-results small { display: block; font-size: .7rem; color: #94a3b8; }

    .clnk-list { display: flex; flex-wrap: wrap; gap: 8px; }
    .clnk-item {
        display: flex; align-items: center; gap: .65rem; padding: .6rem .75rem; min-width: 210px;
        background: #fff; border: 1px solid #e8edf4; border-radius: 14px; transition: all .16s;
    }
    .clnk-item:hover { border-color: #c7d2fe; box-shadow: 0 8px 20px -14px rgba(15,23,42,.5); }
    .clnk-av {
        width: 34px; height: 34px; flex: none; border-radius: 11px; display: grid; place-items: center;
        color: #fff; font-size: .76rem; font-weight: 800;
        background: linear-gradient(135deg, #2563eb, #1e40af);
    }
    .clnk-av.is-company { background: linear-gradient(135deg, #475569, #1e293b); }
    .clnk-txt { min-width: 0; flex: 1; cursor: pointer; }
    .clnk-txt b { display: block; font-size: .84rem; font-weight: 800; color: #0f172a; line-height: 1.2; }
    .clnk-txt small { display: block; font-size: .72rem; color: #94a3b8; }
    .clnk-x, .clnk-star {
        width: 28px; height: 28px; flex: none; border-radius: 9px; display: grid; place-items: center;
        border: 1px solid #e8edf4; background: #fff; color: #cbd5e1; cursor: pointer; font-size: .72rem; transition: all .15s;
    }
    .clnk-x:hover { border-color: #fca5a5; color: #dc2626; background: #fef2f2; }
    .clnk-star:hover { border-color: #fcd34d; color: #d97706; background: #fffbeb; }
    .clnk-star.on { border-color: #fcd34d; color: #f59e0b; background: #fffbeb; }
    .clnk-item.is-primary { border-color: #fde68a; background: linear-gradient(180deg, #fffefb, #fffbeb); }
    .clnk-primary-tag {
        margin-left: 6px; font-size: .55rem; font-weight: 800; letter-spacing: .06em;
        color: #b45309; background: #fef3c7; border-radius: 5px; padding: 1px 5px; vertical-align: middle;
    }

    .clnk-empty {
        display: flex; align-items: center; gap: .6rem; padding: 1rem; width: 100%;
        background: #fbfcfe; border: 1px dashed #e2e8f0; border-radius: 14px; color: #94a3b8;
        font-size: .82rem; font-weight: 600;
    }
    .clnk-empty i { font-size: 1rem; color: #cbd5e1; }

    .clnk-hint { margin-top: .8rem; font-size: .72rem; color: #94a3b8; line-height: 1.5; }
    .clnk-hint i { color: #cbd5e1; margin-right: 4px; }
</style>
@endonce

<script>
(function () {
    // Kart yeniden enjekte edildiğinde tekrar bağlanmasın
    if (window.__clnkBound) return;
    window.__clnkBound = true;

    const csrf = () => document.querySelector('meta[name="csrf-token"]')?.content || '';
    const rootOf = el => el.closest('.clnk');
    const idOf = el => rootOf(el)?.dataset.customer;

    window.clnkToggle = function (btn) {
        const picker = rootOf(btn).querySelector('.clnk-picker');
        picker.hidden = !picker.hidden;
        if (!picker.hidden) {
            const input = picker.querySelector('.clnk-input');
            input.focus();
            clnkSearch(input);
        }
    };

    let timer = null;
    function clnkSearch(input) {
        const root = rootOf(input);
        const box = root.querySelector('.clnk-results');
        clearTimeout(timer);
        timer = setTimeout(() => {
            fetch(`/agency/customers/${idOf(input)}/link-candidates?q=` + encodeURIComponent(input.value.trim()),
                { headers: { Accept: 'application/json' } })
                .then(r => r.json())
                .then(d => {
                    if (!d.results?.length) {
                        box.innerHTML = '<div style="padding:.6rem;text-align:center;font-size:.78rem;color:#94a3b8">Uygun kayıt yok</div>';
                        box.hidden = false;
                        return;
                    }
                    box.innerHTML = d.results.map(r =>
                        `<button type="button" data-target="${r.id}"><b>${r.label}</b><small>${r.sub || ''}</small></button>`).join('');
                    box.hidden = false;
                })
                .catch(() => {});
        }, 220);
    }

    document.addEventListener('input', e => {
        if (e.target.classList?.contains('clnk-input')) clnkSearch(e.target);
    });

    document.addEventListener('click', e => {
        const opt = e.target.closest('.clnk-results button[data-target]');
        if (opt) {
            const id = idOf(opt);
            fetch(`/agency/customers/${id}/link`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': csrf() },
                body: JSON.stringify({ target_id: opt.dataset.target }),
            })
            .then(r => r.json())
            .then(d => {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({ toast: true, position: 'top-end', timer: 1900, showConfirmButton: false,
                        icon: d.success ? 'success' : 'error', title: d.message });
                }
                if (d.success && typeof openCustomerDrawer === 'function') openCustomerDrawer(id, 'details');
            });
            return;
        }
        // Panel dışına tıklanınca sonuçları kapat
        if (!e.target.closest('.clnk-picker')) {
            document.querySelectorAll('.clnk-results').forEach(b => { b.hidden = true; });
        }
    });

    window.clnkPrimary = function (btn, companyId) {
        const id = idOf(btn);
        fetch(`/agency/customers/${id}/primary-company/${companyId}`, {
            method: 'POST',
            headers: { Accept: 'application/json', 'X-CSRF-TOKEN': csrf() },
        })
        .then(r => r.json())
        .then(d => {
            if (typeof Swal !== 'undefined') {
                Swal.fire({ toast: true, position: 'top-end', timer: 1900, showConfirmButton: false,
                    icon: d.success ? 'success' : 'error', title: d.message });
            }
            if (d.success && typeof openCustomerDrawer === 'function') openCustomerDrawer(id, 'details');
        });
    };

    window.clnkUnlink = function (btn, targetId) {
        const id = idOf(btn);
        const run = () => fetch(`/agency/customers/${id}/link/${targetId}`, {
            method: 'DELETE',
            headers: { Accept: 'application/json', 'X-CSRF-TOKEN': csrf() },
        })
        .then(r => r.json())
        .then(d => {
            if (d.success && typeof openCustomerDrawer === 'function') openCustomerDrawer(id, 'details');
        });

        if (typeof Swal !== 'undefined') {
            Swal.fire({ title: 'Bağ kaldırılsın mı?', icon: 'question', showCancelButton: true,
                confirmButtonText: 'Evet, kaldır', cancelButtonText: 'Vazgeç', confirmButtonColor: '#dc2626' })
                .then(r => r.isConfirmed && run());
        } else if (confirm('Bağ kaldırılsın mı?')) run();
    };
})();
</script>
