/**
 * Advanced Filters JavaScript Module
 * Enhanced dynamic filtering system for location search
 */

class AdvancedFiltersModule {
    constructor() {
        this.filters = {
            category: 'all',
            rating: '',
            status: '',
            distance: 50,
            country: '',
            province: '',
            city: ''
        };

        this.locationCounts = {};
        this.isLoading = false;
        this.debounceTimer = null;
        this.apiEndpoints = {
            provinces: '/api/provinces-by-country',
            cities: '/api/cities-by-province',
            filterCounts: '/api/filter-counts'
        };

        this.init();
    }

    init() {
        this.setupEventListeners();
        this.setupGeographicFilters();
        this.setupDistancePresets();
        this.setupSubcategoryToggle();
        this.loadInitialCounts();
        this.initializeAnimations();
    }

    setupEventListeners() {
        // Category filter listeners
        document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
            input.addEventListener('change', (e) => {
                this.filters.category = e.target.value;
                this.updateActiveCategory(e.target.value);
                this.toggleSubcategories(e.target.value);
                this.debounceApplyFilters();
            });
        });

        // Rating filter
        const ratingFilter = document.getElementById('rating-filter');
        if (ratingFilter) {
            ratingFilter.addEventListener('change', (e) => {
                this.filters.rating = e.target.value;
                this.updateRatingStats(e.target.value);
                this.debounceApplyFilters();
            });
        }

        // Status filter
        document.querySelectorAll('input[name="statusFilter"]').forEach(input => {
            input.addEventListener('change', (e) => {
                this.filters.status = e.target.value;
                this.updateStatusStats(e.target.value);
                this.debounceApplyFilters();
            });
        });

        // Distance filter
        const distanceFilter = document.getElementById('distance-filter-range');
        if (distanceFilter) {
            distanceFilter.addEventListener('input', (e) => {
                this.filters.distance = parseInt(e.target.value);
                this.updateDistanceDisplay(this.filters.distance);
                this.debounceApplyFilters();
            });
        }

        // Apply and clear buttons
        const applyBtn = document.getElementById('apply-filters');
        if (applyBtn) {
            applyBtn.addEventListener('click', () => {
                this.applyFilters();
            });
        }

        const clearBtn = document.getElementById('clear-filters');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                this.clearAllFilters();
            });
        }
    }

    setupGeographicFilters() {
        // Country filter
        const countryFilter = document.getElementById('dynamic-country-filter');
        if (countryFilter) {
            countryFilter.addEventListener('change', (e) => {
                this.filters.country = e.target.value;
                this.loadProvinces(e.target.value);
                this.resetSubsequentFilters(['province', 'city']);
                this.debounceApplyFilters();
            });
        }

        // Province filter
        const provinceFilter = document.getElementById('dynamic-province-filter');
        if (provinceFilter) {
            provinceFilter.addEventListener('change', (e) => {
                this.filters.province = e.target.value;
                this.loadCities(e.target.value);
                this.resetSubsequentFilters(['city']);
                this.debounceApplyFilters();
            });
        }

        // City filter
        const cityFilter = document.getElementById('dynamic-city-filter');
        if (cityFilter) {
            cityFilter.addEventListener('change', (e) => {
                this.filters.city = e.target.value;
                this.debounceApplyFilters();
            });
        }
    }

    setupDistancePresets() {
        document.querySelectorAll('.distance-preset').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const distance = parseInt(e.target.dataset.distance);
                this.setDistance(distance);
                this.updateDistancePresetButtons(distance);
            });
        });
    }

    setupSubcategoryToggle() {
        document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
            const categoryId = input.value;
            const subcategoryContainer = document.getElementById(`subcats-${categoryId}`);

            if (subcategoryContainer) {
                input.addEventListener('change', (e) => {
                    if (e.target.checked) {
                        this.showSubcategories(categoryId);
                    }
                });
            }
        });
    }

    async loadProvinces(countryId) {
        if (!countryId) {
            this.hideContainer('province-filter-container');
            this.hideContainer('city-filter-container');
            return;
        }

        try {
            this.showLoadingInSelect('dynamic-province-filter');
            const response = await fetch(`${this.apiEndpoints.provinces}/${countryId}`);
            const data = await response.json();

            if (data.success) {
                this.populateSelect('dynamic-province-filter', data.data, 'name', 'id');
                this.showContainer('province-filter-container');
            } else {
                console.error('Failed to load provinces:', data.message);
            }
        } catch (error) {
            console.error('Error loading provinces:', error);
        } finally {
            this.hideLoadingInSelect('dynamic-province-filter');
        }
    }

    async loadCities(provinceId) {
        if (!provinceId) {
            this.hideContainer('city-filter-container');
            return;
        }

        try {
            this.showLoadingInSelect('dynamic-city-filter');
            const response = await fetch(`${this.apiEndpoints.cities}/${provinceId}`);
            const data = await response.json();

            if (data.success) {
                this.populateSelect('dynamic-city-filter', data.data, 'name', 'id');
                this.showContainer('city-filter-container');
            } else {
                console.error('Failed to load cities:', data.message);
            }
        } catch (error) {
            console.error('Error loading cities:', error);
        } finally {
            this.hideLoadingInSelect('dynamic-city-filter');
        }
    }

    async loadInitialCounts() {
        try {
            const response = await fetch(this.apiEndpoints.filterCounts);
            const data = await response.json();

            if (data.success) {
                this.locationCounts = data.counts;
                this.updateAllCounts();
            }
        } catch (error) {
            console.error('Error loading initial counts:', error);
            this.loadFallbackCounts();
        }
    }

    loadFallbackCounts() {
        this.locationCounts = {
            all: 156,
            1: 45,  // Hotels
            2: 67,  // Restaurants
            3: 23,  // Attractions
            4: 12,  // Shopping
            5: 9    // Services
        };
        this.updateAllCounts();
    }

    updateAllCounts() {
        Object.keys(this.locationCounts).forEach(category => {
            this.updateCountDisplay(category, this.locationCounts[category]);
        });
    }

    updateCountDisplay(category, count) {
        const countElement = document.getElementById(`count-${category}`);
        if (countElement) {
            const countText = countElement.querySelector('.count-text');
            if (countText) {
                countText.textContent = count;
            } else {
                countElement.textContent = count;
            }

            // Animate count change
            countElement.style.transform = 'scale(1.2)';
            setTimeout(() => {
                countElement.style.transform = 'scale(1)';
            }, 200);
        }
    }

    updateDistanceDisplay(distance) {
        const distanceDisplay = document.getElementById('distance-display');
        if (distanceDisplay) {
            distanceDisplay.textContent = `${distance} کیلومتر`;
        }
    }

    updateDistancePresetButtons(selectedDistance) {
        document.querySelectorAll('.distance-preset').forEach(btn => {
            const btnDistance = parseInt(btn.dataset.distance);
            if (btnDistance === selectedDistance) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
    }

    updateActiveFiltersCount() {
        const activeCount = Object.values(this.filters).filter(value =>
            value !== '' && value !== 'all' && value !== 50
        ).length;

        const countElement = document.getElementById('active-filters-count');
        if (countElement) {
            countElement.textContent = activeCount;
            countElement.className = activeCount > 0 ? 'badge bg-warning text-dark ms-auto' : 'badge bg-light text-dark ms-auto';
        }

        this.updateFilterSummary();
    }

    updateFilterSummary() {
        const summaryElement = document.getElementById('active-filters-summary');
        if (summaryElement) {
            const activeFilters = [];

            if (this.filters.category !== 'all') {
                const categoryLabel = document.querySelector(`input[value="${this.filters.category}"]`)?.nextElementSibling?.textContent || this.filters.category;
                activeFilters.push(categoryLabel);
            }

            if (this.filters.rating) {
                activeFilters.push(`${this.filters.rating}+ ستاره`);
            }

            if (this.filters.status) {
                activeFilters.push(this.filters.status === 'open' ? 'باز' : 'بسته');
            }

            if (this.filters.distance !== 50) {
                activeFilters.push(`${this.filters.distance} کیلومتر`);
            }

            summaryElement.textContent = activeFilters.length > 0 ? activeFilters.join(', ') : 'هیچ';
        }
    }

    debounceApplyFilters() {
        if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
        }

        this.debounceTimer = setTimeout(() => {
            this.applyFilters();
        }, 300);
    }

    applyFilters() {
        this.showLoadingState(true);
        this.updateActiveFiltersCount();

        // Apply filters to map and location list
        if (window.mapController && window.mapController.applyFilters) {
            window.mapController.applyFilters(this.filters);
        }

        // Update location counts
        this.updateLocationCounts();

        setTimeout(() => {
            this.showLoadingState(false);
            this.showFilterFeedback('فیلترها اعمال شد', 'success');
        }, 500);

        this.trackFilterUsage();
    }

    // Animation initialization
    initializeAnimations() {
        // Initialize smooth transitions for filter panels
        const filterPanels = document.querySelectorAll('.filter-panel, .advanced-filter-section');
        filterPanels.forEach(panel => {
            panel.style.transition = 'all 0.3s ease-in-out';
        });

        // Initialize count animations
        const countElements = document.querySelectorAll('[id^="count-"]');
        countElements.forEach(element => {
            element.style.transition = 'transform 0.2s ease-in-out';
        });

        console.log('Filter animations initialized');
    }

    // Missing utility methods
    updateActiveCategory(categoryValue) {
        document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
            const label = input.nextElementSibling;
            if (label) {
                if (input.value === categoryValue) {
                    label.classList.add('active');
                } else {
                    label.classList.remove('active');
                }
            }
        });
    }

    toggleSubcategories(categoryValue) {
        // Hide all subcategory containers first
        document.querySelectorAll('[id^="subcats-"]').forEach(container => {
            container.style.display = 'none';
        });

        // Show the selected category's subcategories
        if (categoryValue !== 'all') {
            const subcategoryContainer = document.getElementById(`subcats-${categoryValue}`);
            if (subcategoryContainer) {
                subcategoryContainer.style.display = 'block';
            }
        }
    }

    updateRatingStats(rating) {
        const ratingDisplay = document.getElementById('rating-display');
        if (ratingDisplay) {
            ratingDisplay.textContent = rating ? `${rating}+ ستاره` : 'همه';
        }
    }

    updateStatusStats(status) {
        const statusDisplay = document.getElementById('status-display');
        if (statusDisplay) {
            statusDisplay.textContent = status === 'open' ? 'باز' : status === 'closed' ? 'بسته' : 'همه';
        }
    }

    setDistance(distance) {
        this.filters.distance = distance;
        const distanceSlider = document.getElementById('distance-filter-range');
        if (distanceSlider) {
            distanceSlider.value = distance;
        }
        this.updateDistanceDisplay(distance);
    }

    showSubcategories(categoryId) {
        const container = document.getElementById(`subcats-${categoryId}`);
        if (container) {
            container.style.display = 'block';
            container.style.opacity = '0';
            setTimeout(() => {
                container.style.opacity = '1';
            }, 10);
        }
    }

    resetSubsequentFilters(filterTypes) {
        filterTypes.forEach(type => {
            this.filters[type] = '';
            const element = document.getElementById(`dynamic-${type}-filter`);
            if (element) {
                element.value = '';
            }
        });
    }

    showLoadingInSelect(selectId) {
        const select = document.getElementById(selectId);
        if (select) {
            select.innerHTML = '<option>در حال بارگذاری...</option>';
            select.disabled = true;
        }
    }

    hideLoadingInSelect(selectId) {
        const select = document.getElementById(selectId);
        if (select) {
            select.disabled = false;
        }
    }

    populateSelect(selectId, data, textField, valueField) {
        const select = document.getElementById(selectId);
        if (select && data) {
            select.innerHTML = '<option value="">انتخاب کنید</option>';
            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item[valueField];
                option.textContent = item[textField];
                select.appendChild(option);
            });
        }
    }

    showContainer(containerId) {
        const container = document.getElementById(containerId);
        if (container) {
            container.style.display = 'block';
        }
    }

    hideContainer(containerId) {
        const container = document.getElementById(containerId);
        if (container) {
            container.style.display = 'none';
        }
    }

    showLoadingState(show) {
        const loadingElements = document.querySelectorAll('.filter-loading');
        loadingElements.forEach(element => {
            element.style.display = show ? 'block' : 'none';
        });
    }

    showFilterFeedback(message, type) {
        // Create or update feedback element
        let feedback = document.getElementById('filter-feedback');
        if (!feedback) {
            feedback = document.createElement('div');
            feedback.id = 'filter-feedback';
            feedback.className = 'alert alert-dismissible fade show position-fixed';
            feedback.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 250px;';
            document.body.appendChild(feedback);
        }

        feedback.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        feedback.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        // Auto hide after 3 seconds
        setTimeout(() => {
            if (feedback && feedback.parentNode) {
                feedback.remove();
            }
        }, 3000);
    }

    updateLocationCounts() {
        // This would typically make an API call to get updated counts
        // For now, we'll just update the display with current counts
        this.updateAllCounts();
    }

    trackFilterUsage() {
        // Track filter usage for analytics
        const activeFilters = Object.keys(this.filters).filter(key =>
            this.filters[key] !== '' && this.filters[key] !== 'all' && this.filters[key] !== 50
        );

        console.log('Filter usage tracked:', activeFilters);
    }

    clearAllFilters() {
        // Reset all filters to default values
        this.filters = {
            category: 'all',
            rating: '',
            status: '',
            distance: 50,
            country: '',
            province: '',
            city: ''
        };

        // Reset all form elements
        document.querySelectorAll('input[name="categoryFilter"]').forEach(input => {
            input.checked = input.value === 'all';
        });

        const ratingFilter = document.getElementById('rating-filter');
        if (ratingFilter) ratingFilter.value = '';

        document.querySelectorAll('input[name="statusFilter"]').forEach(input => {
            input.checked = false;
        });

        const distanceSlider = document.getElementById('distance-filter-range');
        if (distanceSlider) distanceSlider.value = 50;

        // Reset geographic filters
        ['dynamic-country-filter', 'dynamic-province-filter', 'dynamic-city-filter'].forEach(id => {
            const element = document.getElementById(id);
            if (element) element.value = '';
        });

        // Hide dependent containers
        this.hideContainer('province-filter-container');
        this.hideContainer('city-filter-container');

        // Update displays
        this.updateDistanceDisplay(50);
        this.updateActiveFiltersCount();
        this.applyFilters();

        this.showFilterFeedback('تمام فیلترها پاک شد', 'info');
    }
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    if (typeof window.advancedFilters === 'undefined') {
        window.advancedFilters = new AdvancedFiltersModule();
    }
});
