{{--
    Ürün listelerinde klasör (kategori) gezinmesi — arayüz parçası.

    Tablo yapısı olduğu gibi korunur: klasörler tablonun ilk satırlarında,
    ürünler onların altında listelenir. Satıra sağ tıklandığında açılan menüden
    kayıt başka bir klasöre taşınabilir (folder mantığı).

    Beklenen:
      $type        : liste anahtarı (kultur-turlari | gunubirlik-turlar | yurtdisi-turlari)
      $indexRoute  : listenin route adı (ör. agency.products.kultur-turlari.index)
      $folderPath  : kırıntı yolu (ProductCategory koleksiyonu)
      $folders     : geçerli klasörün alt klasörleri
      $flat        : arama/filtre nedeniyle klasör kipi kapalı mı
--}}
@php
    $type = $type ?? '';
    $flat = $flat ?? false;
    $folders = $folders ?? collect();
    $folderPath = $folderPath ?? collect();
@endphp

@unless($flat)
    {{-- ══ KIRINTI YOLU ══ --}}
    <div class="pfd-crumbs">
        <a href="{{ route($indexRoute) }}" class="pfd-crumb {{ $folderPath->isEmpty() ? 'is-current' : '' }}">
            <i class="fas fa-folder-tree"></i> Tümü
        </a>
        @foreach($folderPath as $c)
            <i class="fas fa-chevron-right pfd-crumb-sep"></i>
            <a href="{{ route($indexRoute, ['folder' => $c->id]) }}"
               class="pfd-crumb {{ $loop->last ? 'is-current' : '' }}">{{ $c->name }}</a>
        @endforeach

        @if($folderPath->isNotEmpty())
            @php $up = $folderPath->count() > 1 ? $folderPath[$folderPath->count() - 2]->id : null; @endphp
            <a href="{{ route($indexRoute, $up ? ['folder' => $up] : []) }}" class="pfd-up" title="Üst klasöre çık">
                <i class="fas fa-turn-up"></i> Üst klasör
            </a>
        @endif
    </div>
@endunless

{{-- ══ SAĞ TIK MENÜSÜ + TAŞIMA PENCERESİ ══ --}}
<div class="pfd-menu" id="pfdMenu" hidden></div>

<div class="pfd-ov" id="pfdMoveOv" hidden>
    <div class="pfd-modal">
        <div class="pfd-modal-h">
            <i class="fas fa-folder-tree"></i>
            <div>
                <b>Klasöre Taşı</b>
                <small id="pfdMoveSub">—</small>
            </div>
            <button type="button" class="pfd-x" onclick="pfdCloseMove()"><i class="fas fa-xmark"></i></button>
        </div>

        <div class="pfd-search">
            <i class="fas fa-magnifying-glass"></i>
            <input type="text" id="pfdMoveSearch" placeholder="Klasör ara…" autocomplete="off">
        </div>

        <div class="pfd-list" id="pfdMoveList"></div>

        <div class="pfd-modal-f">
            <button type="button" class="dt-btn dt-btn-ghost dt-btn-sm" onclick="pfdCloseMove()">Vazgeç</button>
        </div>
    </div>
</div>

@once
@push('styles')
<style>
    /* ── Kırıntı yolu ── */
    .pfd-crumbs {
        display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
        margin: 0 0 12px; padding: 9px 13px;
        background: var(--bg-card, #fff); border: 1px solid var(--dt-border, #e9edf3); border-radius: 12px;
        font-size: .82rem;
    }
    .pfd-crumb { color: var(--dt-muted, #64748b); font-weight: 700; text-decoration: none; }
    .pfd-crumb:hover { color: var(--dt-primary, #4f46e5); }
    .pfd-crumb.is-current { color: var(--dt-text, #1e293b); }
    .pfd-crumb i { margin-right: 4px; font-size: .78rem; }
    .pfd-crumb-sep { font-size: .58rem; color: #cbd5e1; }
    .pfd-up {
        margin-left: auto; font-size: .74rem; font-weight: 700; text-decoration: none;
        color: var(--dt-muted, #64748b); background: var(--dt-head-bg, #f8fafc);
        border-radius: 8px; padding: 3px 10px;
    }
    .pfd-up:hover { color: var(--dt-primary, #4f46e5); }
    .pfd-up i { margin-right: 4px; }

    /* ── Klasör satırı: tablo satırı olarak durur, zemini hafif vurgulanır ── */
    .dt-table tbody tr.pfd-row > td { background: color-mix(in srgb, var(--dt-primary, #4f46e5) 3%, transparent); }
    .dt-table tbody tr.pfd-row:hover > td { background: color-mix(in srgb, var(--dt-primary, #4f46e5) 7%, transparent); }
    .pfd-ic {
        display: grid; place-items: center; width: 34px; height: 34px; margin: 0 auto;
        border-radius: 10px; font-size: .9rem;
        color: var(--fc); background: color-mix(in srgb, var(--fc) 13%, transparent);
    }
    .pfd-main { display: flex; align-items: center; gap: 14px; }
    .pfd-name { font-weight: 800; color: var(--dt-text, #1e293b); }
    .pfd-meta { display: flex; align-items: center; gap: 12px; font-size: .74rem; color: var(--dt-muted, #64748b); }
    .pfd-meta i { margin-right: 3px; font-size: .68rem; opacity: .7; }
    .pfd-desc { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 320px; opacity: .8; }
    .pfd-go { margin-left: auto; color: #cbd5e1; font-size: .75rem; }

    /* ── Sağ tık menüsü ── */
    .pfd-menu {
        position: fixed; z-index: 2000; min-width: 190px; padding: 5px;
        background: var(--bg-elevated, #fff); border: 1px solid var(--dt-border, #e9edf3);
        border-radius: 12px; box-shadow: 0 18px 40px rgba(15, 23, 42, .18);
        font-size: .82rem;
    }
    .pfd-menu button {
        display: flex; align-items: center; gap: 9px; width: 100%; border: none; background: none;
        padding: 7px 10px; border-radius: 8px; cursor: pointer; text-align: left;
        color: var(--dt-text, #1e293b); font: inherit; font-weight: 600;
    }
    .pfd-menu button:hover { background: var(--dt-primary-soft, #eef2ff); color: var(--dt-primary, #4f46e5); }
    .pfd-menu button i { width: 15px; text-align: center; font-size: .78rem; opacity: .8; }
    .pfd-menu .pfd-menu-h {
        padding: 6px 10px 7px; font-size: .68rem; font-weight: 800; text-transform: uppercase;
        letter-spacing: .05em; color: var(--dt-muted, #94a3b8);
        border-bottom: 1px solid var(--dt-border, #f1f5f9); margin-bottom: 4px;
        overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }

    /* ── Taşıma penceresi ── */
    .pfd-ov { position: fixed; inset: 0; z-index: 2100; background: rgba(15, 23, 42, .45); display: grid; place-items: center; }
    .pfd-modal {
        width: min(430px, 92vw); max-height: 78vh; display: flex; flex-direction: column;
        background: var(--bg-card, #fff); border-radius: 16px; box-shadow: 0 24px 60px rgba(15, 23, 42, .3);
        overflow: hidden;
    }
    .pfd-modal-h { display: flex; align-items: center; gap: 11px; padding: 14px 16px; border-bottom: 1px solid var(--dt-border, #e9edf3); }
    .pfd-modal-h > i { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; background: var(--dt-primary-soft, #eef2ff); color: var(--dt-primary, #4f46e5); }
    .pfd-modal-h b { display: block; font-size: .9rem; color: var(--dt-text, #0f172a); }
    .pfd-modal-h small { font-size: .73rem; color: var(--dt-muted, #94a3b8); }
    .pfd-x { margin-left: auto; border: none; background: none; color: #94a3b8; cursor: pointer; font-size: .95rem; }
    .pfd-x:hover { color: #ef4444; }

    .pfd-search { display: flex; align-items: center; gap: 8px; margin: 12px 16px 0; padding: 8px 11px; background: var(--dt-head-bg, #f8fafc); border-radius: 10px; color: #94a3b8; }
    .pfd-search input { flex: 1; border: none; background: none; outline: none; font: inherit; font-size: .84rem; color: var(--dt-text, #0f172a); }

    .pfd-list { flex: 1; overflow-y: auto; padding: 10px 12px 12px; }
    .pfd-opt {
        display: flex; align-items: center; gap: 9px; width: 100%; border: none; background: none;
        padding: 8px 10px; border-radius: 9px; cursor: pointer; text-align: left; font: inherit;
        font-size: .84rem; color: var(--dt-text, #334155);
    }
    .pfd-opt:hover { background: var(--dt-primary-soft, #eef2ff); color: var(--dt-primary, #4f46e5); }
    .pfd-opt.is-current { opacity: .45; cursor: default; }
    .pfd-opt.is-current:hover { background: none; color: inherit; }
    .pfd-opt i { font-size: .78rem; opacity: .7; }
    .pfd-opt .pfd-opt-root { font-weight: 800; }
    .pfd-empty { padding: 1.4rem; text-align: center; font-size: .8rem; color: var(--dt-muted, #94a3b8); }

    .pfd-modal-f { display: flex; justify-content: flex-end; padding: 11px 16px; border-top: 1px solid var(--dt-border, #e9edf3); }
</style>
@endpush
@endonce

@push('scripts')
<script>
(function () {
    const TREE_URL = @json(route('agency.products.folders.tree', ['type' => $type]));
    const MOVE_PRODUCT_URL = @json(route('agency.products.folders.move-product', ['type' => $type]));
    const MOVE_CATEGORY_URL = @json(route('agency.products.folders.move-category', ['type' => $type]));

    const menu = document.getElementById('pfdMenu');
    const ov = document.getElementById('pfdMoveOv');
    const list = document.getElementById('pfdMoveList');
    const search = document.getElementById('pfdMoveSearch');
    if (!menu || !ov) return;

    let target = null;   // { kind: 'category'|'product', id, name, parent, quickView, openUrl }
    let tree = null;     // [{id, name, depth}]

    const csrf = () => document.querySelector('meta[name="csrf-token"]')?.content || '';
    const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));

    function toast(icon, title) {
        if (typeof window.appToast === 'function') window.appToast({ icon: icon, title: title, timer: 2000 });
    }

    // ── Sağ tık: klasör ya da ürün satırı ──────────────────────────
    document.addEventListener('contextmenu', function (e) {
        const row = e.target.closest('.dt-table tbody tr');
        if (!row) return;

        const kind = row.dataset.pfdKind || (row.dataset.quickviewUrl ? 'product' : null);
        if (!kind) return;

        // Ürün satırında id, satır seçim kutusunun değerinden okunur
        const id = row.dataset.pfdId || row.querySelector('.dt-rowcheck')?.value;
        if (!id) return;

        e.preventDefault();
        target = {
            kind: kind,
            id: Number(id),
            name: row.dataset.pfdName || row.querySelector('.dt-cell-main')?.textContent?.trim() || 'Kayıt',
            parent: row.dataset.pfdParent ? Number(row.dataset.pfdParent) : null,
            quickView: row.dataset.quickviewUrl || null,
            openUrl: (row.getAttribute('onclick') || '').match(/'([^']+)'/)?.[1] || null,
        };

        openMenu(e.clientX, e.clientY);
    });

    function openMenu(x, y) {
        const items = ['<div class="pfd-menu-h">' + esc(target.name) + '</div>'];

        if (target.kind === 'category') {
            items.push('<button type="button" data-act="open"><i class="fas fa-folder-open"></i> Klasörü Aç</button>');
        } else if (target.quickView) {
            items.push('<button type="button" data-act="card"><i class="fas fa-eye"></i> Kartı Aç</button>');
        }
        items.push('<button type="button" data-act="move"><i class="fas fa-arrow-right-arrow-left"></i> Klasöre Taşı…</button>');

        menu.innerHTML = items.join('');
        menu.hidden = false;

        // Menü ekran dışına taşmasın
        const r = menu.getBoundingClientRect();
        menu.style.left = Math.max(6, Math.min(x, window.innerWidth - r.width - 8)) + 'px';
        menu.style.top = Math.max(6, Math.min(y, window.innerHeight - r.height - 8)) + 'px';

        menu.querySelectorAll('button').forEach(function (b) {
            b.addEventListener('click', function () {
                const act = b.dataset.act;
                closeMenu();
                if (act === 'open' && target.openUrl) window.location = target.openUrl;
                else if (act === 'card' && typeof openQuickView === 'function') openQuickView(target.quickView);
                else if (act === 'move') openMove();
            });
        });
    }

    function closeMenu() { menu.hidden = true; }
    document.addEventListener('click', closeMenu);
    document.addEventListener('scroll', closeMenu, true);
    window.addEventListener('resize', closeMenu);

    // ── Taşıma penceresi ───────────────────────────────────────────
    function openMove() {
        document.getElementById('pfdMoveSub').textContent =
            (target.kind === 'category' ? 'Klasör: ' : 'Kayıt: ') + target.name;
        search.value = '';
        ov.hidden = false;
        list.innerHTML = '<div class="pfd-empty">Klasörler yükleniyor…</div>';
        setTimeout(function () { search.focus(); }, 60);

        if (tree) { renderTree(); return; }

        fetch(TREE_URL, { headers: { 'Accept': 'application/json' } })
            .then(function (r) { return r.json(); })
            .then(function (d) { tree = d.categories || []; renderTree(); })
            .catch(function () { list.innerHTML = '<div class="pfd-empty">Klasörler yüklenemedi.</div>'; });
    }

    window.pfdCloseMove = function () { ov.hidden = true; };
    ov.addEventListener('click', function (e) { if (e.target === ov) window.pfdCloseMove(); });
    document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !ov.hidden) window.pfdCloseMove(); });
    search.addEventListener('input', renderTree);

    function renderTree() {
        const q = search.value.trim().toLocaleLowerCase('tr-TR');
        const rows = (tree || []).filter(function (c) {
            return !q || c.name.toLocaleLowerCase('tr-TR').indexOf(q) !== -1;
        });

        // Kök seçeneği: ürün için "kategorisiz", klasör için "en üst seviye"
        let html = '';
        if (!q) {
            const rootLabel = target.kind === 'category' ? 'En üst seviye' : 'Kategorisiz';
            const rootCurrent = target.kind === 'category' && target.parent === null;
            html += '<button type="button" class="pfd-opt ' + (rootCurrent ? 'is-current' : '') + '" data-id=""' +
                (rootCurrent ? ' disabled' : '') + '>' +
                '<i class="fas fa-folder-tree"></i><span class="pfd-opt-root">' + rootLabel + '</span></button>';
        }

        html += rows.map(function (c) {
            // Klasör kendi içine ya da hâlihazırda bulunduğu üst klasöre taşınmaz
            const disabled = target.kind === 'category' && (c.id === target.id || c.id === target.parent);
            return '<button type="button" class="pfd-opt ' + (disabled ? 'is-current' : '') + '" data-id="' + c.id + '"' +
                (disabled ? ' disabled' : '') + '>' +
                '<span style="width:' + (c.depth * 14) + 'px"></span>' +
                '<i class="fas fa-folder"></i><span>' + esc(c.name) + '</span></button>';
        }).join('');

        list.innerHTML = html || '<div class="pfd-empty">Eşleşen klasör yok.</div>';
        list.querySelectorAll('.pfd-opt:not([disabled])').forEach(function (b) {
            b.addEventListener('click', function () {
                submitMove(b.dataset.id ? Number(b.dataset.id) : null);
            });
        });
    }

    function submitMove(categoryId) {
        const url = target.kind === 'category' ? MOVE_CATEGORY_URL : MOVE_PRODUCT_URL;
        const body = target.kind === 'category'
            ? { id: target.id, parent_id: categoryId }
            : { id: target.id, category_id: categoryId };

        list.innerHTML = '<div class="pfd-empty">Taşınıyor…</div>';

        fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf() },
            body: JSON.stringify(body),
        })
        .then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d || {} }; }); })
        .then(function (res) {
            if (!res.ok || !res.d.success) { toast('error', res.d.message || 'Taşınamadı'); renderTree(); return; }
            toast('success', res.d.message || 'Taşındı');
            window.pfdCloseMove();
            location.reload();
        })
        .catch(function () { toast('error', 'Sunucuya ulaşılamadı'); renderTree(); });
    }
})();
</script>
@endpush
