<div id="quickViewOverlay" class="qv-drawer-overlay" onclick="closeQuickView()"></div>
<div id="quickViewDrawer" class="qv-drawer">
    <div id="quickViewLoader" class="qv-drawer-loader">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Yükleniyor...</span>
        </div>
    </div>
    <div id="quickViewContent"></div>
</div>

<div id="qvMinimizedStack" class="qv-minimized-stack"></div>

<style>
.qv-minimized-stack {
    position: fixed;
    bottom: 1rem;
    right: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    z-index: 1052;
    pointer-events: none;
}
.qv-min-item {
    pointer-events: auto;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(226, 232, 240, 0.8);
    padding: 0.5rem 0.8rem;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
    display: flex;
    align-items: center;
    gap: 0.6rem;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    animation: slideUpTaskbar 0.4s ease forwards;
    width: auto;
    min-width: 150px;
    max-width: 260px;
}
.qv-min-item:hover { transform: translateY(-5px); border-color: #2563eb; box-shadow: 0 10px 25px rgba(37, 99, 235, 0.1); }
.qv-min-all-btn {
    width: 36px; height: 36px; border-radius: 12px; background: rgba(254, 226, 226, 0.8);
    backdrop-filter: blur(10px); border: 1px solid rgba(254, 202, 202, 0.8); color: #ef4444; 
    display: flex; align-items: center; justify-content: center; transition: all 0.2s; cursor: pointer;
}
.qv-min-all-btn:hover { background: #ef4444; color: #fff; transform: scale(1.1); }
.qv-min-avatar { width: 28px; height: 28px; border-radius: 6px; background: #eff6ff; color: #2563eb; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 0.7rem; flex-shrink: 0; }
.qv-min-info { flex: 1; min-width: 0; }
.qv-min-title { font-size: 0.8rem; font-weight: 700; color: #1e293b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.qv-min-label { font-size: 0.6rem; font-weight: 600; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.02em; display: none; }
.qv-min-close { width: 22px; height: 22px; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #94a3b8; transition: all 0.2s; flex-shrink: 0; }
.qv-min-close:hover { background: #fee2e2; color: #ef4444; }

@keyframes slideUpTaskbar { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }

.qv-drawer-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(15, 23, 42, 0.3);
    backdrop-filter: blur(8px);
    z-index: 1050;
    opacity: 0;
    visibility: hidden;
    transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}
.qv-drawer-overlay.active {
    opacity: 1;
    visibility: visible;
}

.qv-drawer {
    position: fixed;
    top: 0;
    right: -85%;
    width: 85%;
    height: 100%;
    background: #ffffff;
    box-shadow: -20px 0 60px rgba(15, 23, 42, 0.1);
    z-index: 1051;
    transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
    display: flex;
    flex-direction: column;
    border-left: 1px solid rgba(226, 232, 240, 0.8);
}
@media (max-width: 1200px) {
    .qv-drawer { width: 95%; right: -95%; }
}
@media (max-width: 768px) {
    .qv-drawer { width: 100%; right: -100%; }
}
.qv-drawer.active {
    right: 0;
}

#quickViewContent {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.qv-drawer-loader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255,255,255,0.8);
    z-index: 10;
    opacity: 0;
    visibility: hidden;
}
.qv-drawer-loader.active {
    opacity: 1;
    visibility: visible;
}
</style>

<script>
let activeQuickViewUrl = null;

// Persistent state management
function saveMinimizedState() {
    localStorage.setItem('qvMinimizedItems', JSON.stringify(window.minimizedItems || []));
}

function loadMinimizedState() {
    try {
        const saved = localStorage.getItem('qvMinimizedItems');
        window.minimizedItems = saved ? JSON.parse(saved) : [];
    } catch (e) {
        window.minimizedItems = [];
    }
}

// Global initialization
loadMinimizedState();

// Compatibility shim
function openCustomerDrawer(customerId, activeTab = null) {
    openQuickView(`/agency/customers/${customerId}/quick-view`, activeTab);
}

function openSaleDrawer(saleId, activeTab = null) {
    openQuickView(`/agency/sales/${saleId}/quick-view`, activeTab);
}

function openSupplierDrawer(supplierId, activeTab = null) {
    openQuickView(`/agency/suppliers/${supplierId}/quick-view`, activeTab);
}

function openQuickView(url, activeTab = null) {
    const drawer = document.getElementById('quickViewDrawer');
    const overlay = document.getElementById('quickViewOverlay');
    const loader = document.getElementById('quickViewLoader');
    const content = document.getElementById('quickViewContent');

    // If this URL was minimized, remove it from stack
    removeMinimizedItem(url, true);

    activeQuickViewUrl = url;
    
    // UI show
    drawer.classList.add('active');
    overlay.classList.add('active');
    loader.classList.add('active');
    if (document.body.style.overflow !== 'hidden') document.body.style.setProperty('--old-overflow', document.body.style.overflow);
    document.body.style.overflow = 'hidden';

    // Fetch data
    fetch(url)
        .then(response => {
            if (!response.ok) throw new Error('Yükleme hatası');
            return response.text();
        })
        .then(html => {
            if (activeQuickViewUrl === url) {
                $(content).html(html);
                
                // If a specific tab was requested, activate it
                if (activeTab) {
                    const tabEl = content.querySelector(`.qv-tab[onclick*="'${activeTab}'"]`);
                    if (tabEl) {
                        switchQvTab(activeTab, tabEl);
                    }
                }
                
                loader.classList.remove('active');
            }
        })
        .catch(err => {
            content.innerHTML = `<div class="p-5 text-center"><i class="fas fa-exclamation-triangle text-danger font-large"></i><p class="mt-3">Bilgiler yüklenirken bir hata oluştu.</p></div>`;
            loader.classList.remove('active');
        });
}

function minimizeQuickView() {
    if (!activeQuickViewUrl) return;

    const content = document.getElementById('quickViewContent');
    const headerTitle = content.querySelector('.qv-header h3');
    const title = headerTitle ? headerTitle.innerText : 'Hızlı Görünüm';
    const avatar = content.querySelector('.qv-avatar-big');
    const initials = avatar ? avatar.innerText : 'QV';
    
    // Add to state if not already there
    if (!window.minimizedItems.find(i => i.url === activeQuickViewUrl)) {
        window.minimizedItems.push({
            url: activeQuickViewUrl,
            title: title,
            initials: initials
        });
        saveMinimizedState();
        renderMinimizedStack();
    }

    closeQuickView(true); // close but keep the URL state
}

function closeQuickView(isMinimizing = false) {
    if (!isMinimizing) activeQuickViewUrl = null;
    
    document.getElementById('quickViewDrawer').classList.remove('active');
    document.getElementById('quickViewOverlay').classList.remove('active');
    document.body.style.overflow = document.body.style.getPropertyValue('--old-overflow') || 'auto';
    
    setTimeout(() => {
        if (!isMinimizing) {
             const content = document.getElementById('quickViewContent');
             if (content) content.innerHTML = '';
        }
    }, 400);
}

function renderMinimizedStack() {
    const stack = document.getElementById('qvMinimizedStack');
    if (!stack) return;
    stack.innerHTML = '';
    
    if (window.minimizedItems && window.minimizedItems.length > 0) {
        window.minimizedItems.forEach((item, index) => {
            const div = document.createElement('div');
            div.className = 'qv-min-item';
            div.setAttribute('onclick', `openQuickView('${item.url}')`);
            div.innerHTML = `
                <div class="qv-min-avatar">${item.initials}</div>
                <div class="qv-min-info">
                    <div class="qv-min-title">${item.title}</div>
                </div>
                <button class="qv-min-close" onclick="event.stopPropagation(); removeMinimizedItem('${item.url}', true)"><i class="fas fa-times"></i></button>
            `;
            stack.appendChild(div);
        });

        if (window.minimizedItems.length > 1) {
            const closeAllWrap = document.createElement('div');
            closeAllWrap.className = 'qv-min-all-wrap';
            closeAllWrap.style.cssText = 'pointer-events: auto;';
            closeAllWrap.innerHTML = `
                <button class="qv-min-all-btn" onclick="clearAllMinimized()" title="Tümünü Kapat">
                    <i class="fas fa-trash-can"></i>
                </button>
            `;
            stack.appendChild(closeAllWrap);
        }
    }
}

function removeMinimizedItem(url, reRender = false) {
    window.minimizedItems = (window.minimizedItems || []).filter(i => i.url !== url);
    saveMinimizedState();
    if (reRender) renderMinimizedStack();
}

function clearAllMinimized() {
    window.minimizedItems = [];
    saveMinimizedState();
    renderMinimizedStack();
}

// Initial render
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', renderMinimizedStack);
} else {
    renderMinimizedStack();
}


function switchQvTab(tab, el) {
    // Find nearest tab container
    const container = el.closest('.qv-wrapper') || document;
    container.querySelectorAll('.qv-tab').forEach(t => t.classList.remove('active'));
    el.classList.add('active');

    container.querySelectorAll('.qv-tab-panel').forEach(p => {
        p.classList.remove('active');
        p.style.display = 'none';
    });
    
    const target = container.querySelector('#qv-tab-' + tab);
    if (target) {
        target.classList.add('active');
        target.style.display = 'block';
    }
}

// Global handle for escape key
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeQuickView();
});

// Global handle for customer row/link clicks
document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('click', (e) => {
        // 1. Direct customer row (TR)
        let customerTarget = e.target.closest('tr.customer-row[data-id]');
        let customerId = customerTarget ? customerTarget.dataset.id : null;

        // 2. Specific customer link/element inside any view
        if (!customerId) {
            customerTarget = e.target.closest('[data-customer-id]');
            customerId = customerTarget ? customerTarget.dataset.customerId : null;
        }

        // 3. Sale row
        let saleTarget = e.target.closest('tr.sale-row[data-id]');
        let saleId = saleTarget ? saleTarget.dataset.id : null;

        // 4. Supplier row
        let supplierTarget = e.target.closest('tr.supplier-row[data-id]');
        let supplierId = supplierTarget ? supplierTarget.dataset.id : null;

        if (!supplierId) {
            supplierTarget = e.target.closest('[data-supplier-id]');
            supplierId = supplierTarget ? supplierTarget.dataset.supplierId : null;
        }

        const isAction = e.target.closest('.row-actions') || e.target.closest('input') || e.target.closest('a:not([data-customer-id]):not([data-supplier-id])') || e.target.closest('button') || e.target.classList.contains('inline-editable');
        
        if (customerId && !isAction) {
            e.preventDefault();
            e.stopPropagation();
            openCustomerDrawer(customerId);
        } else if (saleId && !isAction) {
            e.preventDefault();
            e.stopPropagation();
            openSaleDrawer(saleId);
        } else if (supplierId && !isAction) {
            e.preventDefault();
            e.stopPropagation();
            openSupplierDrawer(supplierId);
        }
    });
});

// ─── INLINE EDIT LOGIC ───
document.addEventListener('click', function(e) {
    const target = e.target.closest('.inline-editable');
    if (!target || target.classList.contains('editing')) return;

    const field = target.dataset.field;
    const cid = target.dataset.id;
    const type = target.dataset.type || 'text';
    const originalValue = target.dataset.value || target.innerText.trim();
    
    target.classList.add('editing');
    const originalContent = target.innerHTML;
    
    let input;
    if (type === 'select') {
        input = document.createElement('select');
        input.className = 'form-select form-select-sm';
        const options = JSON.parse(target.dataset.options || '[]');
        options.forEach(opt => {
            const option = document.createElement('option');
            option.value = opt.value;
            option.text = opt.label;
            option.selected = (opt.value == originalValue);
            input.appendChild(option);
        });
    } else if (type === 'textarea') {
        input = document.createElement('textarea');
        input.className = 'form-control form-control-sm';
        input.rows = 3;
        input.value = originalValue === '—' ? '' : originalValue;
    } else {
        input = document.createElement('input');
        input.type = type;
        input.className = 'form-control form-control-sm';
        input.value = originalValue === '—' ? '' : originalValue;
        
        // Calculate width for inline text inputs
        if (!target.classList.contains('w-100')) {
            const charCount = Math.max(input.value.length, 5);
            input.style.width = (charCount + 2) + 'ch';
        }
    }

    target.innerHTML = '';
    target.appendChild(input);
    input.focus();

    const save = () => {
        const newValue = input.value;
        if (newValue == originalValue) {
            target.innerHTML = originalContent;
            target.classList.remove('editing');
            return;
        }

        // Show loading
        target.innerHTML = '<span class="spinner-border spinner-border-sm text-primary"></span>';

        const url = target.dataset.url || `/agency/customers/${cid}/update-field`;

        fetch(url, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ field: field, value: newValue })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                target.innerText = data.display_value || (newValue || '—');
                target.dataset.value = newValue;
                target.classList.remove('editing');
                
                // Show success toast
                if (typeof Swal !== 'undefined') {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000,
                        timerProgressBar: true
                    });
                    Toast.fire({
                        icon: 'success',
                        title: data.message || 'Güncellendi'
                    });
                }

                // Highlight effect
                target.style.backgroundColor = '#d1fae5';
                setTimeout(() => target.style.backgroundColor = '', 1000);
            } else {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Hata',
                        text: data.message || 'Güncelleme başarısız.'
                    });
                }
                target.innerHTML = originalContent;
                target.classList.remove('editing');
            }
        })
        .catch(err => {
            console.error(err);
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: 'error',
                    title: 'Hata',
                    text: 'Bağlantı hatası oluştu.'
                });
            }
            target.innerHTML = originalContent;
            target.classList.remove('editing');
        });
    };

    input.addEventListener('blur', save);
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && type !== 'textarea') save();
        if (e.key === 'Escape') {
            target.innerHTML = originalContent;
            target.classList.remove('editing');
        }
    });
});
</script>
