
// --- FINAL PATCH FOR DEAL FLOW ---

// Redefine openProductModal to ensure selectedProduct is set
window.openProductModal = function (itemOrId) {
    let item = itemOrId;
    if (typeof itemOrId === 'string' || typeof itemOrId === 'number') {
        const all = (window.SERVER_CACHE || []).concat(typeof MOCK_DB !== 'undefined' ? MOCK_DB.listings : []);
        item = all.find(i => i.id == itemOrId);
    }
    if (!item) return;

    // CRITICAL FIX: Set BOTH globals to ensure requestDeal finds it
    window.selectedProduct = item;
    if (!window.activeRide) window.activeRide = {};
    window.activeRide.item = item;

    // Populate Modal
    const title = document.getElementById('modal-title');
    const price = document.getElementById('modal-price');
    const desc = document.getElementById('modal-desc');
    const brand = document.getElementById('modal-brand');
    const color = document.getElementById('modal-color');
    const cond = document.getElementById('modal-cond');

    if (title) title.innerText = item.title || 'Item';
    if (price) price.innerText = (item.price) ? '₦' + item.price.toLocaleString() : 'Contact';
    if (desc) desc.innerText = item.description || 'No description.';
    if (brand) brand.innerText = item.brand || '-';
    if (color) color.innerText = item.color || '-';
    if (cond) cond.innerText = item.condition || '-';

    // Show Modal
    const modal = document.getElementById('product-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
};

// Redefine requestDeal to check both globals
window.requestDeal = function () {
    const item = (window.activeRide && window.activeRide.item) || window.selectedProduct;

    if (item) {
        // Use openChatOptions to show Bike/Keke/Car/Chat choices
        if (typeof openChatOptions === 'function') {
            openChatOptions(item.id);
        } else {
            console.error("openChatOptions missing");
            alert("Contact options not available.");
        }
        return;
    }

    // Fallback if no item selected
    if (typeof showMessage === 'function') {
        showMessage("Select Item", "Please select a product on the map first.", "info");
    } else {
        alert("Please select a product first.");
    }
};
