/* ==========================================================================
   CHAT & NAVIGATION ENHANCEMENT (Real Implementation V2)
   Fixes "Simulated" alerts, Navigation, Chat Visibility, and Styling.
   ========================================================================== */

console.log("🚀 Loading Chat & Nav Enhancements V2...");

// --- 1. Z-Index & Layout Fixes (Preloader/Footer) ---

document.addEventListener('DOMContentLoaded', () => {
    // Ensure Preloader is on TOP of everything (Fix footer showing through)
    const loader = document.getElementById('app-loader');
    if (loader) {
        loader.style.zIndex = '99999';
        loader.style.position = 'fixed';
    }

    // Ensure Map is initialized (Safety Check)
    setTimeout(() => {
        if (typeof L !== 'undefined' && !window.map && document.getElementById('map')) {
            console.log("🗺️ Initializing Map (Safety Fallback)...");
            window.map = L.map('map', { zoomControl: false, attributionControl: false }).setView([9.0765, 7.3986], 13);
            L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png').addTo(window.map);
        }
    }, 2000);
});


// --- 2. Navigation Logic ---

window.startInAppNav = function () {
    console.log("🚗 Starting Real In-App Navigation...");

    // Close modal
    const navModal = document.getElementById('nav-options-modal');
    if (navModal) navModal.classList.add('hidden');

    // Resolve Item
    const item = window.selectedItem || window.selectedProduct || (window.activeRide ? window.activeRide.item : null);

    if (!item) {
        alert("No destination selected. Please select an item first.");
        return;
    }

    // Ensure Location
    let dest = null;
    if (item.location) {
        dest = item.location;
    } else if (item.lat && item.lng) {
        dest = { lat: item.lat, lng: item.lng };
    }

    if (!dest) {
        alert("This item does not have a location set.");
        return;
    }

    window.navigationDestination = {
        lat: parseFloat(dest.lat),
        lng: parseFloat(dest.lng),
        address: dest.address || item.title || "Destination"
    };

    // Check Geoloc
    if (!navigator.geolocation) {
        alert("Geolocation is not supported by your browser.");
        return;
    }

    // Show Overlay
    const navOverlay = document.getElementById('nav-overlay');
    if (navOverlay) {
        navOverlay.classList.remove('hidden');
        navOverlay.style.display = 'flex';

        // Update helper text if element exists
        const destLabel = document.getElementById('nav-destination-label');
        if (destLabel) destLabel.textContent = `Navigating to: ${item.title}`;
    }

    // Trigger existing logic hooks
    if (typeof startNavigationSimulation === 'function') {
        startNavigationSimulation(window.navigationDestination);
    }

    console.log("✅ Navigation Started to:", window.navigationDestination);
};


// --- 3. Chat Logic (Real-time & UI Fixes) ---

// Store active chat context
window.activeChatContext = null;
let chatPollInterval = null;

// Override startInAppChat
window.startInAppChat = function () {
    console.log("💬 Starting Real Chat...");

    const choiceModal = document.getElementById('chat-choice-modal');
    if (choiceModal) choiceModal.remove();

    if (!window.currentUser) {
        window.showAuthModal('login');
        return;
    }

    const item = window.selectedProduct || window.selectedItem || (window.activeRide ? window.activeRide.item : null);

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

    openChat(item);
};

// Main Open Chat Function
window.openChat = async function (itemOrId) {
    let item = itemOrId;

    // Resolution
    if (typeof itemOrId === 'string') {
        const cached = (window.productsData || []).find(p => p.id === itemOrId);
        if (cached) item = cached;
        else item = { id: itemOrId, title: 'Item', price: 0, seller: 'Seller' };
    }

    window.activeChatContext = item;
    window.activeChatContext.msgCount = 0; // Reset count

    // UI Setup
    const view = document.getElementById('view-chat-detail');
    if (!view) return;

    // --- FIX: VISIBILITY & Z-INDEX ---
    view.style.zIndex = '500'; // Ensure above footer (z-100) and modals

    const footer = document.getElementById('bottom-nav');
    if (footer) footer.style.display = 'none'; // Hide footer completely

    const pModal = document.getElementById('product-modal');
    if (pModal) pModal.classList.add('hidden'); // Ensure product modal is gone

    // Populate Header
    const nameEl = document.getElementById('chat-name');
    if (nameEl) nameEl.innerHTML = `${item.seller || item.sellerName || 'Seller'} <span class="material-symbols-outlined text-[14px] text-gray-400">chevron_right</span>`;

    const titleEl = document.getElementById('chat-product-title');
    if (titleEl) titleEl.textContent = item.title;

    const priceEl = document.getElementById('chat-product-price');
    if (priceEl) priceEl.textContent = `₦${parseInt(item.price || 0).toLocaleString()}`;

    // Images
    const avatar = document.getElementById('chat-avatar');
    if (avatar) avatar.style.backgroundImage = `url('${item.sellerAvatar || 'https://ui-avatars.com/api/?name=Seller'}')`;

    const prodImg = document.getElementById('chat-product-img');
    if (prodImg) prodImg.style.backgroundImage = `url('${item.image || (item.images && item.images[0]) || ''}')`;

    // Show View
    view.classList.remove('hidden');
    view.style.display = 'flex';

    // Load & Poll
    if (chatPollInterval) clearInterval(chatPollInterval); // Clear old
    loadChatMessages(item.id);
    chatPollInterval = setInterval(() => loadChatMessages(item.id, true), 3000); // Poll every 3s
};

// Close Chat
window.closeChat = function () {
    const view = document.getElementById('view-chat-detail');
    if (view) {
        view.classList.add('hidden');
        view.style.display = 'none';
    }
    window.activeChatContext = null;
    if (chatPollInterval) clearInterval(chatPollInterval);

    // Restore Footer
    const footer = document.getElementById('bottom-nav');
    if (footer) footer.style.display = 'grid'; // Grid is default for nav
};

// Load Messages (Polling Support)
async function loadChatMessages(itemId, silent = false) {
    const container = document.getElementById('chat-messages');
    if (!container) return;

    if (!silent) container.innerHTML = '<div class="text-center py-4"><span class="material-symbols-outlined animate-spin">sync</span></div>';

    try {
        const res = await fetch(`../server/chat.php?action=load&itemId=${itemId}`);
        const data = await res.json();

        // Check if update needed
        if (silent && data.messages && data.messages.length === window.activeChatContext.msgCount) {
            return; // No new messages
        }

        if (!silent) container.innerHTML = '';

        // Add System/Safety Note (Only if non-silent redraw)
        if (!silent || (data.messages && data.messages.length > 0)) {
            // If polling and we have new messages, we redraw everything. 
            // Better to append, but simpler to redraw for exact sync.
            container.innerHTML = `
                <div class="text-center text-[10px] text-gray-400 font-bold uppercase tracking-widest my-4">Today</div>
                <div class="bg-yellow-50 p-3 rounded-lg border border-yellow-100 text-xs text-gray-600 text-center mx-4 mb-4">
                    <span class="font-bold block text-yellow-700 mb-1">Safety Tip</span>
                    Meet in a safe, public place. Do not pay in advance.
                </div>
            `;
        }

        if (data.success && data.messages && data.messages.length > 0) {
            // Update count
            window.activeChatContext.msgCount = data.messages.length;

            data.messages.forEach(msg => {
                appendMessageBubble(msg);
            });
            scrollToBottom();
        } else {
            if (!silent) container.innerHTML += `<div class="text-center text-gray-400 text-xs mt-4">Start the conversation!</div>`;
        }
    } catch (e) {
        console.error("Load Chat Error:", e);
        if (!silent) container.innerHTML = '<p class="text-center text-red-400 text-xs">Failed to load messages.</p>';
    }
}

// Append Bubble
function appendMessageBubble(msg) {
    const container = document.getElementById('chat-messages');
    if (!container) return;

    const isMe = msg.sender === window.currentUser.username || msg.sender === window.currentUser.email;

    const div = document.createElement('div');
    div.className = `flex ${isMe ? 'justify-end' : 'justify-start'} mb-2`;

    div.innerHTML = `
        <div class="max-w-[75%] ${isMe ? 'bg-primary text-white rounded-tr-none' : 'bg-white border border-gray-100 rounded-tl-none'} rounded-2xl px-4 py-2 shadow-sm">
            ${msg.replyTo ? `<div class="text-[10px] opacity-75 border-l-2 border-white/50 pl-1 mb-1">Replying...</div>` : ''}
            <p class="text-sm">${msg.text}</p>
            <span class="text-[10px] ${isMe ? 'text-blue-100' : 'text-gray-400'} block text-right mt-1">
                ${new Date(msg.timestamp * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </span>
        </div>
    `;
    container.appendChild(div);
}

// Send Message
window.sendMessage = async function () {
    const input = document.getElementById('chat-input');
    if (!input) return;

    const text = input.value.trim();
    if (!text || !window.activeChatContext) return;

    if (!window.currentUser) {
        window.showAuthModal('login');
        return;
    }

    // Optimistic UI
    const tempMsg = {
        id: 'temp_' + Date.now(),
        sender: window.currentUser.username,
        text: text,
        timestamp: Date.now() / 1000,
        receiver: window.activeChatContext.seller || 'Seller'
    };
    appendMessageBubble(tempMsg);
    scrollToBottom();
    input.value = '';

    // Send to Backend
    try {
        const res = await fetch('../server/chat.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                itemId: window.activeChatContext.id,
                sender: window.currentUser.username,
                receiver: window.activeChatContext.seller || window.activeChatContext.sellerName || 'Seller',
                text: text,
                timestamp: Date.now() / 1000
            })
        });
        const data = await res.json();
        // Force refresh to sync
        loadChatMessages(window.activeChatContext.id, true);
    } catch (e) {
        console.error("Send Network Error:", e);
    }
};

function scrollToBottom() {
    const container = document.getElementById('chat-messages');
    if (container) container.scrollTop = container.scrollHeight;
}

// Attach Event Listeners on Load
document.addEventListener('DOMContentLoaded', () => {
    const input = document.getElementById('chat-input');
    if (input) {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });

        const btn = input.nextElementSibling || input.parentElement.querySelector('button');
        if (btn) btn.onclick = sendMessage;
    }
});

// Re-attach fallback
setTimeout(() => {
    const input = document.getElementById('chat-input');
    if (input) {
        const btn = input.parentElement.querySelector('button');
        if (btn) btn.onclick = sendMessage;
    }
}, 1000);
