<!-- Recent Pages & Quick-View History Sidebar -->
<div id="recentSidebarTrigger" class="recent-sidebar-trigger" onclick="toggleRecentSidebar()" title="Geçmiş & Hızlı Erişim">
    <i class="fas fa-history"></i>
</div>

<div id="recentSidebar" class="recent-sidebar">
    <div class="rs-header">
        <div class="rs-title">
            <i class="fas fa-clock-rotate-left text-primary me-2"></i>Geçmiş & Erişim
        </div>
        <button class="rs-close-btn" onclick="toggleRecentSidebar()" title="Kapat">
            <i class="fas fa-times"></i>
        </button>
    </div>

    <!-- Sidebar Content Scroll Area -->
    <div class="rs-content">
        <div id="rs-list" class="rs-list">
            <!-- Dynamically populated combined list -->
        </div>
        <div class="rs-empty-state d-none" id="rs-empty">
            <i class="fas fa-history text-muted mb-2" style="font-size: 1.5rem;"></i>
            <p>Henüz geçmiş kaydı yok.</p>
        </div>
        <button class="rs-clear-btn mt-3" onclick="clearRecentHistory()">
            <i class="fas fa-trash-can me-1"></i>Geçmişi Temizle
        </button>
    </div>
</div>

<style>
/* ─── SIDEBAR TRIGGER BUTTON ─── */
.recent-sidebar-trigger {
    position: fixed;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
    width: 44px;
    height: 48px;
    background: linear-gradient(135deg, #2563eb, #1d4ed8);
    color: #fff;
    border-radius: 12px 0 0 12px;
    box-shadow: -4px 0 20px rgba(37, 99, 235, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 1040;
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
.recent-sidebar-trigger:hover {
    width: 50px;
    background: linear-gradient(135deg, #1d4ed8, #1e40af);
}
.recent-sidebar-trigger i {
    font-size: 1.15rem;
    animation: rotateMicro 6s linear infinite;
}
@keyframes rotateMicro {
    0% { transform: rotate(0deg); }
    80% { transform: rotate(0deg); }
    100% { transform: rotate(-360deg); }
}

/* ─── SIDEBAR CONTAINER ─── */
.recent-sidebar {
    position: fixed;
    top: 0;
    right: -280px;
    width: 280px;
    height: 100%;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-left: 1px solid rgba(226, 232, 240, 0.8);
    box-shadow: -10px 0 40px rgba(15, 23, 42, 0.08);
    z-index: 1046;
    display: flex;
    flex-direction: column;
    transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
.recent-sidebar.active {
    right: 0;
}

/* Header */
.rs-header {
    padding: 1rem 1.25rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #f1f5f9;
}
.rs-title {
    font-size: 0.95rem;
    font-weight: 800;
    color: #0f172a;
    display: flex;
    align-items: center;
}
.rs-close-btn {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    border: none;
    background: transparent;
    color: #94a3b8;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    cursor: pointer;
}
.rs-close-btn:hover {
    background: #fee2e2;
    color: #ef4444;
}

/* Content Area */
.rs-content {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
}

/* Lists */
.rs-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}
.rs-item {
    background: #fff;
    border: 1px solid #f1f5f9;
    border-radius: 10px;
    padding: 0.65rem 0.8rem;
    display: flex;
    align-items: center;
    gap: 0.65rem;
    cursor: pointer;
    position: relative;
    transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}
.rs-item:hover {
    border-color: #2563eb;
    box-shadow: 0 4px 12px rgba(37,99,235,0.05);
    transform: translateY(-1px);
}
.rs-item-info {
    flex: 1;
    min-width: 0;
}
.rs-item-title {
    font-size: 0.76rem;
    font-weight: 700;
    color: #1e293b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.rs-item-meta {
    font-size: 0.62rem;
    color: #94a3b8;
    display: flex;
    align-items: center;
    gap: 0.4rem;
    margin-top: 0.1rem;
}
.rs-item-meta span {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.rs-item-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.68rem;
    flex-shrink: 0;
}

/* Theme color codes for history */
.rs-item.theme-customers .rs-item-avatar { background: #e0f2fe; color: #0369a1; }
.rs-item.theme-sales .rs-item-avatar { background: #fee2e2; color: #dc2626; }
.rs-item.theme-suppliers .rs-item-avatar { background: #dcfce7; color: #15803d; }

.rs-item-delete {
    width: 20px;
    height: 20px;
    border-radius: 5px;
    border: none;
    background: transparent;
    color: #cbd5e1;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    cursor: pointer;
    flex-shrink: 0;
}
.rs-item:hover .rs-item-delete {
    color: #94a3b8;
}
.rs-item-delete:hover {
    background: #fee2e2 !important;
    color: #ef4444 !important;
}

/* Empty & Clear elements */
.rs-empty-state {
    text-align: center;
    padding: 1.5rem 1rem;
    color: #94a3b8;
    font-size: 0.72rem;
}
.rs-empty-state i {
    font-size: 1.25rem;
}
.rs-clear-btn {
    width: 100%;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    color: #64748b;
    border-radius: 8px;
    padding: 0.45rem;
    font-size: 0.7rem;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.2s;
}
.rs-clear-btn:hover {
    background: #fee2e2;
    border-color: #fca5a5;
    color: #ef4444;
}
</style>

<script>
// Sidebar Toggle
function toggleRecentSidebar() {
    const sidebar = document.getElementById('recentSidebar');
    sidebar.classList.toggle('active');
    const isActive = sidebar.classList.contains('active');
    localStorage.setItem('recent_sidebar_active', isActive ? 'true' : 'false');
    if (isActive) {
        renderRecentSidebar();
    }
}

// Restore state on load and set up outside click listener
document.addEventListener('DOMContentLoaded', () => {
    if (localStorage.getItem('recent_sidebar_active') === 'true') {
        const sidebar = document.getElementById('recentSidebar');
        if (sidebar) {
            sidebar.classList.add('active');
            renderRecentSidebar();
        }
    }

    // Close on outside click
    document.addEventListener('click', (e) => {
        const sidebar = document.getElementById('recentSidebar');
        const trigger = document.getElementById('recentSidebarTrigger');
        if (sidebar && sidebar.classList.contains('active')) {
            if (!sidebar.contains(e.target) && !trigger.contains(e.target)) {
                sidebar.classList.remove('active');
                localStorage.setItem('recent_sidebar_active', 'false');
            }
        }
    });
});

// Format relative time helper
function timeAgo(timestamp) {
    const diff = Date.now() - timestamp;
    const mins = Math.floor(diff / 60000);
    if (mins < 1) return 'Az önce';
    if (mins < 60) return `${mins} dk önce`;
    const hours = Math.floor(mins / 60);
    if (hours < 24) return `${hours} sa önce`;
    return new Date(timestamp).toLocaleDateString('tr-TR', { day: '2-digit', month: '2-digit' });
}

// Render Lists
function renderRecentSidebar() {
    const pages = JSON.parse(localStorage.getItem('recent_pages') || '[]');
    const qvs = JSON.parse(localStorage.getItem('qv_history') || '[]');
    
    // Combine lists
    const combined = [
        ...pages.map(p => ({ ...p, type: 'page' })),
        ...qvs.map(q => ({ ...q, type: 'qv' }))
    ];
    
    // Sort by timestamp desc
    combined.sort((a, b) => b.time - a.time);
    
    // Limit to 30 items
    const items = combined.slice(0, 30);
    
    const listContainer = document.getElementById('rs-list');
    const emptyState = document.getElementById('rs-empty');
    
    listContainer.innerHTML = '';
    
    if (items.length === 0) {
        emptyState.classList.remove('d-none');
    } else {
        emptyState.classList.add('d-none');
        items.forEach((item) => {
            const div = document.createElement('div');
            
            if (item.type === 'page') {
                div.className = 'rs-item';
                div.setAttribute('onclick', `window.location.href = '${item.url}'`);
                div.innerHTML = `
                    <div class="rs-item-avatar"><i class="fas fa-link"></i></div>
                    <div class="rs-item-info">
                        <div class="rs-item-title">${item.title}</div>
                        <div class="rs-item-meta">
                            <span>Sayfa</span>
                            <span>•</span>
                            <span>${timeAgo(item.time)}</span>
                        </div>
                    </div>
                    <button class="rs-item-delete" onclick="event.stopPropagation(); removeRecentItem('page', '${item.url}')" title="Sil">
                        <i class="fas fa-trash-can"></i>
                    </button>
                `;
            } else {
                let themeClass = '';
                let typeLabel = 'Kart';
                if (item.url.includes('/customers/')) { themeClass = 'theme-customers'; typeLabel = 'Müşteri'; }
                else if (item.url.includes('/sales/')) { themeClass = 'theme-sales'; typeLabel = 'Satış'; }
                else if (item.url.includes('/suppliers/')) { themeClass = 'theme-suppliers'; typeLabel = 'Tedarikçi'; }
                
                div.className = `rs-item ${themeClass}`;
                div.setAttribute('onclick', `openQuickView('${item.url}')`);
                div.innerHTML = `
                    <div class="rs-item-avatar">${item.initials}</div>
                    <div class="rs-item-info">
                        <div class="rs-item-title">${item.title}</div>
                        <div class="rs-item-meta">
                            <span>${typeLabel}</span>
                            <span>•</span>
                            <span>${timeAgo(item.time)}</span>
                        </div>
                    </div>
                    <button class="rs-item-delete" onclick="event.stopPropagation(); removeRecentItem('qv', '${item.url}')" title="Sil">
                        <i class="fas fa-trash-can"></i>
                    </button>
                `;
            }
            listContainer.appendChild(div);
        });
    }
}

// Remove single item
function removeRecentItem(type, url) {
    if (type === 'page') {
        let pages = JSON.parse(localStorage.getItem('recent_pages') || '[]');
        pages = pages.filter(p => p.url !== url);
        localStorage.setItem('recent_pages', JSON.stringify(pages));
    } else {
        let qvs = JSON.parse(localStorage.getItem('qv_history') || '[]');
        qvs = qvs.filter(q => q.url !== url);
        localStorage.setItem('qv_history', JSON.stringify(qvs));
    }
    renderRecentSidebar();
}

// Clear history
function clearRecentHistory() {
    if (!confirm('Tüm geçmişi temizlemek istediğinizden emin misiniz?')) return;
    localStorage.removeItem('recent_pages');
    localStorage.removeItem('qv_history');
    renderRecentSidebar();
}

// Capture current page views
(function() {
    const currentUrl = window.location.pathname + window.location.search;
    const rawTitle = document.title || 'Acente Paneli';
    const currentTitle = rawTitle.split(' - ')[0] || 'Acente Paneli';
    
    if (currentUrl.includes('/login') || currentUrl.includes('/select') || currentUrl.includes('/quick-view') || currentUrl.includes('/update-field') || currentUrl.includes('/bulk-')) return;
    
    let pages = JSON.parse(localStorage.getItem('recent_pages') || '[]');
    pages = pages.filter(p => p.url !== currentUrl);
    pages.unshift({
        url: currentUrl,
        title: currentTitle,
        time: Date.now()
    });
    if (pages.length > 30) pages = pages.slice(0, 30);
    localStorage.setItem('recent_pages', JSON.stringify(pages));
})();

// Global hook setter
window.refreshRecentSidebar = renderRecentSidebar;
</script>
