document.addEventListener("DOMContentLoaded", () => {
    const waitForAppToLoad = setInterval(() => {
        if (typeof App !== 'undefined' && App.map && App.data && App.data.allMarkers) {
            clearInterval(waitForAppToLoad);
            initializeStoreSearch();
        }
    }, 200); 
    
    setTimeout(() => clearInterval(waitForAppToLoad), 10000);
});

function initializeStoreSearch() {
    const searchInput = document.getElementById('store-code-input');
    const searchBtn = document.getElementById('store-search-btn');
    const dropdown = document.getElementById('search-results-dropdown');

    if (!searchInput || !searchBtn || !dropdown) return;

    // --- توابع کمکی (Utilities) ---

    const debounce = (func, delay) => {
        let timeoutId;
        return (...args) => {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => func.apply(this, args), delay);
        };
    };

    const safeOpenPopup = (marker) => {
        App.map.once('moveend', () => {
            marker.openPopup();
        });
    };

    // --- منطق اصلی نقشه ---

    const flyToMarker = (marker) => {
        const targetZoom = 18;
        const isClustering = App.state && App.state.isClustering;
        const brandCluster = App.layerGroups.clusters && App.layerGroups.clusters['dailymarket'];

        if (isClustering && brandCluster && brandCluster.hasLayer(marker)) {
            brandCluster.zoomToShowLayer(marker, () => {
                // اطمینان از زوم نهایی روی عدد 18
                App.map.flyTo(marker.getLatLng(), targetZoom, { animate: true, duration: 1 });
                safeOpenPopup(marker);
            });
        } else {
            App.map.flyTo(marker.getLatLng(), targetZoom, { animate: true, duration: 1.5 });
            safeOpenPopup(marker);
        }
    };

    // --- منطق جستجو و رابط کاربری ---

    const performSearch = () => {
        const query = searchInput.value.trim().toLowerCase();
        
        if (!query) {
            dropdown.style.display = 'none';
            searchInput.style.borderColor = '#ccc';
            return;
        }

        searchInput.style.borderColor = '#2E7D32';

        const matches = App.data.allMarkers.filter(marker => {
            const d = marker.storeData;
            if (!d || d.brand !== 'dailymarket') return false;
            
            const code = (d.store_code || '').toLowerCase();
            const name = (d.store_name || '').toLowerCase();
            
            return code.includes(query) || name.includes(query);
        }).slice(0, 15);

        dropdown.innerHTML = '';
        
        if (matches.length === 0) {
            const emptyLi = document.createElement('li');
            emptyLi.className = 'sr-empty';
            emptyLi.textContent = 'فروشگاهی یافت نشد';
            dropdown.appendChild(emptyLi);
        } else {
            // استفاده از DocumentFragment برای پرفورمنس بهتر در دستکاری DOM
            const fragment = document.createDocumentFragment();
            
            matches.forEach(marker => {
                const d = marker.storeData;
                const li = document.createElement('li');
                
                const spanCode = document.createElement('span');
                spanCode.className = 'sr-code';
                spanCode.textContent = `کد: ${d.store_code || 'ندارد'}`;
                
                const spanName = document.createElement('span');
                spanName.className = 'sr-name';
                spanName.textContent = d.store_name || 'نامشخص';
                
                li.appendChild(spanCode);
                li.appendChild(spanName);
                
                li.addEventListener('click', () => {
                    searchInput.value = d.store_code; 
                    dropdown.style.display = 'none'; 
                    flyToMarker(marker);             
                });
                
                fragment.appendChild(li);
            });
            
            dropdown.appendChild(fragment);
        }
        
        dropdown.style.display = 'block';
    };

    searchInput.addEventListener('input', debounce(performSearch, 250));

    const performExactSearch = () => {
        const query = searchInput.value.trim();
        if (!query) return;

        const targetMarker = App.data.allMarkers.find(m => {
            if (m.storeData.brand !== 'dailymarket') return false;
            return m.storeData.store_code === query || m.storeData.store_name === query;
        });

        if (targetMarker) {
            dropdown.style.display = 'none';
            searchInput.value = targetMarker.storeData.store_code; 
            flyToMarker(targetMarker);
        } else {
            searchInput.style.borderColor = 'red';
            dropdown.innerHTML = '';
            const errLi = document.createElement('li');
            errLi.className = 'sr-empty';
            errLi.style.color = 'red';
            errLi.textContent = 'موردی با این مشخصات دقیق یافت نشد';
            dropdown.appendChild(errLi);
            dropdown.style.display = 'block';
        }
    };

    searchBtn.addEventListener('click', performExactSearch);

    searchInput.addEventListener('keypress', (event) => {
        if (event.key === 'Enter') {
            event.preventDefault();
            const firstResult = dropdown.querySelector('li:not(.sr-empty)');
            if (dropdown.style.display === 'block' && firstResult) {
                firstResult.click();
            } else {
                performExactSearch();
            }
        }
    });

    document.addEventListener('click', (event) => {
        if (!event.target.closest('#store-search-wrapper')) {
            dropdown.style.display = 'none';
            searchInput.style.borderColor = '#ccc';
        }
    });
}
