/**
 * Boundary Display Handler for Main Page
 * 
 * This script adds functionality to display geographical boundaries on the map
 * when a region is selected from the dropdown menus on the main page.
 */

// Wait for the document to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    // Wait a moment for the map to be fully initialized
    setTimeout(() => {
        // Initialize boundary display when the map is ready
        if (window.map) {
            initializeBoundaryDisplay();
        } else {
            console.warn('Map not initialized, boundary display is disabled');
        }
    }, 1000);
});

function initializeBoundaryDisplay() {
    // Store the main map reference
    const map = window.map;
    
    if (!map) {
        console.warn('Map not available, cannot initialize boundary display');
        return;
    }
    
    // Add a layer for the boundary
    let boundaryLayer = null;
    
    // Currently displayed region
    let currentRegion = {
        type: null,
        id: null
    };
    
    // Region type selects
    const selects = {
        country: document.getElementById('country-select'),
        province: document.getElementById('province-select'),
        county: document.getElementById('county-select'),
        district: document.getElementById('district-select'),
        city: document.getElementById('city-select'),
        village: document.getElementById('village-select'),
        zone: document.getElementById('zone-select')
    };
    
    // Add event listeners to all selects
    Object.entries(selects).forEach(([type, select]) => {
        if (select) {
            select.addEventListener('change', function() {
                const regionId = this.value;
                handleSelectChange(type, regionId);
            });
        }
    });
    
    function handleSelectChange(regionType, regionId) {
        console.log(`Region selection changed: ${regionType} = ${regionId}`);
        
        if (regionId) {
            // Update the current region information
            currentRegion = {
                type: regionType,
                id: regionId
            };
            
            // Fetch and display the boundary
            fetchAndDisplayBoundary(regionType, regionId);
        } else if (regionType === currentRegion.type) {
            // If the region that was cleared was the currently displayed one
            clearBoundary();
            
            // Find the highest level region that is still selected
            const regionTypes = ['zone', 'village', 'city', 'district', 'county', 'province', 'country'];
            for (const type of regionTypes) {
                if (selects[type] && selects[type].value) {
                    currentRegion = {
                        type: type,
                        id: selects[type].value
                    };
                    fetchAndDisplayBoundary(type, selects[type].value);
                    break;
                }
            }
        }
    }
    
    function fetchAndDisplayBoundary(regionType, regionId) {
        if (!map) {
            console.warn('Map not available, cannot display boundary');
            return;
        }
        
        clearBoundary();
        
        // Fetch boundary data from API
        fetch(`/api/boundaries/${regionType}/${regionId}`)
            .then(response => {
                if (!response.ok) {
                    console.warn(`Failed to fetch boundary data for ${regionType} ID: ${regionId} - Status: ${response.status}`);
                    return null;
                }
                return response.json();
            })
            .then(data => {
                if (!data) return;
                
                if (!data.boundaries) {
                    console.info(`No boundary data available for ${regionType} ID: ${regionId} - This is normal for some regions`);
                    return;
                }
                
                // Parse the GeoJSON from the boundaries column
                let geoJSON;
                try {
                    // If boundaries is already a GeoJSON object, use it directly
                    if (typeof data.boundaries === 'object') {
                        geoJSON = data.boundaries;
                    } else {
                        // Otherwise, try to parse it from a string
                        geoJSON = JSON.parse(data.boundaries);
                    }
                    
                    if (!geoJSON || (Array.isArray(geoJSON) && geoJSON.length === 0)) {
                        console.info(`Empty GeoJSON data for ${regionType} ID: ${regionId}`);
                        return;
                    }
                } catch (error) {
                    console.warn(`Failed to parse GeoJSON data for ${regionType} ID: ${regionId}: ${error.message}`);
                    return;
                }
                
                // Create a GeoJSON layer with the boundary data
                boundaryLayer = L.geoJSON(geoJSON, {
                    style: {
                        color: '#ff0000',     // Red border
                        weight: 2,            // Border width
                        opacity: 0.8,         // Opacity of border
                        fillColor: '#ff0000', // Fill color
                        fillOpacity: 0.1      // Fill opacity
                    }
                }).addTo(map);
                
                // Fit the map to the boundary bounds
                map.fitBounds(boundaryLayer.getBounds());
            })
            .catch(error => {
                console.warn(`Error displaying boundary for ${regionType} ID: ${regionId}: ${error.message}`);
            });
    }
    
    function clearBoundary() {
        if (map && boundaryLayer) {
            map.removeLayer(boundaryLayer);
            boundaryLayer = null;
        }
    }
} 