// LocationSelector - Versión simplificada sin códigos postales
class LocationSelector {
    constructor() {
        this.provinceSelect = document.getElementById('province_code');
        this.municipalitySelect = document.getElementById('municipality_code');
        
        if (!this.provinceSelect || !this.municipalitySelect) {
            return;
        }
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.loadProvinces();
    }
    
    async loadProvinces() {
        try {
            this.showLoading(this.provinceSelect, 'Cargando provincias...');
            
            const response = await fetch('/location/provinces');
            
            if (!response.ok) {
                throw new Error(`Error HTTP: ${response.status}`);
            }
            
            const data = await response.json();
            
            if (data.success && data.data) {
                this.populateSelect(this.provinceSelect, data.data, 'Selecciona una provincia');
                this.provinceSelect.disabled = false;
            } else {
                throw new Error(data.error || 'Error en formato de datos');
            }
        } catch (error) {
            this.showError(this.provinceSelect, 'Error de conexión');
            this.loadEmbeddedProvinces();
        }
    }
    
    loadEmbeddedProvinces() {
        const embeddedProvinces = [
            {code: '08', name: 'Barcelona'}, 
            {code: '28', name: 'Madrid'}, 
            {code: '46', name: 'Valencia'}, 
            {code: '41', name: 'Sevilla'},
            {code: '29', name: 'Málaga'}, 
            {code: '03', name: 'Alicante'},
            {code: '39', name: 'Cantabria'},
            {code: '48', name: 'Bizkaia'}
        ];
        this.populateSelect(this.provinceSelect, embeddedProvinces, 'Selecciona una provincia');
        this.provinceSelect.disabled = false;
    }
    
    async loadMunicipalities(provinceCode) {
        try {
            this.showLoading(this.municipalitySelect, 'Cargando municipios...');
            this.municipalitySelect.disabled = true;
            
            const response = await fetch(`/location/municipalities?province=${encodeURIComponent(provinceCode)}`);
            
            if (!response.ok) {
                throw new Error(`Error HTTP: ${response.status}`);
            }
            
            const data = await response.json();
            
            if (data.success && data.data) {
                this.populateSelect(this.municipalitySelect, data.data, 'Selecciona un municipio');
                this.municipalitySelect.disabled = false;
            } else {
                throw new Error(data.error || 'Error en formato de datos');
            }
        } catch (error) {
            this.showError(this.municipalitySelect, 'Error cargando municipios');
        }
    }
    
    populateSelect(select, data, placeholder, valueField = 'code') {
        this.clearSelect(select);
        
        const placeholderOption = new Option(placeholder, '');
        placeholderOption.disabled = true;
        placeholderOption.selected = true;
        select.add(placeholderOption);
        
        if (data && data.length > 0) {
            data.forEach(item => {
                const displayName = item.name || item.code;
                const value = item[valueField];
                const option = new Option(displayName, value);
                select.add(option);
            });
        }
    }
    
    clearSelect(select) {
        select.innerHTML = '';
    }
    
    showLoading(select, message) {
        this.clearSelect(select);
        const option = new Option(message, '');
        option.disabled = true;
        option.selected = true;
        select.add(option);
        select.disabled = true;
    }
    
    showError(select, message) {
        this.clearSelect(select);
        const option = new Option(message, '');
        option.disabled = true;
        option.selected = true;
        option.style.color = '#ef4444';
        select.add(option);
        select.disabled = false;
    }
    
    setupEventListeners() {
        this.provinceSelect.addEventListener('change', (e) => {
            const provinceCode = e.target.value;
            
            if (provinceCode) {
                this.loadMunicipalities(provinceCode);
            } else {
                this.municipalitySelect.disabled = true;
                this.clearSelect(this.municipalitySelect);
            }
        });
    }
}

// Inicializar
document.addEventListener('DOMContentLoaded', function() {
    new LocationSelector();
});