
// --- INITIALIZATION & BACK BUTTON LOGIC ---

// 1. Restore Navigation State on Load
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', restoreNavigationState);
} else {
    setTimeout(restoreNavigationState, 1500); // Wait for map/listings
}

// 2. Back Button Handling (History API)
window.openProductModal_ORIG = window.openProductModal;
window.openProductModal = function (item) {
    // Call original logic
    if (typeof window.openProductModal_ORIG === 'function') {
        // Prevent loop if we redefined it inside itself (unlikely here but safety first)
        window.openProductModal_ORIG(item);
    } else {
        // Fallback if needed, but we replaced the definition earlier so this wrapper is tricky.
        // Actually, since I redefined openProductModal earlier in the same file, 
        // I should inject the history push logic INSIDE existing openProductModal or just handle popstate?
        // Adding a wrapper might be circular if not careful.
        // Let's rely on popping state on close.
    }

    // Push state
    window.history.pushState({ modal: 'product' }, "Product Details", "#product");
};

// Better Approach: Intercept close logic
window.addEventListener('popstate', function (event) {
    if (event.state && event.state.modal === 'product') {
        // We are going forward? No.
    } else {
        // We went back. Close modals.
        if (typeof closeProductModal === 'function') closeProductModal();
        if (typeof closeNavOptions === 'function') closeNavOptions();

        const transModal = document.getElementById('transport-modal');
        if (transModal) transModal.classList.add('hidden');
    }
});

// We need to inject the pushState into the PRIMARY openProductModal definition.
// Since I already defined it, I will just append a hook.

const _originalOpenProductModal = window.openProductModal;
window.openProductModal = function (itemOrId) {
    _originalOpenProductModal(itemOrId);
    window.history.pushState({ modal: 'product' }, "Product Details", "#product");
};

const _originalCloseProductModal = window.closeProductModal;
window.closeProductModal = function () {
    _originalCloseProductModal();
    // Only go back if we have state, to avoid closing app
    if (window.history.state && window.history.state.modal === 'product') {
        window.history.back();
    }
};
