// Everest Büro Makinaları - Core Client Scripting
document.addEventListener('DOMContentLoaded', () => {
    // 1. Theme Manager
    const storedTheme = localStorage.getItem('ev-theme') || 'light';
    if (storedTheme === 'light') {
        document.documentElement.classList.add('light-theme');
    } else {
        document.documentElement.classList.remove('light-theme');
    }

    // Segmented Controls logic
    document.querySelectorAll('.segmented-control').forEach(control => {
        const btns = control.querySelectorAll('.seg-btn');
        btns.forEach(btn => {
            btn.addEventListener('click', function() {
                btns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                // If this is the theme control
                if (control.id === 'theme-control') {
                    const theme = this.getAttribute('data-theme-val');
                    if (theme === 'light') {
                        document.documentElement.classList.add('light-theme');
                        localStorage.setItem('ev-theme', 'light');
                        document.cookie = "ev-theme=light; path=/; max-age=31536000";
                    } else {
                        document.documentElement.classList.remove('light-theme');
                        localStorage.setItem('ev-theme', 'dark');
                        document.cookie = "ev-theme=dark; path=/; max-age=31536000";
                    }
                    // Sync the desktop theme icon if it exists
                    const desktopIcon = document.getElementById('theme-icon');
                    if (desktopIcon) {
                        desktopIcon.className = theme === 'light' ? 'fa fa-moon-o' : 'fa fa-sun-o';
                    }
                } else if (control.id === 'lang-control') {
                    const val = this.getAttribute('data-val');
                    const desktopLang = document.getElementById('lang-select');
                    if (desktopLang) {
                        desktopLang.value = val;
                        desktopLang.dispatchEvent(new Event('change'));
                    }
                } else if (control.id === 'currency-control') {
                    const val = this.getAttribute('data-val');
                    const desktopCur = document.getElementById('currency-select');
                    if (desktopCur) {
                        desktopCur.value = val;
                        desktopCur.dispatchEvent(new Event('change'));
                    }
                }
            });
        });

        // Initialize active state
        if (control.id === 'theme-control') {
            btns.forEach(b => b.classList.toggle('active', b.getAttribute('data-theme-val') === storedTheme));
        } else if (control.id === 'lang-control') {
            const desktopLang = document.getElementById('lang-select');
            if (desktopLang) {
                btns.forEach(b => b.classList.toggle('active', b.getAttribute('data-val') === desktopLang.value));
            }
        } else if (control.id === 'currency-control') {
            const desktopCur = document.getElementById('currency-select');
            if (desktopCur) {
                btns.forEach(b => b.classList.toggle('active', b.getAttribute('data-val') === desktopCur.value));
            }
        }
    });

    // 2. Language and Currency Selectors
    const langSelect = document.getElementById('lang-select');
    if (langSelect) {
        langSelect.addEventListener('change', (e) => {
            const url = new URL(window.location.href);
            url.searchParams.set('lang', e.target.value);
            window.location.href = url.toString();
        });
    }

    const curSelect = document.getElementById('currency-select');
    if (curSelect) {
        curSelect.addEventListener('change', (e) => {
            const url = new URL(window.location.href);
            url.searchParams.set('currency', e.target.value);
            window.location.href = url.toString();
        });
    }

    if ('serviceWorker' in navigator) {
        const swUrl = document.body.getAttribute('data-sw-url') || '/sw.js';
        navigator.serviceWorker.register(swUrl)
            .then(reg => console.log('Service Worker registered successfully. Scope:', reg.scope))
            .catch(err => console.log('Service Worker registration failed:', err));
    }

    // 4. Live Search Autocomplete for Front-end
    document.querySelectorAll('form[action$="/search"] input[name="q"]').forEach(input => {
        let timer;
        const form = input.closest('form');
        
        // Create dropdown container
        const dropdown = document.createElement('div');
        dropdown.className = 'live-search-dropdown';
        dropdown.style.cssText = 'position:absolute;top:100%;left:0;right:0;background:var(--surface-2);border:1px solid var(--border);border-radius:0 0 8px 8px;box-shadow:0 10px 25px rgba(0,0,0,0.1);z-index:9999;max-height:400px;overflow-y:auto;display:none;';
        form.style.position = 'relative';
        form.appendChild(dropdown);

        input.addEventListener('input', (e) => {
            clearTimeout(timer);
            const q = e.target.value.trim();
            if (q.length < 2) {
                dropdown.style.display = 'none';
                return;
            }
            // Optional loading state
            const iconBtn = form.querySelector('button[type="submit"] i');
            if (iconBtn) iconBtn.className = 'fa fa-spinner fa-spin';

            timer = setTimeout(() => {
                fetch(form.action + '?q=' + encodeURIComponent(q))
                .then(res => res.text())
                .then(html => {
                    if (iconBtn) iconBtn.className = 'fa fa-search';
                    const doc = new DOMParser().parseFromString(html, 'text/html');
                    const products = doc.querySelectorAll('.product-card');
                    dropdown.innerHTML = '';
                    
                    if (products.length > 0) {
                        let htmlList = '<ul style="list-style:none;padding:0;margin:0;">';
                        let count = 0;
                        products.forEach(p => {
                            if (count >= 5) return;
                            const imgNode = p.querySelector('img');
                            const titleNode = p.querySelector('.product-title');
                            const linkNode = p.querySelector('.product-title a');
                            const priceNode = p.querySelector('.product-price');
                            
                            if(!imgNode || !titleNode || !linkNode || !priceNode) return;
                            
                            htmlList += `
                                <li style="border-bottom:1px solid var(--border);">
                                    <a href="${linkNode.href}" style="display:flex;align-items:center;padding:10px;text-decoration:none;color:var(--text-1);gap:10px;transition:background 0.2s;">
                                        <img src="${imgNode.src}" style="width:40px;height:40px;object-fit:contain;border-radius:4px;background:#fff;">
                                        <div style="flex:1;overflow:hidden;">
                                            <div style="font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${titleNode.innerText.trim()}</div>
                                            <div style="font-size:12px;color:var(--orange);font-weight:700;margin-top:3px;">${priceNode.innerText.trim()}</div>
                                        </div>
                                    </a>
                                </li>
                            `;
                            count++;
                        });
                        htmlList += `<li><a href="${form.action}?q=${encodeURIComponent(q)}" style="display:block;text-align:center;padding:10px;font-size:13px;color:var(--orange);font-weight:700;text-decoration:none;background:rgba(249, 115, 22, 0.05);">Tüm Sonuçları Gör &raquo;</a></li></ul>`;
                        dropdown.innerHTML = htmlList;
                        dropdown.style.display = 'block';
                    } else {
                        dropdown.innerHTML = `<div style="padding:15px;text-align:center;font-size:13px;color:var(--text-3);">"${q}" için sonuç bulunamadı.</div>`;
                        dropdown.style.display = 'block';
                    }
                }).catch(() => {
                    if (iconBtn) iconBtn.className = 'fa fa-search';
                });
            }, 400);
        });
        
        document.addEventListener('click', (e) => {
            if (!form.contains(e.target)) dropdown.style.display = 'none';
        });
        input.addEventListener('focus', () => {
            if(input.value.trim().length >= 2 && dropdown.innerHTML !== '') {
                dropdown.style.display = 'block';
            }
        });
    });

});

// 4. Cart Functions (Global API Wrapper)
const baseUrl = document.body.getAttribute('data-base-url') || '';

function addToCart(productId, quantity = 1) {
    fetch(baseUrl + '/api/cart/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ product_id: productId, quantity: quantity })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update cart badges
            document.querySelectorAll('.cart-badge').forEach(badge => {
                badge.innerText = data.total_items;
                badge.style.display = data.total_items > 0 ? 'flex' : 'none';
            });
            showToast(data.message || 'Ürün sepete eklendi.');
        } else {
            showToast(data.message || 'Hata oluştu.', 'error');
        }
    })
    .catch(err => {
        console.error('Cart error:', err);
        showToast('Bağlantı hatası oluştu.', 'error');
    });
}

function updateCart(productId, quantity) {
    fetch(baseUrl + '/api/cart/update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ product_id: productId, quantity: quantity })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        } else {
            showToast(data.message || 'Hata oluştu.', 'error');
        }
    })
    .catch(err => console.error(err));
}

// Simple Toast Notification
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    toast.innerText = message;
    
    // Inject styles if not present
    if (!document.getElementById('toast-styles')) {
        const style = document.createElement('style');
        style.id = 'toast-styles';
        style.innerText = `
            .toast-notification {
                position: fixed;
                bottom: 80px;
                right: 20px;
                background-color: #10b981;
                color: white;
                padding: 12px 24px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 10000;
                font-family: sans-serif;
                font-weight: 600;
                animation: toast-in 0.3s ease forwards;
            }
            .toast-notification.error { background-color: #ef4444; }
            @keyframes toast-in {
                from { transform: translateY(50px); opacity: 0; }
                to { transform: translateY(0); opacity: 1; }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(toast);
    setTimeout(() => {
        toast.style.animation = 'toast-in 0.3s ease reverse forwards';
        setTimeout(() => toast.remove(), 300);
    }, 2500);
}

// ═══════════════════════════════════════════════════════
// BOTTOM SHEETS LOGIC
// ═══════════════════════════════════════════════════════
window.openBottomSheet = function(id) {
    const sheet = document.getElementById(id);
    const backdrop = document.getElementById('sheetBackdrop');
    if (sheet && backdrop) {
        backdrop.classList.add('show');
        sheet.classList.add('show');
    }
};

window.closeAllBottomSheets = function() {
    const backdrop = document.getElementById('sheetBackdrop');
    if (backdrop) backdrop.classList.remove('show');
    document.querySelectorAll('.bottom-sheet').forEach(sheet => {
        sheet.classList.remove('show');
    });
};

window.focusMobileSearch = function() {
    closeAllBottomSheets();
    window.scrollTo({ top: 0, behavior: 'smooth' });
    
    // Fallback logic to focus the input after smooth scroll
    setTimeout(() => {
        const mobileInput = document.querySelector('.mob-hdr-search input[name="q"]');
        if (mobileInput) {
            mobileInput.focus();
        } else {
            const desktopInput = document.querySelector('.hdr-search input[name="q"]');
            if (desktopInput) desktopInput.focus();
        }
    }, 400);
};

// ═══════════════════════════════════════════════════════
// PWA INSTALL LOGIC
// ═══════════════════════════════════════════════════════
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
    // Prevent default browser banner so we can use our premium button
    e.preventDefault();
    deferredPrompt = e;
    
    const installGroup = document.getElementById('pwa-install-group');
    if (installGroup) {
        installGroup.style.display = 'block';
    }

    // Show top banner only on mobile devices and if not dismissed
    if (window.innerWidth <= 768 && !localStorage.getItem('pwa-banner-dismissed')) {
        const banner = document.getElementById('pwa-install-banner');
        if (banner) banner.style.display = 'flex';
    }
});

async function triggerInstall() {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    if (outcome === 'accepted') {
        console.log('User installed the PWA');
    }
    deferredPrompt = null;
    
    const installGroup = document.getElementById('pwa-install-group');
    if (installGroup) installGroup.style.display = 'none';
    
    const banner = document.getElementById('pwa-install-banner');
    if (banner) banner.style.display = 'none';
}

const installBtn = document.getElementById('pwa-install-btn');
if (installBtn) {
    installBtn.addEventListener('click', triggerInstall);
}

const bannerInstallBtn = document.getElementById('pwa-banner-install');
if (bannerInstallBtn) {
    bannerInstallBtn.addEventListener('click', triggerInstall);
}

const bannerCloseBtn = document.getElementById('pwa-banner-close');
if (bannerCloseBtn) {
    bannerCloseBtn.addEventListener('click', () => {
        localStorage.setItem('pwa-banner-dismissed', 'true');
        const banner = document.getElementById('pwa-install-banner');
        if (banner) banner.style.display = 'none';
    });
}
