{{-- Yeni Görev modalı — index shell'inden include edilir --}}
<div class="modal fade" id="taskCreateModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width: 640px;">
        <div class="modal-content tkm">
            <form method="POST" action="{{ route('agency.tasks.store') }}">
                @csrf

                <div class="tkm-head">
                    <div class="tkm-head-ico"><i class="fas fa-list-check"></i></div>
                    <div>
                        <h5>Yeni Görev</h5>
                        <p>Görevi tanımlayın, dilerseniz kayıt ve kişilerle ilişkilendirin.</p>
                    </div>
                    <button type="button" class="btn-close ms-auto" data-bs-dismiss="modal" aria-label="Kapat"></button>
                </div>

                <div class="tkm-body">
                    <div class="tkm-field">
                        <label>Başlık <span>*</span></label>
                        <input type="text" name="title" class="tkm-input" required maxlength="255"
                               placeholder="Ör. Kesin kalkış öncesi otel onaylarını kontrol et">
                    </div>

                    <div class="tkm-field">
                        <label>Açıklama</label>
                        <textarea name="description" class="tkm-input" rows="3" maxlength="5000"
                                  placeholder="Görevin detayları…"></textarea>
                    </div>

                    <div class="tkm-row">
                        <div class="tkm-field">
                            <label>Son Tarih</label>
                            <input type="datetime-local" name="due_date" class="tkm-input">
                        </div>
                        <div class="tkm-field">
                            <label>Öncelik</label>
                            <div class="tkm-pills">
                                @foreach(\App\Models\Task\Task::PRIORITIES as $key => $meta)
                                    <label class="tkm-pill" style="--pc: {{ $meta['color'] }};">
                                        <input type="radio" name="priority" value="{{ $key }}" {{ $key === 'normal' ? 'checked' : '' }}>
                                        <span>{{ $meta['label'] }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>
                    </div>

                    @if($canAssign)
                        <div class="tkm-field">
                            <label>Atananlar <small>(boş bırakılırsa görev size atanır)</small></label>
                            <div class="tkm-staff">
                                @foreach($staffUsers as $su)
                                    <label class="tkm-staff-chip">
                                        <input type="checkbox" name="assignees[]" value="{{ $su->id }}" {{ $su->id === auth()->id() ? 'checked' : '' }}>
                                        <span class="tkm-staff-av">{{ $su->initials }}</span>
                                        <span>{{ $su->full_name }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>
                    @else
                        <div class="tkm-note"><i class="fas fa-circle-info"></i> Görev size atanacaktır.</div>
                    @endif

                    {{-- ── İlişkili Kayıtlar: sabit yükseklikli bağlama paneli ── --}}
                    <div class="tkm-field">
                        <label>İlişkili Kayıtlar <small>(isteğe bağlı — görevi ilgili kayıtlara bağlayın)</small></label>

                        <div class="tkl" id="tkLinker">
                            <div class="tkl-chips" id="tkLinkerChips"></div>

                            <button type="button" class="tkl-trigger" id="tkLinkerTrigger">
                                <span class="tkl-trigger-ico"><i class="fas fa-link"></i></span>
                                <span class="tkl-trigger-text">
                                    <b>Kayıt Bağla</b>
                                    <small>Müşteri, satış, tur kalkışı, tedarikçi veya kaynak arayın</small>
                                </span>
                                <i class="fas fa-chevron-down tkl-chev"></i>
                            </button>

                            <div class="tkl-panel" id="tkLinkerPanel">
                                <div class="tkl-search">
                                    <i class="fas fa-magnifying-glass"></i>
                                    <input type="text" id="tkLinkerInput" placeholder="Aramak için en az 2 karakter yazın…" autocomplete="off">
                                    <span class="tkl-spin" id="tkLinkerSpin"><i class="fas fa-circle-notch fa-spin"></i></span>
                                </div>

                                <div class="tkl-types" id="tkLinkerTypes">
                                    <button type="button" class="tkl-type on" data-type="">Tümü</button>
                                    <button type="button" class="tkl-type" data-type="customer"><i class="fas fa-user"></i> Müşteri</button>
                                    <button type="button" class="tkl-type" data-type="sale"><i class="fas fa-shopping-cart"></i> Satış</button>
                                    <button type="button" class="tkl-type" data-type="date"><i class="fas fa-calendar-days"></i> Kalkış</button>
                                    <button type="button" class="tkl-type" data-type="supplier"><i class="fas fa-handshake"></i> Tedarikçi</button>
                                    <button type="button" class="tkl-type" data-type="resource"><i class="fas fa-id-badge"></i> Kaynak</button>
                                </div>

                                <div class="tkl-results" id="tkLinkerResults">
                                    <div class="tkl-state">
                                        <i class="fas fa-wand-magic-sparkles"></i>
                                        <b>Kayıt arayın</b>
                                        <span>Ad, kod veya tarih yazın — sonuçlar burada listelenir</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tkm-foot">
                    <button type="button" class="tkm-btn ghost" data-bs-dismiss="modal">Vazgeç</button>
                    <button type="submit" class="tkm-btn solid"><i class="fas fa-plus"></i> Görevi Oluştur</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('styles')
<style>
    .tkm { border: none; border-radius: 18px; overflow: hidden; }
    .tkm-head { display: flex; align-items: flex-start; gap: .9rem; padding: 1.25rem 1.4rem 1rem; border-bottom: 1px solid #f1f5f9; }
    .tkm-head-ico {
        width: 44px; height: 44px; border-radius: 13px; flex-shrink: 0;
        background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff;
        display: flex; align-items: center; justify-content: center; font-size: 1.1rem;
        box-shadow: 0 8px 18px -8px rgba(217,119,6,.6);
    }
    .tkm-head h5 { margin: 0 0 .15rem; font-weight: 800; color: #0f172a; letter-spacing: -0.02em; }
    .tkm-head p { margin: 0; font-size: .78rem; color: #94a3b8; font-weight: 600; }

    .tkm-body { padding: 1.15rem 1.4rem; display: flex; flex-direction: column; gap: .95rem; max-height: 68vh; overflow-y: auto; }
    .tkm-row { display: grid; grid-template-columns: 1fr 1.4fr; gap: .9rem; }
    .tkm-field label { display: block; font-size: .74rem; font-weight: 800; color: #475569; text-transform: uppercase; letter-spacing: .04em; margin-bottom: .35rem; }
    .tkm-field label span { color: #ef4444; }
    .tkm-field label small { text-transform: none; letter-spacing: 0; font-weight: 600; color: #94a3b8; }
    .tkm-input {
        width: 100%; border: 1px solid #e2e8f0; border-radius: 10px; padding: .55rem .75rem;
        font-size: .85rem; color: #1e293b; background: #fff; transition: border-color .15s, box-shadow .15s;
    }
    .tkm-input:focus { outline: none; border-color: #fbbf24; box-shadow: 0 0 0 3px rgba(251,191,36,.18); }

    .tkm-pills { display: flex; gap: .4rem; flex-wrap: wrap; }
    .tkm-pill { margin: 0; cursor: pointer; }
    .tkm-pill input { display: none; }
    .tkm-pill span {
        display: inline-block; font-size: .76rem; font-weight: 800; color: #64748b;
        border: 1.5px solid #e2e8f0; border-radius: 999px; padding: .32rem .8rem; transition: all .15s ease;
    }
    .tkm-pill input:checked + span { color: var(--pc); border-color: var(--pc); background: color-mix(in srgb, var(--pc) 10%, #fff); }

    .tkm-staff { display: flex; flex-wrap: wrap; gap: .45rem; max-height: 150px; overflow-y: auto; padding: .1rem; }
    .tkm-staff-chip { display: inline-flex; align-items: center; gap: .45rem; margin: 0; cursor: pointer;
        border: 1.5px solid #e2e8f0; border-radius: 999px; padding: .28rem .75rem .28rem .3rem;
        font-size: .78rem; font-weight: 700; color: #475569; transition: all .15s ease; }
    .tkm-staff-chip input { display: none; }
    .tkm-staff-av { width: 24px; height: 24px; border-radius: 50%; background: #e2e8f0; color: #475569;
        font-size: .6rem; font-weight: 800; display: inline-flex; align-items: center; justify-content: center; }
    .tkm-staff-chip:has(input:checked) { border-color: #d97706; background: #fffbeb; color: #92400e; }
    .tkm-staff-chip:has(input:checked) .tkm-staff-av { background: #fde68a; color: #92400e; }

    .tkm-note { font-size: .8rem; font-weight: 600; color: #64748b; background: #f8fafc; border: 1px dashed #e2e8f0; border-radius: 10px; padding: .55rem .8rem; }
    .tkm-note i { color: #94a3b8; margin-right: .3rem; }

    .tkm-foot { display: flex; justify-content: flex-end; gap: .6rem; padding: 1rem 1.4rem; border-top: 1px solid #f1f5f9; background: #fafbfc; }
    .tkm-btn { display: inline-flex; align-items: center; gap: .45rem; border: none; cursor: pointer;
        font-size: .84rem; font-weight: 800; padding: .55rem 1.15rem; border-radius: 11px; transition: all .15s ease; }
    .tkm-btn.ghost { background: #fff; border: 1px solid #e2e8f0; color: #64748b; }
    .tkm-btn.ghost:hover { background: #f8fafc; color: #1e293b; }
    .tkm-btn.solid { background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; box-shadow: 0 6px 16px -6px rgba(217,119,6,.55); }
    .tkm-btn.solid:hover { transform: translateY(-1px); filter: brightness(1.05); }

    /* ═══ Kayıt Bağlama Paneli (tkl) ═══
       Sabit yükseklikli sonuç alanı: modal arama sırasında ASLA uzamaz,
       sonuçlar panelin kendi içinde kayar. Tür renkleri modül renkleriyle uyumlu. */
    .tkl { --t-customer: #6366f1; --t-sale: #10b981; --t-date: #0ea5e9; --t-supplier: #f43f5e; --t-resource: #14b8a6; }

    .tkl-chips { display: flex; flex-wrap: wrap; gap: .4rem; margin-bottom: .45rem; }
    .tkl-chips:empty { display: none; }
    .tkl-chip {
        display: inline-flex; align-items: center; gap: .45rem; max-width: 100%;
        font-size: .75rem; font-weight: 700; color: #1e293b;
        background: #fff; border: 1.5px solid color-mix(in srgb, var(--tc, #94a3b8) 45%, #fff);
        border-left: 4px solid var(--tc, #94a3b8);
        border-radius: 9px; padding: .3rem .55rem .3rem .5rem;
        box-shadow: 0 1px 4px rgba(15,23,42,.05);
        animation: tklChipIn .18s ease;
    }
    @keyframes tklChipIn { from { opacity: 0; transform: scale(.92); } to { opacity: 1; transform: scale(1); } }
    .tkl-chip > i:first-child { color: var(--tc, #94a3b8); font-size: .72rem; }
    .tkl-chip em { font-style: normal; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 230px; }
    .tkl-chip-x {
        display: inline-flex; align-items: center; justify-content: center;
        width: 18px; height: 18px; border-radius: 6px; cursor: pointer; color: #94a3b8; font-size: .66rem;
        transition: all .12s ease; flex-shrink: 0;
    }
    .tkl-chip-x:hover { background: #fee2e2; color: #dc2626; }

    .tkl-trigger {
        display: flex; align-items: center; gap: .7rem; width: 100%; text-align: left; cursor: pointer;
        background: #fafbfc; border: 1.5px dashed #d7dee9; border-radius: 12px; padding: .6rem .8rem;
        transition: all .18s ease;
    }
    .tkl-trigger:hover { border-color: #fbbf24; background: #fffdf5; }
    .tkl-trigger-ico {
        width: 34px; height: 34px; border-radius: 10px; flex-shrink: 0;
        background: #fef3c7; color: #d97706; display: inline-flex; align-items: center; justify-content: center;
        font-size: .82rem; transition: all .18s ease;
    }
    .tkl-trigger:hover .tkl-trigger-ico { background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; }
    .tkl-trigger-text { flex: 1; min-width: 0; display: flex; flex-direction: column; line-height: 1.25; }
    .tkl-trigger-text b { font-size: .8rem; font-weight: 800; color: #334155; }
    .tkl-trigger-text small { font-size: .7rem; font-weight: 600; color: #94a3b8; }
    .tkl-chev { color: #b6c2d2; font-size: .72rem; transition: transform .22s ease; }

    .tkl.open .tkl-trigger { border-style: solid; border-color: #fbbf24; border-bottom-left-radius: 0; border-bottom-right-radius: 0; background: #fffbeb; }
    .tkl.open .tkl-chev { transform: rotate(180deg); }

    .tkl-panel {
        display: none;
        border: 1.5px solid #fbbf24; border-top: none;
        border-radius: 0 0 12px 12px; background: #fff; overflow: hidden;
        box-shadow: 0 14px 30px -14px rgba(15,23,42,.18);
    }
    .tkl.open .tkl-panel { display: block; animation: tklPanelIn .18s ease; }
    @keyframes tklPanelIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }

    .tkl-search { position: relative; border-bottom: 1px solid #f1f5f9; }
    .tkl-search > i { position: absolute; left: .85rem; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: .78rem; }
    .tkl-search input {
        width: 100%; border: none; padding: .68rem .9rem .68rem 2.25rem; font-size: .84rem; color: #1e293b; background: transparent;
    }
    .tkl-search input:focus { outline: none; }
    .tkl-spin { position: absolute; right: .8rem; top: 50%; transform: translateY(-50%); color: #d97706; font-size: .76rem; visibility: hidden; }
    .tkl-spin.on { visibility: visible; }

    .tkl-types { display: flex; gap: .3rem; padding: .5rem .65rem; border-bottom: 1px solid #f1f5f9; overflow-x: auto; scrollbar-width: none; }
    .tkl-types::-webkit-scrollbar { display: none; }
    .tkl-type {
        display: inline-flex; align-items: center; gap: .32rem; border: 1px solid #e9edf3; background: #fff;
        color: #64748b; font-size: .7rem; font-weight: 800; padding: .26rem .6rem; border-radius: 999px;
        cursor: pointer; white-space: nowrap; transition: all .14s ease;
    }
    .tkl-type i { font-size: .62rem; opacity: .65; }
    .tkl-type:hover { border-color: #cbd5e1; color: #334155; }
    .tkl-type.on { background: #1e293b; border-color: #1e293b; color: #fff; }
    .tkl-type.on i { opacity: 1; }

    /* Sabit yükseklikli sonuç alanı — modalın uzamasını önleyen kilit parça */
    .tkl-results { height: 232px; overflow-y: auto; scrollbar-width: thin; scrollbar-color: #e2e8f0 transparent; }
    .tkl-results::-webkit-scrollbar { width: 5px; }
    .tkl-results::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 4px; }

    .tkl-state {
        height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center;
        gap: .3rem; padding: 1rem; text-align: center;
    }
    .tkl-state i { font-size: 1.3rem; color: #d7dee9; margin-bottom: .25rem; }
    .tkl-state b { font-size: .8rem; font-weight: 800; color: #64748b; }
    .tkl-state span { font-size: .72rem; font-weight: 600; color: #b6c2d2; max-width: 300px; }

    .tkl-group { font-size: .64rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; letter-spacing: .06em; padding: .6rem .85rem .25rem; }
    .tkl-row {
        display: flex; align-items: center; gap: .65rem; padding: .5rem .85rem; cursor: pointer;
        transition: background .12s ease;
    }
    .tkl-row:hover { background: #f8fafc; }
    .tkl-row-ico {
        width: 32px; height: 32px; border-radius: 9px; flex-shrink: 0;
        background: color-mix(in srgb, var(--tc, #94a3b8) 12%, #fff); color: var(--tc, #94a3b8);
        display: inline-flex; align-items: center; justify-content: center; font-size: .76rem;
    }
    .tkl-row-body { flex: 1; min-width: 0; }
    .tkl-row-body b { display: block; font-size: .8rem; font-weight: 700; color: #1e293b; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .tkl-row-body small { font-size: .68rem; font-weight: 600; color: #94a3b8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; }
    .tkl-row-tag {
        flex-shrink: 0; font-size: .62rem; font-weight: 800; letter-spacing: .02em;
        color: var(--tc, #64748b); background: color-mix(in srgb, var(--tc, #94a3b8) 10%, #fff);
        border: 1px solid color-mix(in srgb, var(--tc, #94a3b8) 25%, #fff);
        padding: .14rem .5rem; border-radius: 999px; max-width: 130px;
        overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
    .tkl-row-check {
        width: 20px; height: 20px; border-radius: 50%; border: 1.5px solid #d7dee9; flex-shrink: 0;
        display: inline-flex; align-items: center; justify-content: center; font-size: .58rem; color: transparent;
        transition: all .14s ease;
    }
    .tkl-row:hover .tkl-row-check { border-color: var(--tc, #94a3b8); }
    .tkl-row.selected { background: color-mix(in srgb, var(--tc, #94a3b8) 6%, #fff); }
    .tkl-row.selected .tkl-row-check { background: var(--tc, #94a3b8); border-color: var(--tc, #94a3b8); color: #fff; }
</style>
@endpush

@push('scripts')
<script>
    function openTaskCreateModal() {
        const modalEl = document.getElementById('taskCreateModal');
        if (modalEl) bootstrap.Modal.getOrCreateInstance(modalEl).show();
    }

    (function () {
        const SEARCH_URL = "{{ route('agency.tasks.search-entities') }}";
        const linker = document.getElementById('tkLinker');
        if (!linker) return;

        const trigger = document.getElementById('tkLinkerTrigger');
        const panel = document.getElementById('tkLinkerPanel');
        const input = document.getElementById('tkLinkerInput');
        const spin = document.getElementById('tkLinkerSpin');
        const results = document.getElementById('tkLinkerResults');
        const chips = document.getElementById('tkLinkerChips');
        const typeBtns = [...document.querySelectorAll('#tkLinkerTypes .tkl-type')];

        const selected = new Map();   // key → item
        let lastItems = [];
        let activeType = '';
        let timer = null;
        let reqSeq = 0;

        // key önekinden tür çıkar: tour_date/international_tour_date/day_* → 'date'
        const typeOf = (key) => {
            const alias = key.split(':')[0];
            return alias.endsWith('_date') ? 'date' : alias;
        };
        const colorVar = (type) => `var(--t-${type}, #94a3b8)`;

        function state(icon, title, text) {
            results.innerHTML = '';
            const div = document.createElement('div');
            div.className = 'tkl-state';
            div.innerHTML = `<i class="fas ${icon}"></i><b></b><span></span>`;
            div.querySelector('b').textContent = title;
            div.querySelector('span').textContent = text;
            results.appendChild(div);
        }

        function renderChips() {
            chips.innerHTML = '';
            selected.forEach((item, key) => {
                const type = typeOf(key);
                const chip = document.createElement('span');
                chip.className = 'tkl-chip';
                chip.style.setProperty('--tc', colorVar(type));
                chip.innerHTML = `<i class="fas ${item.icon}"></i><em></em><span class="tkl-chip-x"><i class="fas fa-xmark"></i></span>` +
                    `<input type="hidden" name="relations[]" value="${key}">`;
                chip.querySelector('em').textContent = item.label;
                chip.querySelector('.tkl-chip-x').addEventListener('click', () => {
                    selected.delete(key);
                    renderChips();
                    renderResults();
                });
                chips.appendChild(chip);
            });
        }

        function renderResults() {
            const items = lastItems.filter(it => !activeType || typeOf(it.key) === activeType);

            if (!items.length) {
                if (input.value.trim().length < 2) {
                    state('fa-wand-magic-sparkles', 'Kayıt arayın', 'Ad, kod veya tarih yazın — sonuçlar burada listelenir');
                } else {
                    state('fa-inbox', 'Sonuç bulunamadı', activeType ? 'Bu türde eşleşme yok — başka bir tür veya arama deneyin' : 'Farklı bir arama terimi deneyin');
                }
                return;
            }

            results.innerHTML = '';
            let lastGroup = null;
            items.forEach(it => {
                if (it.group !== lastGroup) {
                    lastGroup = it.group;
                    const g = document.createElement('div');
                    g.className = 'tkl-group';
                    g.textContent = it.group;
                    results.appendChild(g);
                }
                const type = typeOf(it.key);
                const row = document.createElement('div');
                row.className = 'tkl-row' + (selected.has(it.key) ? ' selected' : '');
                row.style.setProperty('--tc', colorVar(type));
                row.innerHTML = `<span class="tkl-row-ico"><i class="fas ${it.icon}"></i></span>` +
                    `<span class="tkl-row-body"><b></b><small></small></span>` +
                    (it.badge ? `<span class="tkl-row-tag"></span>` : '') +
                    `<span class="tkl-row-check"><i class="fas fa-check"></i></span>`;
                row.querySelector('b').textContent = it.label;
                row.querySelector('small').textContent = it.sub || '';
                if (it.badge) row.querySelector('.tkl-row-tag').textContent = it.badge;
                row.addEventListener('click', () => {
                    if (selected.has(it.key)) selected.delete(it.key);
                    else selected.set(it.key, it);
                    renderChips();
                    row.classList.toggle('selected', selected.has(it.key));
                });
                results.appendChild(row);
            });
        }

        function search(term) {
            const seq = ++reqSeq;
            spin.classList.add('on');
            fetch(SEARCH_URL + '?q=' + encodeURIComponent(term), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(r => r.json())
                .then(data => {
                    if (seq !== reqSeq) return; // eski istek — yut
                    lastItems = data.items || [];
                    renderResults();
                })
                .catch(() => { if (seq === reqSeq) state('fa-triangle-exclamation', 'Arama başarısız', 'Bağlantıyı kontrol edip tekrar deneyin'); })
                .finally(() => { if (seq === reqSeq) spin.classList.remove('on'); });
        }

        trigger.addEventListener('click', () => {
            linker.classList.toggle('open');
            if (linker.classList.contains('open')) setTimeout(() => input.focus(), 60);
        });

        input.addEventListener('input', () => {
            clearTimeout(timer);
            const term = input.value.trim();
            if (term.length < 2) { lastItems = []; renderResults(); return; }
            timer = setTimeout(() => search(term), 250);
        });

        input.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') { linker.classList.remove('open'); }
            if (e.key === 'Enter') {
                e.preventDefault();
                const first = results.querySelector('.tkl-row:not(.selected)');
                if (first) first.click();
            }
        });

        typeBtns.forEach(btn => btn.addEventListener('click', () => {
            typeBtns.forEach(b => b.classList.toggle('on', b === btn));
            activeType = btn.dataset.type;
            renderResults();
        }));

        // Modal kapanınca paneli topla (seçimler korunur)
        document.getElementById('taskCreateModal')?.addEventListener('hidden.bs.modal', () => {
            linker.classList.remove('open');
        });
    })();
</script>
@endpush
