/**
 * CLAWS Maps Module
 * Handles Leaflet map initialization, markers, and map-related functionality
 */

(function() {
    'use strict';

    // Extend CLAWSApp with maps functionality
    Object.assign(window.CLAWSApp, {

        /**
         * Initialize the Leaflet map
         */
        initializeMap: function() {
            const mapElement = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_MAP);
            if (!mapElement || this.colonyMap) {
                return; // Already initialized or element not found
            }
            
            try {
                // Use custom default coordinates from settings, fallback to US center
                const defaultLat = this.config.defaultLatitude || 39.8283;
                const defaultLng = this.config.defaultLongitude || -98.5795;
                const defaultCenter = [defaultLat, defaultLng];
                
                this.colonyMap = L.map('claws-colony-map').setView(defaultCenter, 14);
                
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors',
                    maxZoom: 18
                }).addTo(this.colonyMap);

                
                // Update markers with current colony data
                this.updateMapMarkers();
                
            } catch (error) {
                mapElement.innerHTML = '<div style="height: 100%; display: flex; align-items: center; justify-content: center; color: #ef4444;"><p>Map failed to load. Please refresh the page.</p></div>';
            }
        },

        /**
         * Check if user can view a specific colony
         */
        canViewColony: function(colony) {
            // Get user roles safely
            const userRoles = clawsData.userRoles || [];
            const userId = clawsData.userId || null;
            
            // Subscribers see NO colony data
            if (userRoles.includes('subscriber') &&
                !userRoles.includes('contributor') &&
                !userRoles.includes('author') &&
                !userRoles.includes('administrator')) {
                return false;
            }
            
            // Authors, editors, and admins see ALL colonies
            if (userRoles.includes('author') || 
                userRoles.includes('editor') || 
                userRoles.includes('administrator')) {
                return true;
            }
            
            // Contributors see only colonies they created
            if (userRoles.includes('contributor')) {
                // Check various author ID fields that might be present
                const colonyAuthor = colony._debug?.postAuthor || 
                                   colony._debug?.authorId || 
                                   colony.author_id || 
                                   colony.postAuthor;
                return colonyAuthor && colonyAuthor.toString() === userId?.toString();
            }
            
            return false; // Default deny
        },

        /**
         * Update map markers for all colonies
         */
        updateMapMarkers: function() {
            if (!this.colonyMap) return;
            
            // Clear existing markers
            this.colonyMarkers.forEach(marker => {
                this.colonyMap.removeLayer(marker);
            });
            this.colonyMarkers = [];
            
            // Filter colonies based on permissions
            const visibleColonies = this.colonies.filter(colony => this.canViewColony(colony));
            
            // Add markers for each visible colony
            visibleColonies.forEach(colony => {
                if (colony.lat && colony.lng) {
                    const healthScore = this.calculateHealthScore(colony);
                    const marker = L.marker([colony.lat, colony.lng]).addTo(this.colonyMap);
                    
                    // Format address for display
                    
                    // Try individual fields first, then fall back to combined address
                    const addressParts = [];
                    if (colony.street) addressParts.push(colony.street);
                    if (colony.city) addressParts.push(colony.city);
                    if (colony.state) addressParts.push(colony.state);
                    if (colony.zip) addressParts.push(colony.zip);
                    
                    let formattedAddress = '';
                    if (addressParts.length > 0) {
                        formattedAddress = addressParts.join(', ');
                    } else if (colony.address && colony.address.trim()) {
                        formattedAddress = colony.address.trim();
                    }
                    

                    marker.bindPopup(`
                        <div style="padding: 0.75rem; min-width: 250px;">
                            <h4 style="font-weight: bold; color: #1f2937; margin: 0 0 0.5rem; font-size: 1rem;">${colony.name}</h4>
                            ${formattedAddress ? `<p style="font-size: 0.8rem; color: #6b7280; margin: 0 0 0.75rem; line-height: 1.3;">${formattedAddress}</p>` : ''}
                            <p style="font-size: 0.9rem; color: #1f2937; margin: 0 0 0.75rem; font-weight: 600;">${colony.cats || 0} cats total</p>
                            
                            <div style="font-size: 0.8rem; margin-bottom: 0.75rem;">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                                    <span style="color: #6b7280;">Health Score:</span>
                                    <span style="color: ${this.getProgressColor(healthScore)}; font-weight: 600;">${healthScore}%</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                                    <span style="color: #6b7280;">Food Security:</span>
                                    <span style="color: ${this.getSecurityColor(colony.foodSecurity)}; font-weight: 600;">${colony.foodSecurity || 'Unknown'}</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                                    <span style="color: #6b7280;">Safe Location:</span>
                                    <span style="color: ${this.getSecurityColor(colony.safeLocation)}; font-weight: 600;">${colony.safeLocation || 'Unknown'}</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                                    <span style="color: #6b7280;">Water Security:</span>
                                    <span style="color: ${this.getSecurityColor(colony.waterSecurity)}; font-weight: 600;">${colony.waterSecurity || 'Unknown'}</span>
                                </div>
                            </div>
                            
                            <div style="font-size: 0.8rem; margin-bottom: 0.75rem;">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                                    <span style="color: #6b7280;">Tipped Ears:</span>
                                    <span style="color: #15803d; font-weight: 600;">${colony.tippedEars || 0} (${((colony.cats_cat || colony.adults || 0) + (colony.cats_senior || colony.seniors || 0)) > 0 ? Math.round(((colony.tippedEars || 0) / ((colony.cats_cat || colony.adults || 0) + (colony.cats_senior || colony.seniors || 0))) * 100) : 0}% TNR)</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                                    <span style="color: #6b7280;">Winter Shelters:</span>
                                    <span style="color: #1d4ed8; font-weight: 600;">${colony.winterShelters || 0} (${((colony.cats_cat || colony.adults || 0) + (colony.cats_senior || colony.seniors || 0)) > 0 ? Math.round(((colony.winterShelters || 0) / ((colony.cats_cat || colony.adults || 0) + (colony.cats_senior || colony.seniors || 0))) * 100) : 0}% coverage)</span>
                                </div>
                            </div>
                            
                            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.25rem; font-size: 0.7rem; margin-bottom: 0.75rem; text-align: center;">
                                <div><span style="color: #6b7280;">Newborn:</span><br><strong>${colony.cats_newborn || colony.babies || 0}</strong></div>
                                <div><span style="color: #6b7280;">Kitten:</span><br><strong>${colony.cats_kitten || colony.kittens || 0}</strong></div>
                                <div><span style="color: #6b7280;">Cat:</span><br><strong>${colony.cats_cat || colony.adults || 0}</strong></div>
                                <div><span style="color: #6b7280;">Senior:</span><br><strong>${colony.cats_senior || colony.seniors || 0}</strong></div>
                            </div>
                            
                            ${this.canUserEditColony(colony) ? `
                                <div style="text-align: center;">
                                    <button onclick="CLAWSApp.editColony(${colony.id})" style="background: #3b82f6; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.375rem; font-size: 0.8rem; cursor: pointer; width: 100%;">Edit Colony</button>
                                </div>
                            ` : ''}
                        </div>
                    `, {
                        maxWidth: 350,
                        className: 'custom-popup'
                    });
                    
                    this.colonyMarkers.push(marker);
                }
            });
        },

        /**
         * Center map on a specific colony
         */
        centerMapOnColony: function(colonyId) {
            const colony = this.colonies.find(c => c.id === colonyId);
            if (colony && colony.lat && colony.lng && this.colonyMap) {
                this.colonyMap.setView([colony.lat, colony.lng], 16);
                
                // Find and open the marker popup
                const marker = this.colonyMarkers.find(m => {
                    const pos = m.getLatLng();
                    return Math.abs(pos.lat - colony.lat) < 0.0001 && Math.abs(pos.lng - colony.lng) < 0.0001;
                });
                
                if (marker) {
                    marker.openPopup();
                }
            }
        },

        /**
         * Add a new marker to the map
         */
        addColonyMarker: function(colony) {
            if (!this.colonyMap || !colony.lat || !colony.lng) return;
            
            const healthScore = this.calculateHealthScore(colony);
            const marker = L.marker([colony.lat, colony.lng]).addTo(this.colonyMap);
            
            const addressParts = [];
            if (colony.street) addressParts.push(colony.street);
            if (colony.city) addressParts.push(colony.city);
            if (colony.state) addressParts.push(colony.state);
            if (colony.zip) addressParts.push(colony.zip);
            
            let formattedAddress = '';
            if (addressParts.length > 0) {
                formattedAddress = addressParts.join(', ');
            } else if (colony.address && colony.address.trim()) {
                formattedAddress = colony.address.trim();
            }
            
            marker.bindPopup(`
                <div style="padding: 0.5rem;">
                    <h4 style="font-weight: bold; color: #1f2937; margin: 0 0 0.25rem;">${colony.name}</h4>
                    ${formattedAddress ? `<p style="font-size: 0.75rem; color: #6b7280; margin: 0 0 0.5rem; line-height: 1.3;">${formattedAddress}</p>` : ''}
                    <p style="font-size: 0.875rem; color: #6b7280; margin: 0 0 0.5rem;">${colony.cats || 0} cats total</p>
                    <div style="font-size: 0.75rem;">
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: #6b7280;">Health Score:</span>
                            <span style="color: ${this.getProgressColor(healthScore)}; font-weight: 600;">${healthScore}%</span>
                        </div>
                        ${this.canUserEditColony(colony) ? `
                            <div style="margin-top: 0.5rem; text-align: center;">
                                <button onclick="CLAWSApp.editColony(${colony.id})" style="background: #3b82f6; color: white; border: none; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.7rem; cursor: pointer;">Edit Colony</button>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `);
            
            this.colonyMarkers.push(marker);
            return marker;
        },

        /**
         * Remove a marker from the map
         */
        removeColonyMarker: function(colonyId) {
            const colony = this.colonies.find(c => c.id === colonyId);
            if (!colony || !this.colonyMap) return;
            
            const markerIndex = this.colonyMarkers.findIndex(marker => {
                const pos = marker.getLatLng();
                return Math.abs(pos.lat - colony.lat) < 0.0001 && Math.abs(pos.lng - colony.lng) < 0.0001;
            });
            
            if (markerIndex >= 0) {
                this.colonyMap.removeLayer(this.colonyMarkers[markerIndex]);
                this.colonyMarkers.splice(markerIndex, 1);
            }
        },

        /**
         * Fit map bounds to show all colonies
         */
        fitMapToColonies: function() {
            if (!this.colonyMap || this.colonies.length === 0) return;
            
            // Filter by both permissions and coordinates
            const visibleColonies = this.colonies.filter(colony => this.canViewColony(colony));
            const coloniesWithCoords = visibleColonies.filter(colony => colony.lat && colony.lng);
            if (coloniesWithCoords.length === 0) return;
            
            if (coloniesWithCoords.length === 1) {
                // Single colony - center on it
                const colony = coloniesWithCoords[0];
                this.colonyMap.setView([colony.lat, colony.lng], 15);
            } else {
                // Multiple colonies - fit bounds
                const group = new L.featureGroup(this.colonyMarkers);
                this.colonyMap.fitBounds(group.getBounds().pad(0.1));
            }
        }

    });

})();