const StoreSearch = {
    init() {
        this.input = document.getElementById('store-code-input');
        this.btn = document.getElementById('store-search-btn');
        this.dropdown = document.getElementById('search-results-dropdown');

        if (!this.input || !this.btn || !this.dropdown) return;

        this.bindEvents();
    },

    bindEvents() {
        this.input.addEventListener('input', this.debounce(() => this.performSearch(), 250));
        this.btn.addEventListener('click', (e) => this.performExactSearch(e));
        
        this.input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                const firstResult = this.dropdown.querySelector('li:not(.sr-empty)');
                if (this.dropdown.style.display === 'block' && firstResult) firstResult.click();
                else this.performExactSearch(e);
            }
        });

        document.addEventListener('click', (e) => {
            if (!e.target.closest('#store-search-wrapper')) this.closeDropdown();
        });
    },

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

    closeDropdown() {
        this.dropdown.style.display = 'none';
        this.input.style.borderColor = '#ccc';
    },

    flyToStore(item) {
        // ایجاد و نمایش فوری پین قبل از شروع حرکت
        if (typeof App._addStoreMarker === 'function') {
            App._addStoreMarker(item);
        }

        App.map.flyTo({
            center: [item.lng, item.lat],
            zoom: 18,
            speed: 1.2,
            essential: true
        });

        App.map.once('moveend', () => {
            setTimeout(() => {
                if (typeof App._showStorePopup === 'function') {
                    App._showStorePopup(item);
                }
            }, 500);
        });
    },

    performSearch() {
        const query = this.input.value.trim().toLowerCase();
        
        if (!query) return this.closeDropdown();

        this.input.style.borderColor = '#2E7D32';

        const matches = App.data.allItems.filter(item => {
            const d = item.storeData;
            return d?.brand === 'dailymarket' && 
                   ((d.store_code || '').toLowerCase().includes(query) || 
                    (d.store_name || '').toLowerCase().includes(query));
        }).slice(0, 15);

        this.renderResults(matches);
    },

    performExactSearch(event) {
        if (event) event.stopPropagation();
        
        const query = this.input.value.trim().toLowerCase();
        if (!query) return;

        const targetItem = App.data.allItems.find(item => {
            const d = item.storeData;
            return d?.brand === 'dailymarket' && 
                   ((d.store_code || '').toLowerCase() === query || 
                    (d.store_name || '').toLowerCase() === query);
        });

        if (targetItem) {
            this.dropdown.style.display = 'none';
            this.input.value = targetItem.storeData.store_code || targetItem.storeData.store_name;
            this.flyToStore(targetItem);
        } else {
            this.input.style.borderColor = 'red';
            this.renderEmpty('موردی با این مشخصات دقیق یافت نشد', 'red');
        }
    },

    renderResults(matches) {
        this.dropdown.innerHTML = '';
        
        if (matches.length === 0) {
            this.renderEmpty('فروشگاهی یافت نشد');
            return;
        }

        const fragment = document.createDocumentFragment();
        
        matches.forEach(item => {
            const d = item.storeData;
            const li = document.createElement('li');
            
            li.innerHTML = `
                <span class="sr-code">کد: ${d.store_code || 'ندارد'}</span>
                <span class="sr-name" style="margin-right: 8px;">${d.store_name || 'نامشخص'}</span>
            `;
            
            li.addEventListener('click', (e) => {
                e.stopPropagation();
                this.input.value = d.store_code || d.store_name;
                this.dropdown.style.display = 'none';
                this.flyToStore(item);
            });
            
            fragment.appendChild(li);
        });
        
        this.dropdown.appendChild(fragment);
        this.dropdown.style.display = 'block';
    },

    renderEmpty(msg, color = 'inherit') {
        this.dropdown.innerHTML = `<li class="sr-empty" style="color: ${color};">${msg}</li>`;
        this.dropdown.style.display = 'block';
    }
};

document.addEventListener("DOMContentLoaded", () => {
    const waitForApp = setInterval(() => {
        if (typeof App !== 'undefined' && App._mapLoaded && App.data?.allItems?.length > 0) {
            clearInterval(waitForApp);
            StoreSearch.init();
        }
    }, 250); 
    
    setTimeout(() => clearInterval(waitForApp), 15000);
});
