<div id="quickViewOverlay" class="qv-drawer-overlay" onclick="shutdownDrawer()"></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="quickViewContainers" class="qv-containers-stack"></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: transparent;
    z-index: 1051;
    transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
    display: flex;
    flex-direction: column;
}
@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;
}

.qv-containers-stack {
    position: relative;
    width: 100%;
    height: 100%;
}

.qv-card-wrapper {
    position: absolute;
    top: 0;
    right: 0;
    width: 100%;
    height: 100%;
    background: #ffffff;
    box-shadow: -20px 0 60px rgba(15, 23, 42, 0.12);
    border: 1px solid rgba(226, 232, 240, 0.8);
    border-radius: 24px 0 0 24px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1),
                opacity 0.6s cubic-bezier(0.16, 1, 0.3, 1),
                filter 0.6s cubic-bezier(0.16, 1, 0.3, 1),
                box-shadow 0.6s cubic-bezier(0.16, 1, 0.3, 1);
    transform-origin: right center;
}

.qv-card-wrapper.inactive {
    transform: translateX(calc(-60px * var(--diff))) translateY(calc(15px * var(--diff))) scale(calc(1 - 0.02 * var(--diff))) !important;
    opacity: 0.9 !important;
    filter: brightness(0.9) blur(0.5px) !important;
    box-shadow: -15px 15px 40px rgba(15, 23, 42, 0.18) !important;
}

.qv-card-wrapper.inactive:hover {
    transform: translateX(calc(-60px * var(--diff) - 20px)) translateY(calc(15px * var(--diff))) scale(calc(1 - 0.02 * var(--diff))) !important;
    opacity: 0.95 !important;
    filter: brightness(0.95) !important;
}

.qv-card-inactive-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(15, 23, 42, 0.04);
    backdrop-filter: blur(0.5px);
    z-index: 1055;
    cursor: pointer;
    transition: background 0.3s;
}
.qv-card-inactive-overlay:hover {
    background: rgba(15, 23, 42, 0.01);
}

.qv-card-wrapper:not(.inactive) .qv-card-side-handle {
    opacity: 0;
    visibility: hidden;
    pointer-events: none;
}

.qv-card-side-handle {
    position: absolute;
    top: 0;
    left: 0;
    width: 60px;
    height: 100%;
    background: #f8fafc;
    border-right: 1px solid #e2e8f0;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 1.5rem 0;
    z-index: 1060;
    cursor: pointer;
    transition: all 0.3s;
}
.qv-card-side-handle:hover {
    background: #f1f5f9;
}
.qv-card-side-handle .handle-avatar {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    background: #eff6ff;
    color: #2563eb;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 0.85rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 6px rgba(37, 99, 235, 0.15);
}
.qv-card-side-handle .handle-title {
    writing-mode: vertical-rl;
    text-orientation: mixed;
    transform: rotate(180deg);
    font-size: 0.82rem;
    font-weight: 800;
    color: #64748b;
    white-space: nowrap;
    letter-spacing: 0.05em;
    flex-grow: 1;
    text-align: right;
    text-overflow: ellipsis;
    overflow: hidden;
    max-height: calc(100% - 120px);
}
.qv-card-side-handle:hover .handle-title {
    color: #1e293b;
}
.qv-card-side-handle .handle-close {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #94a3b8;
    transition: all 0.2s;
    margin-top: auto;
}
.qv-card-side-handle .handle-close:hover {
    background: #fee2e2;
    color: #ef4444;
}

.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: 2000;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s;
}
.qv-drawer-loader.active {
    opacity: 1;
    visibility: visible;
}
</style>

<script>
let activeQuickViewUrl = null;
let qvStack = [];
let qvLoading = new Set();

// 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 setHtmlAndRunScripts(element, html) {
    element.innerHTML = html;
    const scripts = Array.from(element.querySelectorAll('script'));
    scripts.forEach(oldScript => {
        const newScript = document.createElement('script');
        Array.from(oldScript.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
        newScript.appendChild(document.createTextNode(oldScript.textContent));
        oldScript.parentNode.replaceChild(newScript, oldScript);
    });
}

function deactivateCard(cardEl) {
    if (cardEl.classList.contains('inactive')) return;
    cardEl.classList.add('inactive');
    cardEl.querySelectorAll('[id]').forEach(el => {
        const originalId = el.getAttribute('id');
        el.setAttribute('data-original-id', originalId);
        el.removeAttribute('id');
    });
}

function activateCard(cardEl) {
    if (!cardEl.classList.contains('inactive')) return;
    cardEl.classList.remove('inactive');
    cardEl.querySelectorAll('[data-original-id]').forEach(el => {
        const originalId = el.getAttribute('data-original-id');
        el.setAttribute('id', originalId);
        el.removeAttribute('data-original-id');
    });
}

function updateStackUI() {
    const activeIdx = qvStack.length - 1;
    const container = document.getElementById('quickViewContainers');
    if (!container) return;

    qvStack.forEach((item, index) => {
        const cardEl = item.element;
        const diff = activeIdx - index;
        
        cardEl.style.zIndex = 100 + index;
        
        // Remove existing overlay
        const oldOverlay = cardEl.querySelector('.qv-card-inactive-overlay');
        if (oldOverlay) oldOverlay.remove();

        if (index === activeIdx) {
            activateCard(cardEl);
            cardEl.style.transform = '';
            cardEl.style.opacity = '';
            cardEl.style.filter = '';
            cardEl.style.pointerEvents = 'auto';
            cardEl.onclick = null; // Clear click handler when active
            activeQuickViewUrl = item.url;
        } else {
            deactivateCard(cardEl);
            cardEl.style.setProperty('--diff', diff);
            cardEl.style.transform = '';
            cardEl.style.opacity = '';
            cardEl.style.filter = '';
            cardEl.style.pointerEvents = 'auto';

            cardEl.onclick = (e) => {
                e.stopPropagation();
                bringCardToFront(item.url);
            };

            // Add inactive overlay to block inner content interactions
            const overlay = document.createElement('div');
            overlay.className = 'qv-card-inactive-overlay';
            cardEl.appendChild(overlay);
        }
    });
}

function bringCardToFront(url) {
    const idx = qvStack.findIndex(item => item.url === url);
    if (idx === -1 || idx === qvStack.length - 1) return;
    
    const item = qvStack.splice(idx, 1)[0];
    qvStack.push(item);
    updateStackUI();
}

function closeCard(url) {
    const idx = qvStack.findIndex(item => item.url === url);
    if (idx === -1) return;

    const item = qvStack[idx];
    item.element.remove();
    qvStack.splice(idx, 1);

    if (qvStack.length > 0) {
        updateStackUI();
    } else {
        shutdownDrawer();
    }
}

function openQuickView(url, activeTab = null) {
    if (qvLoading.has(url)) return;

    const drawer = document.getElementById('quickViewDrawer');
    const overlay = document.getElementById('quickViewOverlay');
    const loader = document.getElementById('quickViewLoader');
    const container = document.getElementById('quickViewContainers');

    removeMinimizedItem(url, true);

    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';

    const existingItem = qvStack.find(item => item.url === url);

    qvLoading.add(url);

    fetch(url)
        .then(response => {
            qvLoading.delete(url);
            if (!response.ok) throw new Error('Yükleme hatası');
            return response.text();
        })
        .then(html => {
            const cleanText = (str) => str ? str.replace(/\s+/g, ' ').trim() : '';
            
            if (existingItem) {
                // Card already exists, bring it to front and refresh content
                bringCardToFront(url);
                
                const cardEl = existingItem.element;
                const sideHandle = cardEl.querySelector('.qv-card-side-handle');
                
                // Temporarily activate it to write to it cleanly
                activateCard(cardEl);
                setHtmlAndRunScripts(cardEl, html);
                if (sideHandle) cardEl.appendChild(sideHandle);

                // Extract potentially updated title & initials
                let title = '';
                const salesTitle = cardEl.querySelector('.sqv-title');
                if (salesTitle) {
                    title = cleanText(salesTitle.innerText);
                }
                if (!title) {
                    const headerTitle = cardEl.querySelector('.qv-header h3');
                    if (headerTitle) {
                        title = cleanText(headerTitle.innerText);
                    }
                }
                if (!title) title = 'Hızlı Görünüm';

                let initials = 'QV';
                const avatar = cardEl.querySelector('.qv-avatar-big');
                if (avatar) {
                    initials = cleanText(avatar.innerText);
                } else {
                    const sqvIcon = cardEl.querySelector('.sqv-icon i');
                    if (sqvIcon) {
                        initials = sqvIcon.outerHTML;
                    }
                }

                existingItem.title = title;
                existingItem.initials = initials;

                if (sideHandle) {
                    sideHandle.innerHTML = `
                        <div class="handle-avatar">${initials}</div>
                        <div class="handle-title">${title}</div>
                        <button class="handle-close" onclick="event.stopPropagation(); closeCard('${url}')">
                            <i class="fas fa-times"></i>
                        </button>
                    `;
                }

                if (activeTab) {
                    const tabEl = cardEl.querySelector(`.qv-tab[onclick*="'${activeTab}'"]`);
                    if (tabEl) {
                        switchQvTab(activeTab, tabEl);
                    }
                }

                updateStackUI();
                loader.classList.remove('active');
            } else {
                // Create new card
                const cardEl = document.createElement('div');
                cardEl.className = 'qv-card-wrapper inactive';
                setHtmlAndRunScripts(cardEl, html);

                let title = '';
                const salesTitle = cardEl.querySelector('.sqv-title');
                if (salesTitle) {
                    title = cleanText(salesTitle.innerText);
                }
                if (!title) {
                    const headerTitle = cardEl.querySelector('.qv-header h3');
                    if (headerTitle) {
                        title = cleanText(headerTitle.innerText);
                    }
                }
                if (!title) title = 'Hızlı Görünüm';

                let initials = 'QV';
                const avatar = cardEl.querySelector('.qv-avatar-big');
                if (avatar) {
                    initials = cleanText(avatar.innerText);
                } else {
                    const sqvIcon = cardEl.querySelector('.sqv-icon i');
                    if (sqvIcon) {
                        initials = sqvIcon.outerHTML;
                    }
                }

                const sideHandle = document.createElement('div');
                sideHandle.className = 'qv-card-side-handle';
                sideHandle.innerHTML = `
                    <div class="handle-avatar">${initials}</div>
                    <div class="handle-title">${title}</div>
                    <button class="handle-close" onclick="event.stopPropagation(); closeCard('${url}')">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                cardEl.appendChild(sideHandle);
                container.appendChild(cardEl);

                qvStack.push({
                    url: url,
                    title: title,
                    initials: initials,
                    element: cardEl
                });

                if (activeTab) {
                    const tabEl = cardEl.querySelector(`.qv-tab[onclick*="'${activeTab}'"]`);
                    if (tabEl) {
                        switchQvTab(activeTab, tabEl);
                    }
                }

                updateStackUI();
                loader.classList.remove('active');
            }
        })
        .catch(err => {
            qvLoading.delete(url);
            console.error(err);
            loader.classList.remove('active');
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    icon: 'error',
                    title: 'Hata',
                    text: 'Bilgiler yüklenirken bir hata oluştu.'
                });
            }
        });
}

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

    const activeItem = qvStack[qvStack.length - 1];
    if (!activeItem) return;

    const content = activeItem.element;
    const cleanText = (str) => str ? str.replace(/\s+/g, ' ').trim() : '';
    
    let title = '';
    const salesTitle = content.querySelector('.sqv-title');
    if (salesTitle) {
        title = cleanText(salesTitle.innerText);
    }
    if (!title) {
        const headerTitle = content.querySelector('.qv-header h3');
        if (headerTitle) {
            title = cleanText(headerTitle.innerText);
        }
    }
    if (!title) {
        title = 'Hızlı Görünüm';
    }

    let initials = 'QV';
    const avatar = content.querySelector('.qv-avatar-big');
    if (avatar) {
        initials = cleanText(avatar.innerText);
    } else {
        const sqvIcon = content.querySelector('.sqv-icon i');
        if (sqvIcon) {
            initials = sqvIcon.outerHTML;
        }
    }
    
    if (!window.minimizedItems.find(i => i.url === activeQuickViewUrl)) {
        window.minimizedItems.push({
            url: activeQuickViewUrl,
            title: title,
            initials: initials
        });
        saveMinimizedState();
        renderMinimizedStack();
    }

    activeItem.element.remove();
    qvStack.pop();

    if (qvStack.length > 0) {
        updateStackUI();
    } else {
        closeQuickView(true);
    }
}

function closeQuickView(isMinimizing = false) {
    if (isMinimizing) {
        shutdownDrawer(true);
        return;
    }
    if (activeQuickViewUrl) {
        closeCard(activeQuickViewUrl);
    }
}

function shutdownDrawer(keepState = false) {
    if (!keepState) {
        qvStack.forEach(item => item.element.remove());
        qvStack = [];
        activeQuickViewUrl = null;
        if (typeof qvLoading !== 'undefined') qvLoading.clear();
    }
    
    document.getElementById('quickViewDrawer').classList.remove('active');
    document.getElementById('quickViewOverlay').classList.remove('active');
    document.body.style.overflow = document.body.style.getPropertyValue('--old-overflow') || 'auto';
}

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') shutdownDrawer();
});

// 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>
<?php /**PATH C:\xampp\htdocs\acente\resources\views/components/quick-view-drawer.blade.php ENDPATH**/ ?>