// --- EMERGENCY FIXES v1.6 (Consolidated) ---
alert("SYSTEM CHECK: Emergency Fix Loaded v3.0"); // Debugging Alert
console.log("SYSTEM CHECK: Emergency Fix Loaded");

// --- 0. DATA SYNCHRONIZATION (REAL PRODUCTS) ---
window.fetchListings = async function () {
    console.log("Fetching real listings from server...");
    try {
        // Prevent caching with timestamp
        const res = await fetch('../server/listings.php?t=' + Date.now());
        const data = await res.json();

        if (data.success && Array.isArray(data.listings)) {
            window.SERVER_CACHE = data.listings;
            console.log(`Loaded ${data.listings.length} real listings.`);

            // Refresh UI if active
            if (document.getElementById('view-browse').classList.contains('active')) {
                renderBrowseFeed();
            }
            if (typeof renderPins === 'function') {
                renderPins();
                // Safety: Re-render slightly later to ensure map bounds/init
                setTimeout(renderPins, 500);
            }
        } else {
            console.warn("Server returned no listings or error", data);
            window.SERVER_CACHE = [];
        }
    } catch (e) {
        console.error("Failed to fetch listings:", e);
        // Fallback to empty if server fails, do NOT use MOCK_DB
        window.SERVER_CACHE = [];
    }
};

// OVERRIDE: Get Listings (Strict Real Data Only)
window.getListings = function () {
    // 1. Server Cache (Real User Listings from PHP)
    const serverListings = window.SERVER_CACHE || [];

    // 2. Store Products (Official Inventory from products.js)
    // We treat these as "Real" official stock.
    let storeProducts = [];
    if (typeof window.productsData !== 'undefined' && Array.isArray(window.productsData)) {
        storeProducts = window.productsData.map(p => ({
            ...p,
            type: 'sell',
            isStoreItem: true,
            sellerName: 'Ghadget Official',
            sellerVerified: true,
            rating: 5.0,
            // Ensure location is set (HQ)
            location: p.location || { lat: 9.0765, lng: 7.3986, name: "Ghadget HQ" },
            whatsapp: "2348123456789"
        }));
    }

    // COMBINE & RETURN
    // Explicitly EXCLUDING MOCK_DB and localStorage backups to prioritize official/server data
    const combined = [...serverListings, ...storeProducts];

    // Safety Fallback: If combined is empty, at least return store products to ensure map isn't blank
    if (combined.length === 0 && storeProducts.length > 0) return storeProducts;

    return combined;
};

// FORCE RENDER PINS (Override logic.js)
window.renderPins = function (filterText = null) {
    if (typeof map === 'undefined' || !map) return;

    // Clear existing markers (except user/halo)
    if (typeof markers !== 'undefined') {
        markers.forEach(m => map.removeLayer(m));
        window.markers = [];
    } else {
        window.markers = [];
    }

    const allListings = getListings();
    console.log(`RenderPins (Emergency): Processing ${allListings.length} items. Mode: ${window.currentMapMode || 'buy'}`);

    allListings.forEach(item => {
        // Skip items without location (e.g. Main Store Items might need defaults if missing)
        // Note: enrichData() ensures location is present, so this check is just safety.
        if (!item.location && !item.loc) return;

        // Filter: Mode (Sell vs Buy)
        const itemType = item.type || 'sell';
        let isMatch = false;

        // Relaxed Logic:
        // 'buy' mode (default) -> Show 'sell' items (Standard listing) AND Store Items
        if ((!window.currentMapMode || window.currentMapMode === 'buy') && (itemType === 'sell' || item.isStoreItem)) isMatch = true;

        // 'sell' mode -> Show 'buy' requests
        if (window.currentMapMode === 'sell' && itemType === 'buy') isMatch = true;

        if (!isMatch) return;

        // Filter: Text (Case Insensitive)
        if (filterText && filterText !== 'All') {
            const txt = filterText.toLowerCase();
            const match = (
                (item.title && item.title.toLowerCase().includes(txt)) ||
                (item.category && item.category.toLowerCase().includes(txt)) ||
                (item.brand && item.brand.toLowerCase().includes(txt))
            );
            if (!match) return;
        }

        // Create Marker
        const lat = item.location ? item.location.lat : item.loc[0];
        const lng = item.location ? item.location.lng : item.loc[1];

        // Icon Logic
        let iconHtml = '';
        if (item.type === 'buy') {
            iconHtml = `<div class="w-8 h-8 rounded-full bg-green-500 border-2 border-white shadow-lg flex items-center justify-center text-white"><span class="material-symbols-outlined text-[16px]">shopping_cart</span></div>`;
        } else if (item.isStoreItem) {
            iconHtml = `<div class="w-8 h-8 rounded-full bg-blue-600 border-2 border-white shadow-lg flex items-center justify-center text-white"><span class="material-symbols-outlined text-[16px]">storefront</span></div>`;
        } else {
            iconHtml = `<div class="w-8 h-8 rounded-full bg-red-500 border-2 border-white shadow-lg flex items-center justify-center text-white"><span class="material-symbols-outlined text-[16px]">sell</span></div>`;
        }

        const icon = L.divIcon({
            className: 'custom-pin',
            html: iconHtml,
            iconSize: [32, 32],
            iconAnchor: [16, 32]
        });

        const marker = L.marker([lat, lng], { icon: icon }).addTo(map);
        marker.item = item;
        marker.on('click', () => openProductModal(item));
        window.markers.push(marker);
    });
};

// Auto-Fetch on Load
document.addEventListener('DOMContentLoaded', () => {
    fetchListings();
});

// --- 1. CORE NAVIGATION & MODALS ---

// Fix: handleContactAction must check selectedProduct
window.handleContactAction = function (action) {
    if (window.closeContactModal) window.closeContactModal();
    const item = (window.activeRide && window.activeRide.item) || window.selectedProduct;

    if (!item) {
        if (typeof showMessage === 'function') showMessage("Error", "No item selected.", "error");
        else alert("No item selected.");
        return;
    }

    if (!window.activeRide) window.activeRide = {};
    window.activeRide.item = item;

    if (action === 'whatsapp') {
        if (typeof trackWhatsappClick === 'function') trackWhatsappClick(item.id);
        const phone = item.whatsapp || item.sellerPhone || '2348100000000';
        const msg = encodeURIComponent(`Hi, I'm interested in your ${item.title} listed on GadgetGo for ${item.price ? formatCurrency(item.price) : 'Price'}.`);
        window.open(`https://wa.me/${phone}?text=${msg}`, '_blank');
    } else if (action === 'chat' || action === 'in-app') {
        if (typeof startChat === 'function') startChat(item.id);
    } else if (action === 'directions') {
        createTransportModal();
    }
};

window.createTransportModal = function () {
    const modal = document.getElementById('transport-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
};

window.getDirection = function () {
    createTransportModal();
};

window.requestDeal = function () {
    // Default to WhatsApp for "Buy Now" flow as requested
    window.handleContactAction('whatsapp');
};

// --- 2. PRODUCT MODAL (Rich UI Actions - Full DOM Replace) ---
window.openProductModal = function (item) {
    if (!item && window.activeRide) item = window.activeRide.item;
    if (!item) return;

    window.selectedProduct = item;
    const modal = document.getElementById('product-modal-fixed');
    if (!modal) {
        alert("Fatal: Modal element not found! Please reload.");
        return;
    }

    // --- 1. DATA MAPPING ---
    const data = {
        title: item.title || item.name || 'Unknown Item',
        price: item.price ? (typeof item.price === 'number' ? '₦' + item.price.toLocaleString() : item.price) : 'Contact for Price',
        desc: item.description || item.desc || 'No detailed description available for this item.',
        condition: item.condition || 'Used',
        brand: item.brand || 'Generic',
        swap: item.swap ? 'Yes' : 'No',
        seller: item.sellerName || 'Verified Seller',
        rating: item.sellerRating || '4.9',
        reviews: item.reviews || Math.floor(Math.random() * 50) + 10,
        avatar: item.sellerAvatar || 'https://ui-avatars.com/api/?name=' + (item.sellerName || 'S') + '&background=random',
        location: item.location || 'Lagos, Nigeria',
        images: (item.images && item.images.length) ? item.images : [item.image || 'https://placehold.co/300']
    };

    // --- 2. GENERATE FULL HTML ---
    // We completely replace the modal content to ensure consistent UI across all pages
    const imagesHTML = data.images.map(src =>
        `<div class="w-full h-full shrink-0 bg-cover bg-center snap-center" style="background-image: url('${src}')"></div>`
    ).join('');

    const newContent = `
        <div class="bg-white w-full h-[90vh] sm:h-auto sm:max-w-md rounded-t-[2.5rem] sm:rounded-[2.5rem] p-0 shadow-2xl transform transition-transform flex flex-col overflow-hidden relative">
            
            <!-- Close Button -->
            <button onclick="window.closeProductModal()" class="absolute top-4 right-4 w-10 h-10 rounded-full bg-black/20 backdrop-blur flex items-center justify-center text-white hover:bg-black/30 transition z-50">
                <span class="material-symbols-outlined">close</span>
            </button>

            <!-- Image Carousel -->
            <div class="h-64 sm:h-72 bg-gray-100 relative shrink-0">
                <div id="modal-images" class="w-full h-full flex overflow-x-auto snap-x snap-mandatory no-scrollbar bg-gray-200">
                    ${imagesHTML}
                </div>
                <div class="absolute top-4 left-4 bg-white/90 px-2 py-1 rounded text-[10px] font-bold shadow-sm uppercase">Selling</div>
            </div>

            <!-- Content -->
            <div class="p-6 flex-1 overflow-y-auto">
                <div class="flex items-start justify-between mb-2">
                    <h2 class="text-2xl font-bold text-gray-900 leading-tight">${data.title}</h2>
                    <p class="text-xl font-bold text-blue-600 shrink-0">${data.price}</p>
                </div>

                <!-- Seller Profile Card -->
                <div class="bg-gray-50 p-4 rounded-2xl mb-6 flex items-center justify-between border border-gray-100">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 rounded-full bg-cover bg-center border-2 border-white shadow-sm" style="background-image: url('${data.avatar}')"></div>
                        <div>
                            <h4 class="font-bold text-gray-900 text-sm">${data.seller}</h4>
                            <div class="flex items-center text-xs text-gray-500 gap-1">
                                <span class="material-symbols-outlined text-[14px] text-yellow-500 fill-1">star</span>
                                <span class="font-bold text-gray-800">${data.rating}</span>
                                <span>(${data.reviews} reviews)</span>
                            </div>
                        </div>
                    </div>
                    <button onclick="startChat('${item.id}')" class="w-10 h-10 rounded-full bg-white border border-gray-200 flex items-center justify-center text-blue-600 shadow-sm hover:scale-110 transition">
                        <span class="material-symbols-outlined">chat</span>
                    </button>
                </div>

                <!-- Quick Actions Grid -->
                <div class="grid grid-cols-4 gap-2 mb-6">
                    <button onclick="alert('Opening Maps...')" class="flex flex-col items-center gap-1 p-2 rounded-xl bg-blue-50 text-blue-600 hover:bg-blue-100 transition">
                        <span class="material-symbols-outlined text-2xl">directions</span>
                        <span class="text-[10px] font-bold">Directions</span>
                    </button>
                    <button onclick="alert('Calling Seller...')" class="flex flex-col items-center gap-1 p-2 rounded-xl bg-green-50 text-green-600 hover:bg-green-100 transition">
                        <span class="material-symbols-outlined text-2xl">call</span>
                        <span class="text-[10px] font-bold">Call</span>
                    </button>
                    <button onclick="shareItem('${item.id}')" class="flex flex-col items-center gap-1 p-2 rounded-xl bg-purple-50 text-purple-600 hover:bg-purple-100 transition">
                        <span class="material-symbols-outlined text-2xl">share</span>
                        <span class="text-[10px] font-bold">Share</span>
                    </button>
                    <button onclick="alert('Reported')" class="flex flex-col items-center gap-1 p-2 rounded-xl bg-red-50 text-red-600 hover:bg-red-100 transition">
                        <span class="material-symbols-outlined text-2xl">flag</span>
                        <span class="text-[10px] font-bold">Report</span>
                    </button>
                </div>

                <!-- Specs Grid -->
                <div class="grid grid-cols-3 gap-2 mb-6">
                    <div class="bg-gray-50 p-2 rounded-xl text-center">
                        <p class="text-[10px] text-gray-400 uppercase font-bold">Condition</p>
                        <p class="text-xs font-bold text-gray-800">${data.condition}</p>
                    </div>
                    <div class="bg-gray-50 p-2 rounded-xl text-center">
                        <p class="text-[10px] text-gray-400 uppercase font-bold">Brand</p>
                        <p class="text-xs font-bold text-gray-800">${data.brand}</p>
                    </div>
                    <div class="bg-gray-50 p-2 rounded-xl text-center">
                        <p class="text-[10px] text-gray-400 uppercase font-bold">Swap?</p>
                        <p class="text-xs font-bold text-gray-800">${data.swap}</p>
                    </div>
                </div>

                <div class="mb-24">
                    <h3 class="font-bold text-gray-900 mb-2">Description</h3>
                    <p class="text-sm text-gray-600 leading-relaxed">${data.desc}</p>
                </div>
            </div>

            <!-- Fixed Footer Actions -->
            <div class="absolute bottom-0 left-0 right-0 p-4 bg-white border-t border-gray-100 flex gap-3 pb-safe-bottom">
                <button onclick="requestDeal()" class="flex-1 bg-blue-600 text-white font-bold h-12 rounded-xl shadow-lg shadow-blue-200 flex items-center justify-center gap-2 hover:bg-blue-700">
                    Start Deal
                </button>
            </div>
        </div>
    `;

    // --- 3. APPLY FULL REPLACEMENT ---
    // WARNING: This replaces all children of the modal container.
    // Ensure product-modal-fixed is just a wrapper (flex container).
    modal.innerHTML = newContent;

    // --- 4. FORCE VISIBILITY ---
    modal.classList.remove('hidden');
    modal.classList.add('flex', 'open');
    modal.style.display = 'flex';
    modal.style.transform = 'translateY(0)';
    modal.style.opacity = '1';
    modal.style.zIndex = '9999';

    if (typeof closeSheet === 'function') closeSheet();
};

window.closeProductModal = function () {
    const modal = document.getElementById('product-modal-fixed');
    if (modal) {
        modal.classList.add('hidden');
        modal.classList.remove('open');
        modal.style.transform = '';
        modal.style.display = 'none';
    }
};


// --- 3. FEED & UX (Tabs, Badges, Search) ---
let browseState = { tab: 'sell', sort: 'newest' };

window.renderBrowseFeed = function (filterCategory = null, searchQuery = null, sortOverride = null, tabOverride = null) {
    console.log("Emergency renderBrowseFeed Triggered");
    const container = document.getElementById('browse-feed');
    if (!container) return;

    if (sortOverride) browseState.sort = sortOverride;
    if (tabOverride) browseState.tab = tabOverride;

    container.innerHTML = '';

    // HEADER (Tabs & Sort)
    const controls = document.createElement('div');
    controls.className = "col-span-2 sticky top-0 bg-gray-50/95 backdrop-blur z-20 pb-0 -mt-2 border-b border-gray-200";
    controls.innerHTML = `
        <div class="flex items-center justify-between px-1 py-2">
            <div class="flex bg-gray-200 rounded-lg p-1 gap-1">
                <button onclick="renderBrowseFeed('${filterCategory || ''}', '${searchQuery || ''}', null, 'sell')" 
                        class="px-3 py-1.5 rounded-md text-xs font-bold transition ${browseState.tab === 'sell' ? 'bg-white shadow text-gray-900' : 'text-gray-500 hover:text-gray-700'}">
                    For Sale
                </button>
                <button onclick="renderBrowseFeed('${filterCategory || ''}', '${searchQuery || ''}', null, 'buy')" 
                        class="px-3 py-1.5 rounded-md text-xs font-bold transition ${browseState.tab === 'buy' ? 'bg-white shadow text-gray-900' : 'text-gray-500 hover:text-gray-700'}">
                    Buyer Requests
                </button>
            </div>
            <select onchange="renderBrowseFeed('${filterCategory || ''}', '${searchQuery || ''}', this.value, null)" 
                    class="bg-white border text-xs font-bold px-2 py-1.5 rounded-lg text-gray-700 outline-none">
                <option value="newest" ${browseState.sort === 'newest' ? 'selected' : ''}>Newest</option>
                <option value="price_asc" ${browseState.sort === 'price_asc' ? 'selected' : ''}>Price: Low to High</option>
                <option value="price_desc" ${browseState.sort === 'price_desc' ? 'selected' : ''}>Price: High to Low</option>
            </select>
        </div>
        
        <!-- Colorful Category Chips -->
        <div class="flex gap-2 overflow-x-auto no-scrollbar pb-3 px-1">
             <button onclick="renderBrowseFeed('All', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-white text-gray-700 text-[11px] font-bold shadow-sm border border-gray-100 whitespace-nowrap hover:bg-gray-100 transition ring-1 ring-transparent hover:ring-gray-200">All</button>
            <button onclick="renderBrowseFeed('Smartphones', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-blue-50 text-blue-600 text-[11px] font-bold shadow-sm border border-blue-100 whitespace-nowrap hover:bg-blue-100 transition">Smartphones</button>
            <button onclick="renderBrowseFeed('Laptops', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-purple-50 text-purple-600 text-[11px] font-bold shadow-sm border border-purple-100 whitespace-nowrap hover:bg-purple-100 transition">Laptops</button>
            <button onclick="renderBrowseFeed('Consoles', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-indigo-50 text-indigo-600 text-[11px] font-bold shadow-sm border border-indigo-100 whitespace-nowrap hover:bg-indigo-100 transition">Consoles</button>
            <button onclick="renderBrowseFeed('Cameras', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-pink-50 text-pink-600 text-[11px] font-bold shadow-sm border border-pink-100 whitespace-nowrap hover:bg-pink-100 transition">Cameras</button>
             <button onclick="renderBrowseFeed('Tablets', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-teal-50 text-teal-600 text-[11px] font-bold shadow-sm border border-teal-100 whitespace-nowrap hover:bg-teal-100 transition">Tablets</button>
            <button onclick="renderBrowseFeed('Drones', '${searchQuery || ''}')"
                class="px-3 py-1.5 rounded-full bg-orange-50 text-orange-600 text-[11px] font-bold shadow-sm border border-orange-100 whitespace-nowrap hover:bg-orange-100 transition">Drones</button>
        </div>

        ${filterCategory && filterCategory !== 'All' ? `<div class="px-1 mt-1 mb-1"><span class="bg-primary/10 text-primary text-[10px] font-bold px-2 py-0.5 rounded-full inline-flex items-center gap-1">Category: ${filterCategory} <span onclick="renderBrowseFeed(null, '${searchQuery || ''}')" class="cursor-pointer hover:text-red-500">&times;</span></span></div>` : ''}
    `;
    container.appendChild(controls);

    // FETCH & FILTER
    let listings = (typeof getListings === 'function') ? getListings() : (window.SERVER_CACHE || []);

    listings = listings.filter(i => {
        if (browseState.tab === 'sell') return (i.type === 'sell' || !i.type || i.isStoreItem === true);
        else return (i.type === 'buy');
    });

    if (searchQuery) {
        const q = searchQuery.toLowerCase();
        listings = listings.filter(i => (i.title && i.title.toLowerCase().includes(q)) || (i.category && i.category.toLowerCase().includes(q)));
    }
    if (filterCategory && filterCategory !== 'All') {
        const catFilter = filterCategory.toLowerCase();

        listings = listings.filter(i => {
            const cat = (i.category || '').toLowerCase();
            const sub = (i.subcategory || '').toLowerCase();
            // Case-Insensitive Check
            return cat.includes(catFilter) || sub.includes(catFilter) || cat === catFilter;
        });
    }

    // SORT
    listings.sort((a, b) => {
        if (browseState.sort === 'price_asc') return (a.price || 0) - (b.price || 0);
        if (browseState.sort === 'price_desc') return (b.price || 0) - (a.price || 0);
        return (b.id || 0) - (a.id || 0); // Newest
    });

    // RENDER
    if (listings.length === 0) {
        container.innerHTML += `<div class="col-span-2 text-center py-12 text-gray-400"><p class="text-sm font-bold">No results found.</p></div>`;
        return;
    }

    listings.forEach(item => {
        const img = (item.images && item.images[0]) ? item.images[0] : (item.image || 'https://placehold.co/300');
        const badge = item.type === 'buy'
            ? '<span class="absolute top-2 left-2 bg-green-600 text-white text-[9px] font-bold px-2 py-0.5 rounded-full shadow-sm">REQUEST</span>'
            : (item.views > 100 ? '<span class="absolute top-2 left-2 bg-orange-500 text-white text-[9px] font-bold px-2 py-0.5 rounded-full shadow-sm flex items-center gap-0.5"><span class="material-symbols-outlined text-[10px]">local_fire_department</span> HOT</span>' : '<span class="absolute top-2 left-2 bg-white/90 text-gray-800 text-[9px] font-bold px-2 py-0.5 rounded-full shadow-sm">SELLING</span>');

        const el = document.createElement('div');
        el.className = "bg-white p-2 rounded-2xl shadow-sm border border-gray-100 hover:shadow-md transition cursor-pointer relative group";
        el.onclick = () => openProductModal(item); // Fix Click Handler
        el.innerHTML = `
            <div class="aspect-square rounded-xl bg-gray-100 bg-cover bg-center mb-2 relative overflow-hidden" style="background-image: url('${img}')">
                ${badge}
            </div>
            <h3 class="font-bold text-gray-900 text-sm truncate px-1">${item.title}</h3>
            <div class="flex items-center justify-between px-1 mt-1">
                <p class="text-primary font-bold text-xs">${formatCurrency(item.price)}</p>
                <div class="flex items-center gap-0.5 text-[10px] text-gray-400">
                    <span class="material-symbols-outlined text-[12px]">visibility</span> ${item.views || 0}
                </div>
            </div>
            <div class="mt-2 text-center pb-1">
                <button onclick="event.stopPropagation(); window.productClickDispatcher('${item.id}')" 
                    class="w-full bg-primary/10 hover:bg-primary hover:text-white text-primary text-xs font-bold py-2 rounded-lg transition-colors flex items-center justify-center gap-1">
                    <span class="material-symbols-outlined text-[14px]">visibility</span>
                    ${item.type === 'buy' ? 'I Have This' : 'View Details'}
                </button>
            </div>
        `;


        // --- ROBUST CLICK HANDLER (INLINE) ---
        // Using inline onclick to guarantee execution even if listeners fail/detach
        // We set a unique ID or pass data via a global lookup if needed, but passing ID is safest.

        // Ensure global dispatcher exists
        if (!window.productClickDispatcher) {
            window.productClickDispatcher = function (itemId) {
                console.log("Global Dispatcher Clicked:", itemId);
                const item = (window.SERVER_CACHE || []).find(i => i.id == itemId) || (window.productsData || []).find(p => p.id == itemId);

                if (item) {
                    if (window.openProductModal) window.openProductModal(item);
                    else alert("Product modal function missing.");
                } else {
                    // Fallback: search in all listings getter
                    const all = (typeof getListings === 'function') ? getListings() : [];
                    const found = all.find(i => i.id == itemId);
                    if (found && window.openProductModal) window.openProductModal(found);
                    else console.error("Item not found for ID:", itemId);
                }
            };
        }

        el.setAttribute('onclick', `window.productClickDispatcher('${item.id}')`);

        // Visual Feedback
        el.style.cursor = 'pointer';

        container.appendChild(el);
    });
};


// --- 4. MAP & LOCATION FIXES ---
window.locateUser = function () {
    if (!navigator.geolocation) {
        showMessage("Error", "Geolocation not supported", "error");
        return;
    }

    showMessage("Locating...", "Acquiring position...", "info");

    const timeout = setTimeout(() => {
        if (window.closeMsgModal) closeMsgModal();
        showMessage("Timeout", "Position unavailable. Search manually.", "error");
    }, 10000);

    navigator.geolocation.getCurrentPosition(
        (pos) => {
            clearTimeout(timeout);
            if (window.closeMsgModal) closeMsgModal();
            const { latitude: lat, longitude: lng } = pos.coords;

            if (window.map) {
                window.map.setView([lat, lng], 16);
                // showUserPulse([lat, lng]); // Assuming this exists or we mock it
            }
            showMessage("Found You", "Location updated.", "success");
        },
        (err) => {
            clearTimeout(timeout);
            if (window.closeMsgModal) closeMsgModal();
            showMessage("GPS Error", err.message || "Denied", "error");
        },
        { enableHighAccuracy: true, timeout: 9000 }
    );
};

// --- 5. SUGGESTIONS MODAL ---
window.showSuggestionsModal = function (type) {
    let modal = document.getElementById('suggestions-modal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'suggestions-modal';
        modal.className = "fixed inset-0 z-[450] bg-black/60 backdrop-blur-md flex items-end justify-center transition-opacity";
        modal.innerHTML = `
            <div class="bg-white w-full max-w-lg rounded-t-[2.5rem] p-6 shadow-2xl animate-slide-up">
                <div class="w-12 h-1.5 bg-gray-200 rounded-full mx-auto mb-6"></div>
                <h3 id="sugg-title" class="text-xl font-bold text-gray-900 mb-4">You might like...</h3>
                <div id="sugg-grid" class="flex flex-col gap-3 max-h-[50vh] overflow-y-auto"></div>
                <button onclick="closeSuggestionsModal()" class="w-full py-4 mt-4 bg-gray-100 rounded-xl font-bold text-gray-900">Close</button>
            </div>
        `;
        document.body.appendChild(modal);
    }

    const grid = document.getElementById('sugg-grid');
    grid.innerHTML = '';

    // Get Items
    const items = (typeof getListings === 'function') ? getListings().slice(0, 5) : [];

    if (items.length === 0) {
        grid.innerHTML = '<p class="text-center text-gray-500 text-sm">No suggestions available right now.</p>';
    } else {
        items.forEach(item => {
            const row = document.createElement('div');
            row.className = "flex items-center gap-3 p-3 bg-gray-50 rounded-xl hover:bg-gray-100 cursor-pointer";
            row.onclick = () => { closeSuggestionsModal(); openProductModal(item); };
            row.innerHTML = `
               <div class="w-12 h-12 rounded-lg bg-gray-200 bg-cover bg-center" style="background-image: url('${item.image || (item.images && item.images[0])}')"></div>
               <div>
                   <h4 class="font-bold text-sm text-gray-900">${item.title}</h4>
                   <p class="text-xs text-primary font-bold">${formatCurrency(item.price)}</p>
               </div>
           `;
            grid.appendChild(row);
        });
    }

    modal.classList.remove('hidden');
};

window.closeSuggestionsModal = function () {
    const modal = document.getElementById('suggestions-modal');
    if (modal) modal.classList.add('hidden');
};


// --- 6. UTILITIES & VIEW SWITCHING ---

// Fix Currency
window.formatCurrency = function (amount) {
    if (typeof amount !== 'number') return 'Contact';
    try {
        return new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' }).format(amount);
    } catch (e) {
        return '₦' + amount;
    }
};

// Override SwitchView to handle Report Button Visibility
window.switchView = function (viewId) {
    document.querySelectorAll('.view-section').forEach(el => {
        el.classList.remove('active');
        if (el.id !== 'view-map') el.style.display = 'none'; // Ensure hidden
    });

    // Special logic for map background
    if (viewId === 'map') {
        document.getElementById('view-map').classList.add('active');
        document.getElementById('view-map').style.display = 'flex';
    } else if (viewId === 'browse') {
        document.getElementById('view-browse').classList.add('active');
        document.getElementById('view-browse').style.display = 'flex';
        // Force render to ensure correct state
        renderBrowseFeed();
    } else {
        const target = document.getElementById(viewId.startsWith('view-') ? viewId : 'view-' + viewId);
        if (target) {
            target.classList.add('active');
            target.style.display = 'flex';
        }
    }

    // REPORT BUTTON VISIBILITY
    const reportBtn = document.getElementById('fab-report') || document.querySelector('button[title="Report Issue"]');
    if (reportBtn) {
        reportBtn.style.display = (viewId === 'map') ? 'flex' : 'none';
        if (viewId === 'map') reportBtn.classList.remove('hidden');
        else reportBtn.classList.add('hidden');
    }

    // UPDATE FOOTER (Emergency Impl)
    document.querySelectorAll('.nav-btn').forEach(b => {
        b.classList.remove('text-primary');
        b.classList.add('text-gray-400');
    });
    const ids = { map: 'nav-map', browse: 'nav-browse', favorites: 'nav-favorites', wallet: 'nav-wallet', profile: 'nav-profile' };
    const btn = document.getElementById(ids[viewId]);
    if (btn) {
        btn.classList.add('text-primary');
        btn.classList.remove('text-gray-400');
    }
};

// --- 7. PROFILE (Logout & Listings) ---
// --- 7. PROFILE (Logout & Listings) ---
window.fetchAndRenderUserListings = function () {
    const container = document.getElementById('profile-listings');
    const refreshBtn = document.querySelector('button[onclick="fetchAndRenderUserListings()"]');

    if (!container) return;

    // UI Feedback: Loading
    if (refreshBtn) {
        const originalText = refreshBtn.innerHTML;
        refreshBtn.innerHTML = '<span class="material-symbols-outlined animate-spin text-xs">sync</span>';
        refreshBtn.disabled = true;

        setTimeout(() => {
            runRender();
            refreshBtn.innerHTML = originalText;
            refreshBtn.disabled = false;
            // Optional: Toast
            // showToast("Listings updated"); // If showToast exists
        }, 500);
    } else {
        runRender();
    }

    function runRender() {
        // 1. Get Current User
        let currentUser = null;
        try {
            const userStr = localStorage.getItem('ghadget_user');
            if (userStr) {
                currentUser = JSON.parse(userStr);
            }
        } catch (e) { console.error("User Parse Error", e); }

        const currentUserName = currentUser ? currentUser.name : 'Guest';
        console.log("Rendering Profile for:", currentUserName);

        // 2. Fetch & Filter
        // Ensure we check both window.SERVER_CACHE (if logic.js populates it) and getListings()
        const allListings = (typeof getListings === 'function') ? getListings() : (window.SERVER_CACHE || []);

        // Filter strategy
        const items = allListings.filter(i =>
            (i.sellerName === currentUserName) ||
            (i.isUserListing === true) ||
            (i.seller === currentUserName)
        );

        if (items.length === 0) {
            container.innerHTML = `
                <div class="col-span-2 py-8 flex flex-col items-center justify-center text-gray-400 bg-white rounded-2xl border border-dashed border-gray-200">
                    <span class="material-symbols-outlined text-3xl mb-2 opacity-50">inventory_2</span>
                    <p class="text-xs">No active listings.</p>
                </div>`;
        } else {
            container.innerHTML = items.map(i => `
                <div class="bg-white p-3 rounded-xl shadow-sm border border-gray-100 flex items-center justify-between gap-3">
                    <div class="flex items-center gap-3 flex-1 min-w-0">
                        <div class="w-12 h-12 rounded-lg bg-gray-100 bg-cover bg-center shrink-0" 
                             style="background-image: url('${(i.images && i.images[0]) ? i.images[0] : (i.image || 'https://placehold.co/100')}')">
                        </div>
                        <div class="min-w-0">
                            <p class="font-bold text-xs truncate text-gray-900">${i.title}</p>
                            <p class="text-[10px] text-primary font-bold">${formatCurrency(i.price)}</p>
                            <div class="flex items-center gap-1 mt-0.5">
                                 <span class="text-[9px] px-1.5 py-0.5 rounded-md ${i.type === 'buy' ? 'bg-green-100 text-green-700' : 'bg-blue-50 text-blue-600'} font-bold uppercase">${i.type === 'buy' ? 'Request' : 'Selling'}</span>
                                 <span class="text-[9px] text-gray-400 flex items-center gap-0.5"><span class="material-symbols-outlined text-[10px]">visibility</span> ${i.views || 0}</span>
                            </div>
                        </div>
                    </div>
                    <div class="flex flex-col gap-2 shrink-0">
                        <button onclick="editListing('${i.id}')" class="w-8 h-8 rounded-full bg-gray-50 text-gray-600 flex items-center justify-center hover:bg-primary hover:text-white transition shadow-sm">
                            <span class="material-symbols-outlined text-[16px]">edit</span>
                        </button>
                        <button onclick="deleteListing('${i.id}')" class="w-8 h-8 rounded-full bg-red-50 text-red-500 flex items-center justify-center hover:bg-red-500 hover:text-white transition shadow-sm">
                            <span class="material-symbols-outlined text-[16px]">delete</span>
                        </button>
                    </div>
                </div>
            `).join('');
        }
    }
};

// --- EDIT LISTING FUNCTION ---
window.editListing = function (id) {
    const item = (typeof getListings === 'function') ? getListings().find(i => i.id == id) : null;
    if (!item) {
        alert("Listing not found.");
        return;
    }

    // Switch to Listing View
    switchView('listing');

    // Populate Fields
    if (document.getElementById('list-title')) document.getElementById('list-title').value = item.title || '';
    if (document.getElementById('list-price')) document.getElementById('list-price').value = item.price || '';
    if (document.getElementById('list-desc')) document.getElementById('list-desc').value = item.description || item.desc || '';
    if (document.getElementById('list-category')) document.getElementById('list-category').value = item.category || 'Smartphones';
    if (document.getElementById('list-condition')) document.getElementById('list-condition').value = item.condition || 'Used';

    // Extended Specs
    if (document.getElementById('list-brand')) document.getElementById('list-brand').value = item.brand || '';
    if (document.getElementById('list-model')) document.getElementById('list-model').value = item.model || '';
    if (document.getElementById('list-color')) document.getElementById('list-color').value = item.color || '';
    if (document.getElementById('list-storage')) document.getElementById('list-storage').value = item.storage || '';

    // Checkbox
    if (document.getElementById('list-swap')) document.getElementById('list-swap').checked = !!item.swap;

    // Update Button Text (Visual feedback only for now, logic would need to handle update vs create)
    const submitBtn = document.querySelector('#view-listing button[onclick*="createListing"]');
    if (submitBtn) {
        submitBtn.innerHTML = '<span class="material-symbols-outlined">save</span> Update Listing';
        // Note: Actual update logic would require changing the onclick handler or having createListing handle IDs
        // For this emergency fix, we'll let the user "Update" which might create a new one unless we patch createListing too.
        // We will attach the ID to the button to hint 'update mode'
        submitBtn.setAttribute('data-update-id', id);
    }
};

window.deleteListing = function (id) {
    if (!confirm("Are you sure you want to delete this listing? This cannot be undone.")) return;

    // Remove from SERVER_CACHE (Local Simulation)
    if (window.SERVER_CACHE) {
        window.SERVER_CACHE = window.SERVER_CACHE.filter(i => i.id != id);
    }

    // Re-render
    fetchAndRenderUserListings();

    // Optional: Call Backend API
    // fetch('../server/api/delete_listing.php', { method: 'POST', body: JSON.stringify({id}) });
};

// --- 8. CREATION & EDITING LOGIC (Overridden) ---
window.tempUploadedImages = []; // Ensure global access

window.handleImageUpload = async function (input) {
    if (!input.files || input.files.length === 0) return;
    const files = Array.from(input.files);
    const statusEl = document.getElementById('upload-status');

    if (statusEl) {
        statusEl.classList.remove('hidden');
        statusEl.textContent = "Uploading...";
    }

    for (let file of files) {
        // Mock Upload: Use Local FileReader
        const reader = new FileReader();
        reader.onload = (e) => {
            if (window.tempUploadedImages.length < 5) {
                window.tempUploadedImages.push(e.target.result);
                renderUploadGrid();
            } else {
                alert("Max 5 images.");
            }
        };
        reader.readAsDataURL(file);
    }

    if (statusEl) {
        setTimeout(() => { statusEl.classList.add('hidden'); }, 1000);
    }
};

window.renderUploadGrid = function () {
    const grid = document.getElementById('photo-grid');
    if (!grid) return;

    // Keep the first child (Add Button) and the Input
    const addBtn = grid.firstElementChild;
    const fileInput = document.getElementById('file-upload');

    grid.innerHTML = '';
    if (addBtn) grid.appendChild(addBtn);

    window.tempUploadedImages.forEach((src, idx) => {
        const div = document.createElement('div');
        div.className = "aspect-square rounded-2xl bg-gray-100 border border-gray-200 relative overflow-hidden group";
        div.innerHTML = `
            <img src="${src}" class="w-full h-full object-cover">
            <button onclick="removeImage(${idx})" class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center hover:scale-110">
                <span class="material-symbols-outlined text-[12px]">close</span>
            </button>
        `;
        grid.appendChild(div);
    });

    if (fileInput) grid.appendChild(fileInput); // Re-attach input
};

window.removeImage = function (index) {
    window.tempUploadedImages.splice(index, 1);
    renderUploadGrid();
};

window.setListingType = function (type) {
    document.getElementById('list-type').value = type;
    const s = document.getElementById('btn-type-sell');
    const b = document.getElementById('btn-type-buy');
    if (type === 'sell') {
        s.className = "flex-1 py-2 rounded-lg text-sm font-bold text-white bg-primary shadow-sm transition-all";
        b.className = "flex-1 py-2 rounded-lg text-sm font-bold text-gray-500 hover:bg-white transition-all";
    } else {
        b.className = "flex-1 py-2 rounded-lg text-sm font-bold text-white bg-green-600 shadow-sm transition-all";
        s.className = "flex-1 py-2 rounded-lg text-sm font-bold text-gray-500 hover:bg-white transition-all";
    }
};

window.createListing = function () {
    // 1. Get Form Data
    const type = document.getElementById('list-type').value || 'sell';
    const title = document.getElementById('list-title').value;
    const priceStr = document.getElementById('list-price').value.replace(/[^0-9.]/g, '');
    const price = parseFloat(priceStr);
    const desc = document.getElementById('list-desc').value;

    // Validation
    if (!title || isNaN(price)) {
        alert("Please enter a title and price.");
        return;
    }

    // 2. Determine ID (Update vs New)
    const btn = document.querySelector('#view-listing button[onclick*="createListing"]');
    const updateId = btn ? btn.getAttribute('data-update-id') : null;

    const currentUser = JSON.parse(localStorage.getItem('ghadget_user') || '{"name":"Guest"}');

    const newItem = {
        id: updateId ? parseInt(updateId) : Date.now(), // Preserve ID if updating
        title,
        price,
        description: desc,
        type,
        category: document.getElementById('list-category').value,
        condition: document.getElementById('list-condition').value,
        brand: document.getElementById('list-brand').value,
        model: document.getElementById('list-model').value,
        color: document.getElementById('list-color').value,
        storage: document.getElementById('list-storage').value,
        swap: document.getElementById('list-swap').checked,
        images: window.tempUploadedImages.length ? window.tempUploadedImages : ['https://placehold.co/300'],
        sellerName: currentUser.name || 'Guest',
        date: new Date().toISOString(),
        isUserListing: true // Important flag for filtering
    };

    console.log("Saving Item:", newItem);

    // 3. Save to Global Cache
    if (!window.SERVER_CACHE) window.SERVER_CACHE = [];

    if (updateId) {
        // Find and Replace
        const idx = window.SERVER_CACHE.findIndex(i => i.id == updateId);
        if (idx !== -1) window.SERVER_CACHE[idx] = newItem;
        else window.SERVER_CACHE.unshift(newItem); // fallback
        alert("Listing Updated!");
    } else {
        // Add New
        window.SERVER_CACHE.unshift(newItem);
        alert("Listing Posted Successfully!");
    }

    // 4. Reset UI
    if (btn) {
        btn.innerHTML = '<span class="material-symbols-outlined">send</span> Post Listing';
        btn.removeAttribute('data-update-id');
    }
    window.tempUploadedImages = [];
    renderUploadGrid();
    document.getElementById('list-title').value = '';
    document.getElementById('list-price').value = '';
    document.getElementById('list-desc').value = '';

    // 5. Navigate
    window.fetchAndRenderUserListings(); // Refresh profile
    switchView('profile');
};

// --- 9. NOTIFICATION SYSTEM ---
window.renderNotifications = function () {
    const list = document.getElementById('notifications-list');
    if (!list) return;

    const notifs = getMockNotifications();

    if (notifs.length === 0) {
        list.innerHTML = `
            <div class="text-center py-20">
                <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4">
                    <span class="material-symbols-outlined text-3xl text-gray-300">notifications_off</span>
                </div>
                <p class="text-gray-400 font-medium">No new notifications.</p>
            </div>
        `;
        return;
    }

    list.innerHTML = notifs.map(n => {
        let icon = 'notifications';
        let bg = 'bg-gray-100';
        let color = 'text-gray-500';

        // Icon Logic
        switch (n.type) {
            case 'view_profile': icon = 'visibility'; bg = 'bg-blue-50'; color = 'text-blue-500'; break;
            case 'view_product': icon = 'shopping_bag'; bg = 'bg-purple-50'; color = 'text-purple-500'; break;
            case 'admin_mail': icon = 'mail'; bg = 'bg-red-50'; color = 'text-red-500'; break;
            case 'phone_view': icon = 'call'; bg = 'bg-green-50'; color = 'text-green-500'; break;
            case 'ad_expired': icon = 'timer_off'; bg = 'bg-orange-50'; color = 'text-orange-500'; break;
            case 'login': icon = 'lock'; bg = 'bg-gray-900'; color = 'text-white'; break;
            case 'suggestion': icon = 'lightbulb'; bg = 'bg-yellow-50'; color = 'text-yellow-600'; break;
            case 'follower': icon = 'group_add'; bg = 'bg-pink-50'; color = 'text-pink-500'; break;
            case 'rating': icon = 'star'; bg = 'bg-yellow-100'; color = 'text-yellow-600'; break;
            case 'transaction': icon = 'account_balance_wallet'; bg = 'bg-green-100'; color = 'text-green-700'; break;
        }

        return `
            <div class="flex gap-3 p-4 bg-gray-50 rounded-2xl border border-gray-100 relative ${n.read ? 'opacity-70' : 'bg-white shadow-sm border-blue-100'}">
                <div class="w-10 h-10 rounded-full ${bg} ${color} flex items-center justify-center shrink-0">
                    <span class="material-symbols-outlined text-[20px]">${icon}</span>
                </div>
                <div class="flex-1 min-w-0">
                    <h4 class="font-bold text-sm text-gray-900 leading-tight mb-0.5">${n.title}</h4>
                    <p class="text-xs text-gray-500 leading-snug">${n.msg}</p>
                    <p class="text-[10px] text-gray-400 font-bold mt-2 uppercase tracking-wide">${n.time}</p>
                </div>
                ${!n.read ? '<div class="w-2 h-2 rounded-full bg-red-500 absolute top-4 right-4"></div>' : ''}
            </div>
        `;
    }).join('');
};

function getMockNotifications() {
    return [
        { type: 'admin_mail', title: 'System Update', msg: 'We have updated our Terms of Service. Please review.', time: 'Just Now', read: false },
        { type: 'view_product', title: 'New Lead!', msg: 'Someone viewed your iPhone 14 Pro Max listing.', time: '2 mins ago', read: false },
        { type: 'phone_view', title: 'Contact Interest', msg: 'A user revealed your phone number on "MacBook Pro".', time: '10 mins ago', read: false },
        { type: 'transaction', title: 'Wallet Credit', msg: 'You received ₦5,000 commission bonus.', time: '1 hour ago', read: false },
        { type: 'view_profile', title: 'Profile Visit', msg: 'Your profile has 12 new views today.', time: '3 hours ago', read: true },
        { type: 'rating', title: 'New Rating', msg: 'Tunde gave you 5 stars: "Great seller!"', time: '5 hours ago', read: true },
        { type: 'suggestion', title: 'Price Tip', msg: 'Similar items are selling for ₦450k. Consider lowering your price.', time: '1 day ago', read: true },
        { type: 'ad_expired', title: 'Ad Expired', msg: 'Your listing for "Sony Headphones" has expired.', time: '2 days ago', read: true },
        { type: 'follower', title: 'New Follower', msg: 'Chidi Benz started following you.', time: '2 days ago', read: true },
        { type: 'login', title: 'New Login', msg: 'Login detected from iPhone 12, Lagos.', time: '3 days ago', read: true }
    ];
}

// Ensure switchView handles notifications
const originalSwitchView = window.switchView;
window.switchView = function (viewId) {
    if (viewId === 'notifications') {
        renderNotifications();
    }
    if (originalSwitchView) originalSwitchView(viewId);

    // Fallback if original logic missed it
    if (viewId === 'notifications') {
        document.querySelectorAll('.view-section').forEach(el => el.classList.remove('active'));
        const target = document.getElementById('view-notifications');
        if (target) {
            target.classList.add('active');
            target.style.display = 'flex';
        }
    }

    // Security View Handling (Generic)
    if (viewId === 'security') {
        document.querySelectorAll('.view-section').forEach(el => el.classList.remove('active'));
        const target = document.getElementById('view-security');
        if (target) {
            target.classList.add('active');
            target.style.display = 'flex';
        }
        // Init security when opened
        initSecurity();
    }

    // Help View Handling
    if (viewId === 'support') {
        document.querySelectorAll('.view-section').forEach(el => el.classList.remove('active'));
        const target = document.getElementById('view-support');
        if (target) {
            target.classList.add('active');
            target.style.display = 'flex';
        }
    }

    // Favorites View Handling
    if (viewId === 'favorites') {
        // Ensure nav is active
        document.querySelectorAll('.view-section').forEach(el => el.classList.remove('active'));
        const target = document.getElementById('view-favorites');
        if (target) {
            target.classList.add('active');
            target.style.display = 'flex';
        }
        renderSavedItems();
    }
};

// --- 11. SAVED ITEMS (Favorites) ---
window.renderSavedItems = function () {
    const list = document.getElementById('favorites-grid');
    if (!list) return;

    const savedIds = JSON.parse(localStorage.getItem('ghadget_favorites') || '[]');

    // Get all potential items (cache + mock)
    const allItems = (typeof getListings === 'function') ? getListings() : (window.SERVER_CACHE || []);

    // Filter
    const savedItems = allItems.filter(item => savedIds.includes(item.id));

    if (savedItems.length === 0) {
        list.innerHTML = `
            <div class="col-span-2 text-center py-20">
                <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4">
                    <span class="material-symbols-outlined text-3xl text-gray-300">favorite</span>
                </div>
                <p class="text-gray-400 font-medium">No saved items yet.</p>
                <button onclick="switchView('browse')" class="mt-4 text-primary font-bold text-sm">Browse Items</button>
            </div>
        `;
        return;
    }

    list.innerHTML = savedItems.map(item => `
        <div onclick="openItemSheet(${JSON.stringify(item).replace(/"/g, '&quot;')})" 
             class="bg-white rounded-2xl p-3 shadow-sm border border-gray-100 active:scale-95 transition-transform">
            <div class="aspect-square bg-gray-100 rounded-xl mb-3 bg-cover bg-center relative"
                 style="background-image: url('${(item.images && item.images[0]) ? item.images[0] : (item.image || 'https://placehold.co/100')}')">
                 <button onclick="event.stopPropagation(); toggleFavorite('${item.id}', this)" 
                         class="absolute top-2 right-2 w-8 h-8 rounded-full bg-white/90 backdrop-blur shadow-sm flex items-center justify-center">
                    <span class="material-symbols-outlined text-lg text-red-500 filled">favorite</span>
                 </button>
            </div>
            <h4 class="font-bold text-gray-900 text-sm truncate">${item.title}</h4>
            <p class="text-primary font-bold text-xs mt-1">${formatCurrency(item.price)}</p>
        </div>
    `).join('');
};

// --- 10. SECURITY & PRIVACY ---
window.changePassword = function () {
    const oldPass = document.getElementById('sec-old-pass').value;
    const newPass = document.getElementById('sec-new-pass').value;
    const confPass = document.getElementById('sec-conf-pass').value;

    if (!oldPass || !newPass || !confPass) {
        alert("Please fill in all fields.");
        return;
    }
    if (newPass !== confPass) {
        alert("New passwords do not match.");
        return;
    }
    if (newPass.length < 6) {
        alert("Password must be at least 6 characters.");
        return;
    }

    // Mock API Call
    alert("Password updated successfully!");

    // Clear inputs
    document.getElementById('sec-old-pass').value = '';
    document.getElementById('sec-new-pass').value = '';
    document.getElementById('sec-conf-pass').value = '';
};

window.deleteAccount = function () {
    if (!confirm("Are you ABSOLUTELY sure? This action cannot be undone.")) return;
    if (!confirm("This will permanently delete your account, listings, and wallet balance. Proceed?")) return;

    // Clear Logic
    localStorage.clear();
    alert("Account deleted. Goodbye!");
    window.location.reload();
};

window.initSecurity = function () {
    // Load Settings
    const settings = JSON.parse(localStorage.getItem('ghadget_security') || '{}');
    if (settings.autoLogout) {
        const toggle = document.getElementById('sec-logout-toggle');
        if (toggle) toggle.checked = true;
        toggleAutoLogout(true);
        if (settings.duration) document.getElementById('sec-logout-val').value = settings.duration;
        if (settings.unit) document.getElementById('sec-logout-unit').value = settings.unit;
    }
};

window.toggleAutoLogout = function (enabled) {
    const opts = document.getElementById('sec-logout-options');
    if (!opts) return;

    if (enabled) {
        opts.classList.remove('opacity-50', 'pointer-events-none');
    } else {
        opts.classList.add('opacity-50', 'pointer-events-none');
        localStorage.removeItem('ghadget_security'); // Disable
    }
};

window.saveAutoLogoutSettings = function () {
    const duration = parseInt(document.getElementById('sec-logout-val').value);
    const unit = document.getElementById('sec-logout-unit').value;

    if (!duration || duration <= 0) {
        alert("Please enter a valid number.");
        return;
    }

    const settings = { autoLogout: true, duration, unit };
    localStorage.setItem('ghadget_security', JSON.stringify(settings));
    alert(`Auto-logout set to ${duration} ${unit}.`);
};

// Monitor Inactivity
let lastActivity = Date.now();
['mousemove', 'keydown', 'click', 'touchstart'].forEach(evt =>
    document.addEventListener(evt, () => lastActivity = Date.now())
);

setInterval(() => {
    const settings = JSON.parse(localStorage.getItem('ghadget_security') || '{}');
    if (!settings.autoLogout) return;

    let msLimit = 0;
    switch (settings.unit) {
        case 'minutes': msLimit = settings.duration * 60 * 1000; break;
        case 'hours': msLimit = settings.duration * 60 * 60 * 1000; break;
        case 'days': msLimit = settings.duration * 24 * 60 * 60 * 1000; break;
        case 'months': msLimit = settings.duration * 30 * 24 * 60 * 60 * 1000; break;
    }

    if (Date.now() - lastActivity > msLimit) {
        alert("Session expired due to inactivity.");
        window.logout ? window.logout() : window.location.reload();
    }
}, 10000); // Check every 10s


// --- 12. VIEW COUNTING ---
// Helper to get views map
function getLocalViews() {
    return JSON.parse(localStorage.getItem('ghadget_views') || '{}');
}

// Increment views for an item
function incrementItemView(itemId) {
    if (!itemId) return;
    const views = getLocalViews();
    views[itemId] = (views[itemId] || 0) + 1; // Always increment
    localStorage.setItem('ghadget_views', JSON.stringify(views));
    return views[itemId];
}

// Override openItemSheet to track views AND show them
// We need to capture the original if logic.js is loaded
// Since logic.js is loaded BEFORE this file, window.openItemSheet should be defined.
const _originalOpenItemSheet = window.openItemSheet;

window.openItemSheet = function (item) {
    if (!item || !item.id) {
        if (_originalOpenItemSheet) _originalOpenItemSheet(item);
        return;
    }

    // 1. Increment Views
    const newCount = incrementItemView(item.id);
    item.views = newCount; // Update memory object

    // 2. Call Original Display Logic
    if (_originalOpenItemSheet) {
        _originalOpenItemSheet(item);
    } else {
        console.warn("Original openItemSheet not found, falling back to simple display");
        // Fallback display if logic.js is broken
        // (Simplified logic from logic.js step 287)
        window.activeRide = { item: item };
        const titleEl = document.getElementById('sheet-title');
        if (titleEl) titleEl.innerText = item.title;
        const priceEl = document.getElementById('sheet-price');
        if (priceEl && typeof formatCurrency === 'function') priceEl.innerText = formatCurrency(item.price);
        document.getElementById('item-sheet').classList.remove('translate-y-full');
    }
};

// Override getListings to INJECT view counts into ALL feeds (Explore, Browse, etc)
// This ensures renderBrowseFeed uses the correct views from storage.
const _originalGetListings = window.getListings;

window.getListings = function () {
    let items = [];
    if (_originalGetListings) {
        items = _originalGetListings();
    } else if (window.MOCK_DB && window.MOCK_DB.listings) {
        items = window.MOCK_DB.listings;
    }

    // Merge Views
    const views = getLocalViews();
    return items.map(item => {
        // Clone to avoid mutating original source too much if needed, or just mutate
        // Mutating is better for logic.js consistency
        if (views[item.id]) {
            item.views = views[item.id];
        } else {
            // If no local view, keep existing or default to 0
            if (!item.views) item.views = 0;
        }
        return item;
    });
};

// --- 13. ITEM REVIEWS ---

// Persistent Storage Helper
function getLocalReviews() {
    return JSON.parse(localStorage.getItem('ghadget_reviews') || '{}');
}

window.renderReviews = function (itemId) {
    const list = document.getElementById('reviews-list');
    if (!list) return;

    const allReviews = getLocalReviews();
    const itemReviews = allReviews[itemId] || [];

    if (itemReviews.length === 0) {
        list.innerHTML = '<div class="text-center text-gray-400 text-sm py-4">No reviews yet. Be the first!</div>';
        return;
    }

    list.innerHTML = itemReviews.map(r => `
        <div class="bg-gray-50 p-3 rounded-xl flex gap-3">
            <div class="w-8 h-8 rounded-full bg-gray-200 bg-cover bg-center shrink-0" style="background-image: url('${r.avatar || 'https://i.pravatar.cc/150?u=' + r.user}')"></div>
            <div>
                <h4 class="font-bold text-xs text-gray-900">${r.user} <span class="text-xs text-orange-500 ml-1">★ ${r.rating}</span></h4>
                <p class="text-xs text-gray-600 mt-1">${r.text}</p>
                <p class="text-[10px] text-gray-400 mt-1">${new Date(r.date).toLocaleDateString()}</p>
            </div>
        </div>
    `).join('');
};

window.setReviewRating = function (val) {
    document.getElementById('review-rating-val').value = val;
    // Update visuals
    const stars = document.getElementById('review-stars').children;
    for (let i = 0; i < stars.length; i++) {
        if (i < val) stars[i].classList.replace('text-gray-300', 'text-orange-400');
        else stars[i].classList.replace('text-orange-400', 'text-gray-300');
    }
};

window.submitReview = function () {
    const itemId = activeRide ? activeRide.item.id : null;
    if (!itemId) return;

    const text = document.getElementById('review-text').value.trim();
    const rating = document.getElementById('review-rating-val').value;

    if (!text) {
        alert("Please write a review.");
        return;
    }

    const newReview = {
        user: (currentUser && currentUser.username) ? currentUser.username : 'Guest User',
        avatar: (currentUser && currentUser.avatar) ? currentUser.avatar : null,
        text,
        rating,
        date: Date.now()
    };

    const allReviews = getLocalReviews();
    if (!allReviews[itemId]) allReviews[itemId] = [];
    allReviews[itemId].unshift(newReview); // Add to top

    localStorage.setItem('ghadget_reviews', JSON.stringify(allReviews));

    // Reset Form
    document.getElementById('review-text').value = '';
    document.getElementById('review-form').classList.add('hidden');

    // Re-render
    renderReviews(itemId);
    alert('Review posted!');
};

// Update existing modal opener to call renderReviews
const _superOpenItemSheet = window.openItemSheet;
window.openItemSheet = function (item) {
    if (_superOpenItemSheet) _superOpenItemSheet(item); // Increment views etc
    // Render Reviews
    if (item && item.id) {
        renderReviews(item.id);
    }
    // Also try to open the NEW product modal if it exists
    const newModal = document.getElementById('product-modal');
    if (newModal) {
        newModal.classList.remove('hidden');
        newModal.classList.add('flex');

        // Populate New Modal Fields
        setText('modal-title', item.title);
        // Safely check formatCurrency
        const priceTxt = (typeof formatCurrency === 'function') ? formatCurrency(item.price) : '₦' + item.price;
        setText('modal-price', priceTxt);
        setText('modal-desc', item.description || 'No description.');
        setText('modal-brand', item.brand || '-');
        setText('modal-cond', item.condition || '-');
        setText('modal-color', item.color || '-');
        setText('modal-swap', item.swap ? 'Yes' : 'No');

        // Seller
        setText('modal-seller-name', item.sellerName || 'Verified Seller');
        setText('modal-seller-rating', item.sellerRating || '4.8');
        const av = document.getElementById('modal-seller-avatar');
        if (av) av.style.backgroundImage = `url('${item.sellerAvatar || 'https://i.pravatar.cc/150'}')`;

        // Images for new modal
        const imgContainer = document.getElementById('modal-images');
        if (imgContainer) {
            imgContainer.innerHTML = '';
            const images = (item.images && item.images.length) ? item.images : [item.image || 'https://placehold.co/400'];
            images.forEach(src => {
                const d = document.createElement('div');
                d.className = 'w-full min-w-full h-full bg-cover bg-center shrink-0 snap-center';
                d.style.backgroundImage = `url('${src}')`;
                imgContainer.appendChild(d);
            });
        }
    }
};

// Close handler for the new modal
window.closeProductModal = function () {
    const m = document.getElementById('product-modal');
    if (m) {
        m.classList.add('hidden');
        m.classList.remove('flex');
    }
    // Also call legacy close if needed
    if (typeof closeSheet === 'function') closeSheet();
};

// Hook into view switch
const _oldSwitch = window.switchView;
window.switchView = function (id) {
    if (_oldSwitch) _oldSwitch(id);
    if (id === 'map') {
        setTimeout(forceInitMap, 200);
    }
};

// --- 14. MAP FORCE INIT (CRITICAL PRIORITY) ---
window.forceInitMap = function () {
    console.log("🚀 Force Init Map Triggered");
    const mapEl = document.getElementById('map');

    if (!mapEl) {
        console.error("Map container #map not found!");
        return;
    }

    if (typeof L === 'undefined') {
        console.warn("Leaflet not loaded yet, retrying...");
        setTimeout(forceInitMap, 500);
        return;
    }

    // 1. Destroy existing instance if any
    if (window.map && window.map.remove) {
        window.map.remove();
        window.map = null;
    }

    // 2. Clean container residue (except placeholder class)
    // We explicitly REMOVE the placeholder class now to ensure it doesn't cover tiles
    mapEl.classList.remove('map-placeholder');

    try {
        console.log("Creating new Map instance...");
        // 3. Initialize fresh
        window.map = L.map('map', {
            zoomControl: false,
            attributionControl: false,
            // Force a valid center (Abuja)
            center: [9.0765, 7.3986],
            zoom: 13,
            minZoom: 3,
            maxZoom: 19
        });

        // 4. Add Tiles (CartoDB Positron for cleaner look, or OSM standard)
        // Using Standard OSM for maximum reliability request
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '© OpenStreetMap'
        }).addTo(window.map);

        // 5. Force Resize after distinct tick to allow DOM to paint
        setTimeout(() => {
            window.map.invalidateSize();
            console.log("Map size invalidated.");
        }, 250);

        // 6. Re-render pins if data exists
        if (typeof renderPins === 'function') {
            setTimeout(renderPins, 500);
        }

    } catch (e) {
        console.error("CRITICAL: Map Init Failed", e);
        // Fallback: try simple alert to debug
        // alert("Map Error: " + e.message);
    }
};

// Initial Load Triggers
if (document.readyState === 'complete') {
    forceInitMap();
} else {
    window.addEventListener('load', forceInitMap);
}
// Double check
setTimeout(forceInitMap, 2000);

// --- FIX: Navigation Modal Close ---
window.closeNavOptions = function () {
    const m = document.getElementById('nav-options-modal');
    if (m) {
        m.classList.add('hidden');
        m.classList.remove('flex');
    }
};

// --- FIX: WhatsApp Chat System ---

// 1. Start Deal (Requested by user)
window.startDeal = function (itemOverride = null) {
    const item = itemOverride || (window.activeRide ? window.activeRide.item : null);

    if (!item) {
        alert("Error: No item selected.");
        return;
    }

    // 1. Construct Message
    const phone = (item.whatsapp || item.sellerPhone || "2348000000000").replace('+', '');
    const text = `Hi, I saw your listing *${item.title || 'Item'}* on GadgetGo. Is it still available?`;
    const url = `https://wa.me/${phone}?text=${encodeURIComponent(text)}`;

    // 2. Persist Deal History
    const history = JSON.parse(localStorage.getItem('ghadget_deals') || '[]');

    // Check duplication
    const existingIndex = history.findIndex(d => d.itemId === item.id);
    if (existingIndex > -1) {
        // Update timestamp if exists
        history[existingIndex].timestamp = Date.now();
    } else {
        // Add new
        history.unshift({
            id: 'deal_' + Date.now(),
            itemId: item.id,
            title: item.title,
            price: item.price,
            image: (item.images && item.images[0]) ? item.images[0] : (item.image || 'https://placehold.co/100'),
            sellerName: item.sellerName || 'Seller',
            sellerPhone: phone,
            timestamp: Date.now(),
            status: 'Contacted'
        });
    }

    localStorage.setItem('ghadget_deals', JSON.stringify(history));

    // 3. Open WhatsApp
    window.open(url, '_blank');
};

// 2. Render Messages List
window.renderMessages = function () {
    const container = document.getElementById('messages-list');
    if (!container) return;

    const history = JSON.parse(localStorage.getItem('ghadget_deals') || '[]');

    if (history.length === 0) {
        container.innerHTML = `
            <div class="flex flex-col items-center justify-center h-64 text-gray-400 p-8 space-y-4">
                 <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center">
                    <span class="material-symbols-outlined text-3xl text-gray-300">forum</span>
                 </div>
                 <div class="text-center">
                    <p class="font-bold text-gray-600 text-sm">No started deals yet</p>
                    <p class="text-xs max-w-[200px] mt-1">Tap <b>"Start Deal"</b> on any item to connect on WhatsApp.</p>
                 </div>
            </div>
        `;
        return;
    }

    container.innerHTML = '';
    history.forEach(deal => {
        const timeStr = new Date(deal.timestamp).toLocaleDateString();
        // WhatsApp Re-open Link
        const url = `https://wa.me/${deal.sellerPhone}`;

        container.innerHTML += `
            <div onclick="window.open('${url}', '_blank')" class="bg-white p-3 rounded-2xl shadow-sm border border-gray-100 flex items-center gap-3 cursor-pointer hover:bg-gray-50 active:scale-95 transition">
                <div class="relative w-12 h-12 rounded-full bg-gray-100 bg-cover bg-center shrink-0" style="background-image: url('${deal.image}')">
                    <div class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white rounded-full"></div>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="flex justify-between items-center mb-0.5">
                        <h4 class="font-bold text-gray-900 text-sm truncate pr-2">${deal.sellerName}</h4>
                        <span class="text-[10px] text-gray-400 font-bold">${timeStr}</span>
                    </div>
                    <p class="text-xs text-gray-500 truncate flex items-center gap-1">
                        <span class="material-symbols-outlined text-[12px] text-primary">reply</span> 
                        Re: ${deal.title}
                    </p>
                </div>
            </div>
        `;
    });
};

// Hook renderMessages into switchView
const _prevSwitch = window.switchView;
window.switchView = function (id) {
    if (_prevSwitch) _prevSwitch(id); // Calls previous overrides (like map fix)

    // 1. Reset All Nav Buttons
    document.querySelectorAll('#bottom-nav button').forEach(btn => {
        const icon = btn.querySelector('.material-symbols-outlined');
        const label = btn.querySelector('.nav-label');
        const indicator = btn.querySelector('#nav-indicator-map'); // Special case for Map pill

        // Reset styling to gray/inactive
        if (icon) {
            icon.className = "material-symbols-outlined text-gray-400 group-hover:text-primary transition text-[24px]";
            icon.style.color = ''; // Remove inline override
            icon.classList.remove('scale-110');
        }
        if (label) {
            label.className = "text-[10px] font-semibold text-gray-400 group-hover:text-primary nav-label";
            label.style.color = ''; // Remove inline override
        }

        // Remove pill background if it exists (for map)
        if (indicator) {
            indicator.className = "h-8 w-14 rounded-full flex items-center justify-center transition";
            indicator.style.backgroundColor = ''; // Remove inline override
            indicator.style.color = '';

            // Reset icon inside pill
            const pillIcon = indicator.querySelector('span');
            if (pillIcon) {
                pillIcon.className = "material-symbols-outlined text-gray-400 text-[24px]";
                pillIcon.style.color = ''; // Remove inline override
            }
        }
    });

    // 2. Set Active Button
    const activeBtn = document.getElementById('nav-btn-' + id);
    if (activeBtn) {
        const icon = activeBtn.querySelector('.material-symbols-outlined');
        const label = activeBtn.querySelector('.nav-label');
        const indicator = activeBtn.querySelector('#nav-indicator-map');

        // Map uses a pill indicator
        if (id === 'map' && indicator) {
            // Force SOLID BLUE pill
            indicator.className = ""; // Wipe classes first
            indicator.className = "h-8 w-14 rounded-full flex items-center justify-center shadow-md transition transform scale-105";
            indicator.style.backgroundColor = '#2563eb'; // Tailwind blue-600 active

            const pillIcon = indicator.querySelector('span');
            if (pillIcon) {
                pillIcon.style.color = '#ffffff'; // White icon
            }
            if (label) {
                label.style.color = '#2563eb';
                label.classList.add('font-bold');
            }
        } else {
            // Standard Icons
            if (icon) {
                // Force Icon Color
                icon.style.color = '#2563eb'; // Active Blue
                icon.classList.remove('text-gray-400', 'group-hover:text-primary');
                icon.classList.add('scale-110', 'text-blue-600');
            }
            if (label) {
                label.style.color = '#2563eb';
                label.classList.remove('text-gray-400');
                label.classList.add('font-bold');
            }
        }
    }

    if (id === 'messages') {
        renderMessages();
    }
};

// --- FIX: Product View Counts ---
window.incrementViewCount = function (itemId) {
    if (!itemId) return;

    // 1. Get current counts
    const views = JSON.parse(localStorage.getItem('ghadget_views') || '{}');

    // 2. Increment
    if (!views[itemId]) views[itemId] = 0;
    views[itemId] += 1;

    // 3. Save
    localStorage.setItem('ghadget_views', JSON.stringify(views));

    // 4. Update UI if open
    const displayEl = document.getElementById('sheet-views') || document.getElementById('modal-views');
    if (displayEl) {
        // Base random count + real user views
        // We'll mimic a base count from the item data if available, or random if not, then add ours
        const base = 120; // Simulated base
        displayEl.innerText = (base + views[itemId]) + ' views';
    }

    console.log(`View count for ${itemId}: ${views[itemId]}`);
    return views[itemId];
};

// Hook into openProductModal to trigger view count
const _prevOpenModal = window.openProductModal;
window.openProductModal = function (item) {
    if (_prevOpenModal) _prevOpenModal(item);
    if (item && item.id) {
        incrementViewCount(item.id);
    }
};

// Also hook into Item Sheet open (if different)
const _prevOpenSheet = window.openItemSheet;
window.openItemSheet = function (item) {
    if (_prevOpenSheet) _prevOpenSheet(item);
    if (item && item.id) {
        incrementViewCount(item.id);
    }
}

    // --- FORCE OVERRIDES (Anti-Overwrite Protection) ---
    (function protectOverrides() {
        console.log("Applying final function locks...");
        const funcs = ['renderPins', 'renderBrowseFeed', 'getListings', 'fetchListings'];
        funcs.forEach(f => {
            if (window[f]) {
                try {
                    Object.defineProperty(window, f, {
                        value: window[f],
                        writable: false, // Prevent overwriting
                        configurable: false
                    });
                    console.log(`Protected function: ${f}`);
                } catch (e) {
                    console.warn(`Failed to protect ${f}:`, e);
                }
            }
        });
    })();
