/**
 * CLAWS Colony Management Module
 * Handles colony CRUD operations, health tracking, and colony-specific functionality
 */

(function() {
    'use strict';

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

        /**
         * Initialize Colony Tracker
         */
        initColonyTracker: async function() {
            // CRITICAL: Load config first (for standalone shortcode usage)
            this.loadConfig();
            
            // Load colonies data FIRST (like discharge does)
            await this.loadColonies();
            
            // Render everything immediately (no artificial delays)
            this.updateColonyUI();
            
            // Initialize map immediately (no delay)
            this.initializeMap();
        },

        /**
         * Load colonies from API or use demo data
         */
        loadColonies: async function() {
            try {
                // HARD BLOCK: Pure subscribers see empty colonies
                const isPureSubscriber = clawsData.userRoles && 
                    clawsData.userRoles.includes('subscriber') &&
                    !clawsData.userRoles.includes('contributor') &&
                    !clawsData.userRoles.includes('author') &&
                    !clawsData.userRoles.includes('administrator');
                    
                if (isPureSubscriber) {
                    this.colonies = []; // Force empty array
                    this.updateColonyUI();
                    return;
                }
                
                // Add cache busting parameter
                const timestamp = new Date().getTime();
                const response = await fetch(`${this.config.apiUrl}colonies?_=${timestamp}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (response.ok) {
                    const rawColonies = await response.json();
                    this.colonies = this.normalizeColonyData(rawColonies);
                } else {
                    throw new Error('Failed to load from API: ' + response.status);
                }
            } catch (error) {
                this.loadDemoColonies();
            }
            
            // Don't update UI here - caller will do it after data is loaded
        },

        /**
         * Normalize colony data from backend field names to frontend field names
         */
        normalizeColonyData: function(rawColonies) {
            if (!Array.isArray(rawColonies)) {
                return [];
            }
            
            return rawColonies.map(colony => {
                
                const normalized = {
                    ...colony,
                    // Standardize on backend field names (foodSecurity, safeLocation)
                    foodSecurity: colony.foodSecurity || colony.food_security || null,
                    safeLocation: colony.safeLocation || colony.safe_location || null,
                    waterSecurity: colony.waterSecurity || colony.water_security || null,
                    tippedEars: colony.tippedEars || colony.tipped_ears || 0,
                    winterShelters: colony.winterShelters || colony.winter_shelters || 0,
                    
                    // Ensure numeric fields are properly converted - check ALL possible field names
                    babies: parseInt(colony.babies || colony.newborn || colony.cats_babies || colony.cats_newborn) || 0,
                    kittens: parseInt(colony.kittens || colony.kitten || colony.cats_kittens || colony.cats_kitten) || 0,
                    adults: parseInt(colony.adults || colony.cat || colony.cats_adults || colony.cats_cat) || 0,
                    seniors: parseInt(colony.seniors || colony.senior || colony.cats_seniors || colony.cats_senior) || 0,
                    // Also set singular versions for popup display
                    newborn: parseInt(colony.babies || colony.newborn || colony.cats_babies || colony.cats_newborn) || 0,
                    kitten: parseInt(colony.kittens || colony.kitten || colony.cats_kittens || colony.cats_kitten) || 0,
                    cat: parseInt(colony.adults || colony.cat || colony.cats_adults || colony.cats_cat) || 0,
                    senior: parseInt(colony.seniors || colony.senior || colony.cats_seniors || colony.cats_senior) || 0,
                    cats: parseInt(colony.cats) || (
                        (parseInt(colony.babies || colony.newborn || colony.cats_babies || colony.cats_newborn) || 0) +
                        (parseInt(colony.kittens || colony.kitten || colony.cats_kittens || colony.cats_kitten) || 0) +
                        (parseInt(colony.adults || colony.cat || colony.cats_adults || colony.cats_cat) || 0) +
                        (parseInt(colony.seniors || colony.senior || colony.cats_seniors || colony.cats_senior) || 0)
                    ),
                    
                    // Ensure coordinate fields are properly converted
                    lat: parseFloat(colony.latitude || colony.lat) || null,
                    lng: parseFloat(colony.longitude || colony.lng) || null,
                    
                    // Preserve caregiver data (handle ALL possible formats)
                    caregiver: colony.caregiver || colony.primaryCaregiver || colony.caregiver_name || 
                              (colony.caregivers && colony.caregivers[0] && colony.caregivers[0].name) ||
                              (colony.caregivers && colony.caregivers[0] && typeof colony.caregivers[0] === 'string' ? colony.caregivers[0] : null) ||
                              null,
                    caregivers: colony.caregivers || [],
                    caregiverId: colony.caregiverId || colony.caregiver_id || 
                                (colony.caregivers && colony.caregivers[0] && colony.caregivers[0].id) ||
                                null
                };
                
                return normalized;
            });
        },

        /**
         * Load demo colony data for testing
         */
        loadDemoColonies: function() {
            this.colonies = [
                {
                    id: 1,
                    name: "Downtown Parking Lot",
                    address: "123 Main St, Downtown",
                    street: "123 Main St",
                    city: "Downtown", 
                    state: "KS",
                    zip: "67012",
                    date: "2024-01-15",
                    lat: 39.8283,
                    lng: -98.5795,
                    cats: 8,
                    babies: 2,
                    kittens: 3,
                    seniors: 1,
                    adults: 2,
                    foodSecurity: 'Good',
                    safeLocation: 'Marginal',
                    waterSecurity: 'Sufficient',
                    tippedEars: 3,
                    winterShelters: 2,
                    notes: "Located behind shopping center. Friendly cats, regularly fed by store employees."
                }
            ];
        },

        /**
         * Update colony UI components
         */
        updateColonyUI: function() {
            this.updateStatistics();
            this.updateMapMarkers();
            this.updatePieChart();
            this.renderColonyContent();
        },

        /**
         * Update statistics display
         */
        updateStatistics: function() {
            // HARD BLOCK: Pure subscribers see zero statistics
            const isPureSubscriber = clawsData.userRoles && 
                clawsData.userRoles.includes('subscriber') &&
                !clawsData.userRoles.includes('contributor') &&
                !clawsData.userRoles.includes('author') &&
                !clawsData.userRoles.includes('administrator');
                
            const totalColoniesEl = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.TOTAL_COLONIES);
            const totalCatsEl = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.TOTAL_CATS);
            
            if (isPureSubscriber) {
                if (totalColoniesEl) totalColoniesEl.textContent = '0';
                if (totalCatsEl) totalCatsEl.textContent = '0';
                return;
            }
            
            const totalColonies = this.colonies.length;
            const totalCats = this.colonies.reduce((sum, colony) => sum + (colony.cats || 0), 0);
            
            if (totalColoniesEl) totalColoniesEl.textContent = totalColonies;
            if (totalCatsEl) totalCatsEl.textContent = totalCats;
        },

        /**
         * Check if user can edit a specific colony
         */
        canUserEditColony: function(colony) {
            // Pure subscribers cannot edit anything
            if (clawsData.userRoles && clawsData.userRoles.includes('subscriber') && 
                !clawsData.userRoles.includes('contributor') && 
                !clawsData.userRoles.includes('author') && 
                !clawsData.userRoles.includes('administrator')) {
                return false;
            }
            
            // Administrators can edit everything
            if (clawsData.userRoles && clawsData.userRoles.includes('administrator')) {
                return true;
            }
            
            // Authors can edit everything
            if (clawsData.userRoles && clawsData.userRoles.includes('author')) {
                return true;
            }
            
            // Contributors can only edit their own colonies
            if (clawsData.userRoles && clawsData.userRoles.includes('contributor')) {
                return colony._debug && (
                    colony._debug.postAuthor == clawsData.userId || 
                    colony._debug.addedByUserId == clawsData.userId
                );
            }
            
            return false;
        },

        /**
         * Switch chart type between bar and line
         */
        switchChartType: function(chartType) {
            // Store the selected chart type
            CLAWSApp.selectedChartType = chartType;
            
            // Destroy all existing chart instances
            document.querySelectorAll('canvas[id^="history-chart-"]').forEach(canvas => {
                if (canvas._chartInstance) {
                    canvas._chartInstance.destroy();
                    canvas._chartInstance = null;
                }
            });
            
            // Update the radio buttons to reflect the new selection
            const barRadio = document.getElementById('chart-type-bar');
            const lineRadio = document.getElementById('chart-type-line');
            if (barRadio && lineRadio) {
                barRadio.checked = (chartType === 'bar');
                lineRadio.checked = (chartType === 'line');
            }
            
            // Update the colony health list which will recreate all charts with new type
            this.updateColonyHealthList();
        },

        /**
         * Get security score (4-20 points for Very Good down to Insufficient)
         */
        getSecurityScore: function(level) {
            const scores = {
                'Very Good': 20, 'Good': 16, 'Sufficient': 12, 'Marginal': 8, 'Insufficient': 4
            };
            return scores[level] || 0;
        },

        /**
         * Get location safety score (4-20 points for Very Safe down to Dangerous)
         */
        getLocationScore: function(level) {
            const scores = {
                'Very Safe': 20, 'Safe': 16, 'Somewhat Safe': 12, 'Unsafe': 8, 'Dangerous': 4
            };
            return scores[level] || 0;
        },

        /**
         * Calculate health score for a colony (CORRECTED - always uses 5 factors)
         */
        calculateHealthScore: function(colony) {
            let totalScore = 0;
            
            // Food security factor (4-20 points based on 5 levels)
            let foodScore = 0;
            if (colony.foodSecurity) {
                const feedingScores = {
                    'Very Good': 20, 'Good': 16, 'Sufficient': 12, 'Marginal': 8, 'Insufficient': 4
                };
                foodScore = feedingScores[colony.foodSecurity] || 0;
            }
            totalScore += foodScore;
            
            // Safe location factor (4-20 points based on 5 levels)
            let locationScore = 0;
            if (colony.safeLocation) {
                const shelterScores = {
                    'Very Safe': 20, 'Safe': 16, 'Somewhat Safe': 12, 'Unsafe': 8, 'Dangerous': 4
                };
                locationScore = shelterScores[colony.safeLocation] || 0;
            }
            totalScore += locationScore;
            
            // Water security factor (4-20 points based on 5 levels)
            let waterScore = 0;
            if (colony.waterSecurity) {
                const waterScores = {
                    'Very Good': 20, 'Good': 16, 'Sufficient': 12, 'Marginal': 8, 'Insufficient': 4
                };
                waterScore = waterScores[colony.waterSecurity] || 0;
            }
            totalScore += waterScore;
            
            // TNR Progress factor (0-20 points based on percentage - cats and seniors only)
            let tnrScore = 0;
            const catsAndSeniorsForTNR = (colony.cats_cat || colony.cat || colony.adults || 0) + (colony.cats_senior || colony.senior || colony.seniors || 0);
            if (catsAndSeniorsForTNR > 0) {
                const tippedEars = parseInt(colony.tippedEars) || 0;
                const tnrRatio = Math.min(tippedEars / catsAndSeniorsForTNR, 1); // Cap at 100%
                tnrScore = tnrRatio * 20; // 0-20 points based on TNR percentage
            }
            // Note: If no cats+seniors, TNR score stays 0 (not skipped)
            totalScore += tnrScore;
            
            // Winter shelter availability factor (0-20 points based on coverage - cats and seniors only)
            let shelterScore = 0;
            const catsAndSeniors = (colony.cats_cat || colony.cat || colony.adults || 0) + (colony.cats_senior || colony.senior || colony.seniors || 0);
            if (catsAndSeniors > 0) {
                const winterShelters = parseInt(colony.winterShelters) || 0;
                const shelterRatio = Math.min(winterShelters / catsAndSeniors, 1); // Cap at 1 shelter per cat/senior
                shelterScore = shelterRatio * 20; // 0-20 points based on shelter coverage
            }
            // Note: If no cats+seniors, shelter score stays 0 (not skipped)
            totalScore += shelterScore;
            
            // Total possible score is 100 (5 factors × 20 points each)
            // Return percentage (0-100)
            return Math.round(totalScore);
        },

        /**
         * Update colony health list display
         */
        updateColonyHealthList: function() {
            const healthList = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_HEALTH_LIST);
            if (!healthList) return;
            
            // Clear existing content
            healthList.innerHTML = '';
            
            // Filter colonies based on user permissions
            const visibleColonies = this.colonies.filter(colony => this.canViewColony(colony));
            
            // Calculate and sort colonies by health score
            const coloniesWithHealth = visibleColonies.map(colony => ({
                ...colony,
                healthScore: this.calculateHealthScore(colony)
            })).sort((a, b) => a.healthScore - b.healthScore);
            
            // If no colonies are visible, show appropriate message
            if (coloniesWithHealth.length === 0) {
                healthList.innerHTML = `
                    <div style="text-align: center; padding: 2rem; color: #6b7280;">
                        <p style="margin: 0; font-size: 0.875rem;">No colonies to display.</p>
                        <p style="margin: 0.5rem 0 0; font-size: 0.75rem;">You may need appropriate permissions or there may be no colonies added yet.</p>
                    </div>
                `;
                return;
            }
            
            coloniesWithHealth.forEach(colony => {
                const healthColor = this.getProgressColor(colony.healthScore);
                const canEdit = this.canUserEditColony(colony);
                
                const colonyCard = document.createElement('div');
                colonyCard.className = 'colony-health-card';
                // Format address for display
                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();
                } else {
                    formattedAddress = 'Address not specified';
                }

                // Format date for display
                const lastUpdated = colony.date ? new Date(colony.date).toLocaleDateString() : 'Unknown';
                
                colonyCard.innerHTML = `
                    <div style="background: white; border-radius: 0.75rem; padding: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; margin-bottom: 0.75rem;">
                        <!-- Header with name, address, health score -->
                        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1rem;">
                            <div style="flex: 1;">
                                <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 1rem;">${colony.name}</h4>
                                <p style="color: #6b7280; font-size: 0.8rem; margin: 0 0 0.25rem; line-height: 1.3;">${formattedAddress}</p>
                                <p style="color: #9ca3af; font-size: 0.7rem; margin: 0;">Last updated: ${lastUpdated}</p>
                            </div>
                            <div style="text-align: right;">
                                <div style="background: ${healthColor}; color: white; padding: 0.375rem 0.75rem; border-radius: 0.5rem; font-size: 0.8rem; font-weight: 600; margin-bottom: 0.5rem;">
                                    Health: ${colony.healthScore}%
                                </div>
                                ${canEdit ? `<button onclick="CLAWSApp.editColony(${colony.id})" style="
                                    background: linear-gradient(to bottom, #60a5fa, #3b82f6); 
                                    color: white; 
                                    border: none; 
                                    border-top: 1px solid rgba(255, 255, 255, 0.3);
                                    border-bottom: 2px solid rgba(0, 0, 0, 0.2);
                                    padding: 0.5rem 1rem; 
                                    border-radius: 0.5rem; 
                                    font-size: 0.875rem; 
                                    cursor: pointer; 
                                    font-weight: 600;
                                    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1);
                                    transition: all 0.2s ease;
                                    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
                                " onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">Edit Colony</button>` : ''}
                            </div>
                        </div>
                        
                        <!-- Cat Population Breakdown -->
                        <div style="margin-bottom: 1rem;">
                            <h5 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem; font-size: 0.8rem;">Population Analysis (${colony.cats || 0} total)</h5>
                            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.5rem; font-size: 0.75rem;">
                                <div style="text-align: center; padding: 0.5rem; background: #fef3c7; border-radius: 0.375rem; border: 1px solid #fbbf24;">
                                    <div style="font-weight: 600; color: #92400e; font-size: 0.9rem;">${colony.newborn || colony.babies || 0}</div>
                                    <div style="color: #78350f; font-size: 0.7rem;">Newborn (0-8wks)</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: #dcfce7; border-radius: 0.375rem; border: 1px solid #22c55e;">
                                    <div style="font-weight: 600; color: #166534; font-size: 0.9rem;">${colony.kitten || colony.kittens || 0}</div>
                                    <div style="color: #15803d; font-size: 0.7rem;">Kitten (2-5mo)</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: #dbeafe; border-radius: 0.375rem; border: 1px solid #3b82f6;">
                                    <div style="font-weight: 600; color: #1d4ed8; font-size: 0.9rem;">${colony.cat || colony.adults || 0}</div>
                                    <div style="color: #1e40af; font-size: 0.7rem;">Cat (6mo-8yrs)</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: #f3e8ff; border-radius: 0.375rem; border: 1px solid #8b5cf6;">
                                    <div style="font-weight: 600; color: #7c3aed; font-size: 0.9rem;">${colony.senior || colony.seniors || 0}</div>
                                    <div style="color: #6d28d9; font-size: 0.7rem;">Senior (8+ yrs)</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Comprehensive Security Assessment -->
                        <div style="margin-bottom: 1rem;">
                            <h5 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem; font-size: 0.8rem;">Security & Resource Assessment</h5>
                            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; font-size: 0.75rem;">
                                <div style="text-align: center; padding: 0.5rem; background: #f9fafb; border-radius: 0.375rem; border: 1px solid #e5e7eb;">
                                    <div style="font-weight: 600; color: ${this.getSecurityColor(colony.foodSecurity)}; margin-bottom: 0.25rem; font-size: 0.8rem;">${colony.foodSecurity || 'Not Assessed'}</div>
                                    <div style="color: #6b7280; font-size: 0.7rem;">Food Security</div>
                                    <div style="color: #9ca3af; font-size: 0.65rem; margin-top: 0.25rem;">Food availability & regularity</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: #f9fafb; border-radius: 0.375rem; border: 1px solid #e5e7eb;">
                                    <div style="font-weight: 600; color: ${this.getSecurityColor(colony.safeLocation)}; margin-bottom: 0.25rem; font-size: 0.8rem;">${colony.safeLocation || 'Not Assessed'}</div>
                                    <div style="color: #6b7280; font-size: 0.7rem;">Safe Location</div>
                                    <div style="color: #9ca3af; font-size: 0.65rem; margin-top: 0.25rem;">Weather protection & safety</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: #f9fafb; border-radius: 0.375rem; border: 1px solid #e5e7eb;">
                                    <div style="font-weight: 600; color: ${this.getSecurityColor(colony.waterSecurity)}; margin-bottom: 0.25rem; font-size: 0.8rem;">${colony.waterSecurity || 'Not Assessed'}</div>
                                    <div style="color: #6b7280; font-size: 0.7rem;">Water Security</div>
                                    <div style="color: #9ca3af; font-size: 0.65rem; margin-top: 0.25rem;">Fresh water access & quality</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- TNR & Care Assessment -->
                        <div style="margin-bottom: 1rem;">
                            <h5 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem; font-size: 0.8rem;">TNR & Care Status</h5>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; font-size: 0.75rem;">
                                <div style="text-align: center; padding: 0.5rem; background: #f0fdf4; border-radius: 0.375rem; border: 1px solid #bbf7d0;">
                                    <div style="font-weight: 600; color: #15803d; margin-bottom: 0.25rem; font-size: 0.9rem;">${colony.tippedEars || 0}</div>
                                    <div style="color: #166534; font-size: 0.7rem;">TNR</div>
                                    <div style="color: #15803d; font-size: 0.65rem; margin-top: 0.25rem;">${(colony.cat || 0) + (colony.senior || 0) > 0 ? Math.round(((colony.tippedEars || 0) / ((colony.cat || 0) + (colony.senior || 0))) * 100) + '% TNR' : 'No eligible cats'}</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: #eff6ff; border-radius: 0.375rem; border: 1px solid #bfdbfe;">
                                    <div style="font-weight: 600; color: #1d4ed8; margin-bottom: 0.25rem; font-size: 0.9rem;">${colony.winterShelters || 0}</div>
                                    <div style="color: #1e40af; font-size: 0.7rem;">Shelters</div>
                                    <div style="color: #1d4ed8; font-size: 0.65rem; margin-top: 0.25rem;">${colony.cats > 0 ? Math.round(((colony.winterShelters || 0) / colony.cats) * 100) + '% coverage' : 'No cats'}</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Historical Tracking Chart (Authors/Admins only) -->
                        ${this.canViewColonyHistory(colony) ? `
                        <div style="margin-bottom: 1rem;" id="colony-history-${colony.id}">
                            <h5 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem; font-size: 0.8rem;">Historical Tracking</h5>
                            <div style="background: #f9fafb; padding: 0.75rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <div style="height: 200px; position: relative;">
                                    <canvas id="history-chart-${colony.id}" width="100%" height="100%"></canvas>
                                    <div id="chart-loading-${colony.id}" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #6b7280; font-size: 0.8rem;">
                                        Loading historical data...
                                    </div>
                                </div>
                            </div>
                        </div>
                        ` : ''}
                        
                        
                        <!-- Additional Notes (if available) -->
                        ${colony.notes && colony.notes.trim() ? `
                        <div style="margin-bottom: 1rem;">
                            <h5 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem; font-size: 0.8rem;">Notes</h5>
                            <div style="background: #f8fafc; padding: 0.75rem; border-radius: 0.375rem; border: 1px solid #e2e8f0; font-size: 0.75rem; color: #475569; line-height: 1.4;">
                                ${colony.notes.trim()}
                            </div>
                        </div>
                        ` : ''}
                        
                    </div>
                `;
                
                healthList.appendChild(colonyCard);
                
                // Load historical data for the chart if user can view it
                if (this.canViewColonyHistory(colony)) {
                    // Wait a bit for DOM to be ready
                    setTimeout(() => {
                        this.loadColonyHistory(colony.id);
                    }, 100);
                }
            });
        },





        /**
         * Edit colony function
         */
        editColony: function(colonyId) {
            const colony = this.colonies.find(c => c.id == colonyId);
            
            if (!colony) {
                this.showAlert('Colony not found', 'error');
                return;
            }
            
            if (!this.canUserEditColony(colony)) {
                this.showAlert('You do not have permission to edit this colony', 'error');
                return;
            }
            
            // Show the dedicated edit colony form
            this.showEditColonyForm();
            
            // Wait for form to be fully rendered and populated
            const waitForFormAndPopulate = (attempts = 0) => {
                const nameField = document.getElementById('claws-edit-colony-name');
                const maxAttempts = 10;
                
                if (!nameField && attempts < maxAttempts) {
                    setTimeout(() => waitForFormAndPopulate(attempts + 1), 100);
                    return;
                }
                
                if (!nameField) {
                    return;
                }
                
                
                // Populate with colony data
                this.populateEditColonyForm(colony);
                
                // Setup the save button to call the edit form update function
                const saveButton = document.getElementById('claws-edit-save-button');
                if (saveButton) {
                    saveButton.onclick = () => this.updateColonyFromEditForm(colonyId);
                }
            };
            
            waitForFormAndPopulate();
        },

        /**
         * Render main colony content section
         */
        renderColonyContent: function() {
            const colonyContent = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_CONTENT);
            if (!colonyContent) return;
            
            // Check user permissions for colony actions
            const canCreateColonies = clawsData.canCreateColonies || false;
            const isPureSubscriber = clawsData.userRoles && 
                clawsData.userRoles.includes('subscriber') &&
                !clawsData.userRoles.includes('contributor') &&
                !clawsData.userRoles.includes('author') &&
                !clawsData.userRoles.includes('administrator');
            
            // Check if user has any colonies to view
            const hasColonies = this.colonies && this.colonies.length > 0;
            
            colonyContent.innerHTML = `
                <!-- Health Score Formula - Full Width -->
                <div style="background: #f0f9ff; border-radius: 1rem; padding: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); border: 1px solid #0ea5e9; margin-bottom: 1rem;">
                    <h3 style="font-weight: 600; color: #0c4a6e; margin: 0 0 0.5rem; font-size: 0.875rem;">📊 Colony Health Score Formula</h3>
                    <div style="font-size: 0.75rem; color: #075985; line-height: 1.4;">
                        <strong>Health Score = Average of 5 factors:</strong>
                        <br>• <strong>Food Security</strong> (Very Good/Good/Sufficient/Marginal/Insufficient)
                        <br>• <strong>Water Security</strong> (Very Good/Good/Sufficient/Marginal/Insufficient)  
                        <br>• <strong>Shelter Security</strong> (Very Safe/Safe/Somewhat Safe/Unsafe/Dangerous)
                        <br>• <strong>TNR Progress</strong> (% of cats + seniors with tipped ears)
                        <br>• <strong>Shelters</strong> (% of cats + seniors with shelter coverage)
                        <div style="margin-top: 0.5rem; font-style: italic; color: #0369a1;">
                            *Newborns and kittens excluded from TNR and shelter calculations - they nest with mothers and are too young for spay/neuter
                        </div>
                    </div>
                </div>

                ${hasColonies ? `
                <!-- Colony Overview - Full Width -->
                <div style="background: white; border-radius: 1rem; padding: 1.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; margin-bottom: 1rem;">
                    <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; font-size: 0.875rem;">Colony Overview</h3>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                        <div style="text-align: center;">
                            <div style="font-size: 2rem; font-weight: 700; color: #3b82f6;" id="claws-total-colonies">${this.colonies.length}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">Total Colonies</div>
                        </div>
                        <div style="text-align: center;">
                            <div style="font-size: 2rem; font-weight: 700; color: #10b981;" id="claws-total-cats">${this.colonies.reduce((sum, colony) => sum + (colony.cats || 0), 0)}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">Total Cats</div>
                        </div>
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.5rem; font-size: 0.75rem;">
                        <div style="text-align: center; padding: 0.5rem; background: #fef3c7; border-radius: 0.375rem;">
                            <div style="font-weight: 600; color: #92400e; font-size: 1.1rem;">${this.colonies.reduce((sum, colony) => sum + (colony.newborn || colony.babies || 0), 0)}</div>
                            <div style="color: #78350f; font-weight: 600;">Newborn</div>
                            <div style="color: #78350f; font-size: 0.65rem;">(0-8wks)</div>
                        </div>
                        <div style="text-align: center; padding: 0.5rem; background: #dcfce7; border-radius: 0.375rem;">
                            <div style="font-weight: 600; color: #166534; font-size: 1.1rem;">${this.colonies.reduce((sum, colony) => sum + (colony.kitten || colony.kittens || 0), 0)}</div>
                            <div style="color: #15803d; font-weight: 600;">Kitten</div>
                            <div style="color: #15803d; font-size: 0.65rem;">(2-5mo)</div>
                        </div>
                        <div style="text-align: center; padding: 0.5rem; background: #dbeafe; border-radius: 0.375rem;">
                            <div style="font-weight: 600; color: #1d4ed8; font-size: 1.1rem;">${this.colonies.reduce((sum, colony) => sum + (colony.cat || colony.adults || 0), 0)}</div>
                            <div style="color: #1e40af; font-weight: 600;">Cat</div>
                            <div style="color: #1e40af; font-size: 0.65rem;">(6mo-8yrs)</div>
                        </div>
                        <div style="text-align: center; padding: 0.5rem; background: #f3e8ff; border-radius: 0.375rem;">
                            <div style="font-weight: 600; color: #7c3aed; font-size: 1.1rem;">${this.colonies.reduce((sum, colony) => sum + (colony.senior || colony.seniors || 0), 0)}</div>
                            <div style="color: #6d28d9; font-weight: 600;">Senior</div>
                            <div style="color: #6d28d9; font-size: 0.65rem;">(8+ yrs)</div>
                        </div>
                    </div>
                </div>
                
                
                <!-- Colony Size Distribution (Pie Chart) -->
                <div style="background: white; border-radius: 1rem; padding: 1.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; margin-bottom: 1rem;">
                    <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; font-size: 0.875rem; text-align: center;">Colony Size Distribution</h3>
                    <div style="position: relative; height: 250px; display: flex; align-items: center; justify-content: center;">
                        <canvas id="claws-colony-pie-chart" width="400" height="250"></canvas>
                    </div>
                    <div id="claws-chart-legend" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 0.5rem; margin-top: 1rem;"></div>
                </div>
                ` : ''}
                
                <!-- Health Assessment -->
                <div style="background: white; border-radius: 1rem; padding: 1.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb;">
                    <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; font-size: 0.875rem;">Colony Health Assessment</h3>
                    
                    ${hasColonies ? `
                    <!-- Historical Data Display Options -->
                    <div style="margin-bottom: 1.5rem; padding: 0.75rem; background: #f9fafb; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                        <p style="font-weight: 500; color: #374151; margin: 0 0 0.5rem; font-size: 0.8rem;">Display Historical Data as:</p>
                        <div style="display: flex; gap: 1rem; align-items: center;">
                            <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer; font-size: 0.8rem; color: #374151;">
                                <input type="radio" name="chart-type" value="bar" id="chart-type-bar" ${this.selectedChartType === 'bar' ? 'checked' : ''} onchange="CLAWSApp.switchChartType('bar')" style="margin: 0; accent-color: #3b82f6;" />
                                <span>Bar</span>
                            </label>
                            <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer; font-size: 0.8rem; color: #374151;">
                                <input type="radio" name="chart-type" value="line" id="chart-type-line" ${this.selectedChartType === 'line' ? 'checked' : ''} onchange="CLAWSApp.switchChartType('line')" style="margin: 0; accent-color: #3b82f6;" />
                                <span>Line</span>
                            </label>
                        </div>
                    </div>
                    ` : ''}
                    
                    <div id="claws-colony-health-list"></div>
                </div>
            `;
            
            // Update the health list  
            this.updateColonyHealthList();
        },
        
        /**
         * Check if user can view colony data (contributors see their own, authors/admins see all, subscribers see none)
         */
        canViewColony: function(colony) {
            if (!window.clawsData || !window.clawsData.userRoles) {
                return false;
            }
            
            const userRoles = window.clawsData.userRoles;
            const userId = parseInt(window.clawsData.userId);
            
            // Pure subscribers cannot see any colony data
            const isPureSubscriber = userRoles.includes('subscriber') &&
                !userRoles.includes('contributor') &&
                !userRoles.includes('author') &&
                !userRoles.includes('administrator');
            
            if (isPureSubscriber) {
                return false;
            }
            
            // Administrators can see all colonies
            if (userRoles.includes('administrator')) {
                return true;
            }
            
            // Authors can see all colonies  
            if (userRoles.includes('author')) {
                return true;
            }
            
            // Contributors can only see their own colonies
            if (userRoles.includes('contributor')) {
                // Check if this user created this colony
                return colony._debug && (
                    colony._debug.postAuthor == userId || 
                    colony._debug.authorId == userId ||
                    colony.author_id == userId
                );
            }
            
            return false;
        },

        /**
         * Check if user can view colony history (authors, editors, admins only)
         */
        canViewColonyHistory: function(colony) {
            
            if (!window.clawsData || !window.clawsData.userRole) {
                return false;
            }
            
            const userRole = window.clawsData.userRole;
            const userId = window.clawsData.userId;
            
            
            // Admins can see all histories
            if (userRole === 'administrator') {
                return true;
            }
            
            // Authors can see all histories
            if (userRole === 'author') {
                return true;
            }
            
            // Contributors can only see their own colony histories
            if (userRole === 'contributor') {
                const canView = colony.author_id == userId;
                return canView;
            }
            
            return false;
        },
        
        /**
         * Load and display historical chart for a colony
         */
        loadColonyHistory: function(colonyId) {
            
            if (!window.Chart) {
                return;
            }
            
            fetch(`${window.clawsData.apiUrl}colony/${colonyId}/history`, {
                headers: {
                    'X-WP-Nonce': window.clawsData.nonce,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                return response.json();
            })
            .then(data => {
                this.renderHistoryChart(colonyId, data);
            })
            .catch(error => {
                const loadingEl = document.getElementById(`chart-loading-${colonyId}`);
                if (loadingEl) {
                    loadingEl.textContent = 'Error loading data';
                }
            });
        },
        
        /**
         * Render historical chart with dual bar visualization
         */
        renderHistoryChart: function(colonyId, historyData) {
            const canvas = document.getElementById(`history-chart-${colonyId}`);
            const loadingEl = document.getElementById(`chart-loading-${colonyId}`);
            
            if (!canvas || !historyData || historyData.length === 0) {
                if (loadingEl) {
                    loadingEl.textContent = 'No historical data available';
                }
                return;
            }
            
            // No preferences needed - all datasets always visible
            
            // Hide loading message
            if (loadingEl) {
                loadingEl.style.display = 'none';
            }
            
            // Prepare data for Chart.js
            // Create separate arrays for cat counts and dates for better positioning
            const catCounts = historyData.map(entry => {
                // Use new standardized field names, fallback to legacy names
                const totalCats = (parseInt(entry.cats_newborn || entry.cats_babies) || 0) + 
                                (parseInt(entry.cats_kitten || entry.cats_kittens) || 0) + 
                                (parseInt(entry.cats_cat || entry.cats_adults) || 0) + 
                                (parseInt(entry.cats_senior || entry.cats_seniors) || 0);
                return totalCats;
            });
            const dates = historyData.map(entry => entry.effective_date);
            
            // Use dates as main labels for positioning
            const labels = dates;
            const datasets = [];
            
            // Total Cat Count Bar (Left bars) - Age Breakdown (creates "gummy worm" effect)
            
            // Newborn segment (Pastel Yellow/Orange - matching health cards)
            datasets.push({
                label: 'Newborn (0-8wks)',
                data: historyData.map(entry => parseInt(entry.cats_newborn || entry.cats_babies) || 0),
                backgroundColor: '#fef3c7', // Pastel yellow from health cards
                borderColor: '#f59e0b',
                borderWidth: 1,
                stack: 'catCount',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x',
                yAxisID: 'y',
                hidden: false
            });
            
            // Kitten segment (Pastel Mint Green - matching health cards)
            datasets.push({
                label: 'Kitten (2-5mo)',
                data: historyData.map(entry => parseInt(entry.cats_kitten || entry.cats_kittens) || 0),
                backgroundColor: '#dcfce7', // Pastel mint green from health cards
                borderColor: '#10b981',
                borderWidth: 1,
                stack: 'catCount',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x',
                yAxisID: 'y',
                hidden: false
            });
            
            // Adult Cat segment (Pastel Blue - matching health cards)
            datasets.push({
                label: 'Cat (6mo-8yrs)',
                data: historyData.map(entry => parseInt(entry.cats_cat || entry.cats_adults) || 0),
                backgroundColor: '#dbeafe', // Pastel blue from health cards
                borderColor: '#3b82f6',
                borderWidth: 1,
                stack: 'catCount',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x',
                yAxisID: 'y',
                hidden: false
            });
            
            // Senior segment (Pastel Purple - matching health cards)
            datasets.push({
                label: 'Senior (8+ yrs)',
                data: historyData.map(entry => parseInt(entry.cats_senior || entry.cats_seniors) || 0),
                backgroundColor: '#f3e8ff', // Pastel purple from health cards
                borderColor: '#8b5cf6',
                borderWidth: 1,
                stack: 'catCount',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x',
                yAxisID: 'y',
                hidden: false
            });
            
            // Colony Health Stacked Bar (Right bars) - Use same calculation as main health score
            const healthData = historyData.map(entry => {
                
                // Convert historical entry to colony-like object for calculateHealthScore
                const historyColony = {
                    foodSecurity: entry.food_security,
                    safeLocation: entry.safe_location, 
                    waterSecurity: entry.water_security,
                    babies: parseInt(entry.cats_babies) || 0,
                    kittens: parseInt(entry.cats_kittens) || 0,
                    adults: parseInt(entry.cats_adults) || 0,
                    seniors: parseInt(entry.cats_seniors) || 0,
                    // Add new standardized field names for health calculation compatibility
                    cats_cat: parseInt(entry.cats_cat) || parseInt(entry.cats_adults) || 0,
                    cats_senior: parseInt(entry.cats_senior) || parseInt(entry.cats_seniors) || 0,
                    cat: parseInt(entry.cats_cat) || parseInt(entry.cats_adults) || 0,
                    senior: parseInt(entry.cats_senior) || parseInt(entry.cats_seniors) || 0,
                    tippedEars: parseInt(entry.tipped_ears) || 0,
                    winterShelters: parseInt(entry.winter_shelters) || 0
                };
                
                // Use the same health calculation as the main system
                const totalHealthScore = this.calculateHealthScore(historyColony);
                
                // Calculate each component's individual contribution (same logic as calculateHealthScore)
                const totalCats = historyColony.babies + historyColony.kittens + historyColony.adults + historyColony.seniors;
                
                // Individual component scores (0-20 points each) - matches new calculateHealthScore
                const foodScore = historyColony.foodSecurity ? this.getSecurityScore(historyColony.foodSecurity) : 0;
                const waterScore = historyColony.waterSecurity ? this.getSecurityScore(historyColony.waterSecurity) : 0;
                const locationScore = historyColony.safeLocation ? this.getLocationScore(historyColony.safeLocation) : 0;
                
                // TNR Progress (0-20 points) - cats and seniors only
                const catsAndSeniorsForTNR = (historyColony.cats_cat || historyColony.cat || historyColony.adults || 0) + (historyColony.cats_senior || historyColony.senior || historyColony.seniors || 0);
                const tnrScore = catsAndSeniorsForTNR > 0 ? Math.min((historyColony.tippedEars / catsAndSeniorsForTNR) * 20, 20) : 0;
                
                // Shelters (0-20 points) - cats and seniors only
                const catsAndSeniors = (historyColony.cats_cat || historyColony.cat || historyColony.adults || 0) + (historyColony.cats_senior || historyColony.senior || historyColony.seniors || 0);
                const shelterScore = catsAndSeniors > 0 ? Math.min((historyColony.winterShelters / catsAndSeniors) * 20, 20) : 0;
                
                // Each component shows its actual contribution (0-20 points each)
                const result = {
                    food: foodScore,
                    water: waterScore,
                    location: locationScore,
                    tnr: tnrScore,
                    shelter: shelterScore,
                    totalHealthScore: totalHealthScore // Store for label display
                };
                
                // Debug logging to verify calculation
                return result;
            });
            
            // Food Security (Pastel Green)
            datasets.push({
                label: 'Food Security',
                data: healthData.map(entry => entry.food),
                backgroundColor: '#bbf7d0', // Pastel green for food
                borderColor: '#10b981',
                borderWidth: 1,
                stack: 'health',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x2', // Different x-axis for health bars
                yAxisID: 'y1', // Percentage scale
                hidden: false
            });
            
            // Water Security (Pastel Blue)
            datasets.push({
                label: 'Water Security',
                data: healthData.map(entry => entry.water),
                backgroundColor: '#bfdbfe', // Pastel blue for water
                borderColor: '#3b82f6',
                borderWidth: 1,
                stack: 'health',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x2', // Different x-axis for health bars
                yAxisID: 'y1', // Percentage scale
                hidden: false
            });
            
            // Location Security (Pastel Orange/Peach)
            datasets.push({
                label: 'Location Security',
                data: healthData.map(entry => entry.location),
                backgroundColor: '#fed7aa', // Pastel orange/peach for location safety
                borderColor: '#f97316',
                borderWidth: 1,
                stack: 'health',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x2', // Different x-axis for health bars
                yAxisID: 'y1', // Percentage scale
                hidden: false
            });
            
            // Shelters (Pastel Purple)
            datasets.push({
                label: 'Shelters',
                data: healthData.map(entry => entry.shelter),
                backgroundColor: '#e9d5ff', // Pastel purple for winter shelters
                borderColor: '#8b5cf6',
                borderWidth: 1,
                stack: 'health',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x2', // Different x-axis for health bars
                yAxisID: 'y1', // Percentage scale
                hidden: false
            });
            
            // TNR Progress (Pastel Teal)
            datasets.push({
                label: 'TNR Progress',
                data: healthData.map(entry => entry.tnr),
                backgroundColor: '#ccfbf1', // Pastel teal for TNR progress
                borderColor: '#14b8a6',
                borderWidth: 1,
                stack: 'health',
                barPercentage: 0.8,
                categoryPercentage: 0.4,
                xAxisID: 'x2', // Different x-axis for health bars
                yAxisID: 'y1', // Percentage scale
                hidden: false
            });
            
            // Register custom plugin for adjacent bar positioning and labels
            const adjacentBarsPlugin = {
                id: 'adjacentBars',
                beforeDatasetsDraw: function(chart) {
                    const meta = chart.getDatasetMeta(0); // Get meta for cat count datasets
                    const healthMeta = chart.getDatasetMeta(4); // Get meta for health datasets (starts at index 4)
                    
                    if (!meta || !healthMeta) return;
                    
                    // Adjust health bar positions to be adjacent to cat bars
                    const catStackIndex = 0;  // Cat datasets are 0-3
                    const healthStackIndex = 4; // Health datasets are 4-9 (6 health components)
                    
                    // Calculate positioning for adjacent bars
                    chart.data.datasets.forEach((dataset, datasetIndex) => {
                        if (dataset.xAxisID === 'x2' && chart.getDatasetMeta(datasetIndex)) {
                            const healthDatasetMeta = chart.getDatasetMeta(datasetIndex);
                            const catDatasetMeta = chart.getDatasetMeta(0); // Reference cat dataset
                            
                            if (healthDatasetMeta.data && catDatasetMeta.data) {
                                healthDatasetMeta.data.forEach((element, pointIndex) => {
                                    if (element && catDatasetMeta.data[pointIndex]) {
                                        const catBar = catDatasetMeta.data[pointIndex];
                                        // Position health bar immediately adjacent to cat bar
                                        element.x = catBar.x + (catBar.width / 2) + (element.width / 2);
                                    }
                                });
                            }
                        }
                    });
                },
                afterDatasetsDraw: function(chart) {
                    const ctx = chart.ctx;
                    const xScale = chart.scales.x;
                    
                    ctx.save();
                    ctx.fillStyle = '#374151';
                    ctx.font = 'bold 11px Arial';
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'top';
                    
                    // Draw labels under both bar stacks
                    chart.data.labels.forEach((label, index) => {
                        const catDatasetMeta = chart.getDatasetMeta(0);
                        const healthDatasetMeta = chart.getDatasetMeta(4);
                        
                        if (catDatasetMeta.data[index] && healthDatasetMeta.data[index]) {
                            const catBar = catDatasetMeta.data[index];
                            const healthBar = healthDatasetMeta.data[index];
                            
                            // Calculate center position between both bars
                            const centerX = (catBar.x + healthBar.x) / 2;
                            
                            // Line 1: Cat count
                            const catCount = catCounts[index];
                            ctx.fillText(`${catCount} Cats`, centerX, chart.chartArea.bottom + 5);
                            
                            // Line 2: Health percentage  
                            const healthEntry = healthData[index];
                            const totalHealth = healthEntry.totalHealthScore;
                            ctx.fillText(`Health: ${Math.round(totalHealth)}%`, centerX, chart.chartArea.bottom + 20);
                        }
                    });
                    
                    ctx.restore();
                }
            };

            // Determine chart type (default to bar if not set)
            const chartType = this.selectedChartType || 'bar';
            
            // Modify datasets based on chart type
            if (chartType === 'line') {
                
                // For line charts, replace all datasets with just two simplified lines
                datasets.length = 0; // Clear all existing datasets
                
                // Calculate total cats for each data point
                const totalCatsData = historyData.map(entry => {
                    return (parseInt(entry.cats_newborn || entry.cats_babies) || 0) + 
                           (parseInt(entry.cats_kitten || entry.cats_kittens) || 0) + 
                           (parseInt(entry.cats_cat || entry.cats_adults) || 0) + 
                           (parseInt(entry.cats_senior || entry.cats_seniors) || 0);
                });
                
                // Calculate total health for each data point (using existing healthData)
                const totalHealthData = healthData.map(entry => entry.totalHealthScore);
                
                // Total Cats Line
                datasets.push({
                    label: 'Total Cats',
                    data: totalCatsData,
                    borderColor: '#3b82f6',
                    backgroundColor: '#3b82f6',
                    borderWidth: 3,
                    pointRadius: 6,
                    pointHoverRadius: 10,
                    pointBorderWidth: 2,
                    pointBorderColor: '#ffffff',
                    fill: false,
                    tension: 0.3,
                    yAxisID: 'y'
                });
                
                // Total Health Line
                datasets.push({
                    label: 'Total Health',
                    data: totalHealthData,
                    borderColor: '#10b981',
                    backgroundColor: '#10b981',
                    borderWidth: 3,
                    pointRadius: 6,
                    pointHoverRadius: 10,
                    pointBorderWidth: 2,
                    pointBorderColor: '#ffffff',
                    fill: false,
                    tension: 0.3,
                    yAxisID: 'y1'
                });
                
            }
            
            // Create chart
            const ctx = canvas.getContext('2d');
            const chart = new Chart(ctx, {
                type: chartType,
                data: {
                    labels: labels,
                    datasets: datasets
                },
                plugins: chartType === 'bar' ? [adjacentBarsPlugin] : [],
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'point',
                        intersect: true
                    },
                    scales: {
                        x: {
                            type: 'category',
                            offset: true,
                            title: {
                                display: false
                            },
                            ticks: {
                                maxRotation: 0,
                                minRotation: 0,
                                padding: chartType === 'bar' ? 35 : 10,
                                display: true // Show x-axis labels in both modes
                            }
                        },
                        x2: {
                            type: 'category',
                            offset: true,
                            position: 'bottom',
                            display: false, // Hide labels since we'll use custom positioning
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            position: 'left',
                            title: {
                                display: true,
                                text: 'Cat Count'
                            },
                            ticks: {
                                stepSize: 1
                            }
                        },
                        y1: {
                            type: 'linear',
                            position: 'right',
                            beginAtZero: true,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Colony Health %'
                            },
                            ticks: {
                                callback: function(value) {
                                    return value + '%';
                                }
                            },
                            grid: {
                                drawOnChartArea: false
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: chartType === 'line', // Show legend only in line mode
                            position: 'top',
                            align: 'center',
                            labels: {
                                filter: function(legendItem, chartData) {
                                    // In line mode, only show main categories: Cats and Health
                                    if (chartType === 'line') {
                                        const catLabels = ['Baby (0-8wks)', 'Kitten (2-5mo)', 'Cat (6mo-8yrs)', 'Senior (8+ yrs)'];
                                        const healthLabels = ['Food Security', 'Water Security', 'Location Security', 'Shelters', 'TNR Progress'];
                                        
                                        // Show one representative from each category
                                        return legendItem.text === 'Cat (6mo-8yrs)' || legendItem.text === 'Food Security';
                                    }
                                    return true;
                                },
                                generateLabels: function(chart) {
                                    if (chartType === 'line') {
                                        // Use actual dataset labels for simplified line chart
                                        return [
                                            {
                                                text: 'Total Cats',
                                                fillStyle: '#3b82f6', // Blue color for cats
                                                strokeStyle: '#3b82f6',
                                                lineWidth: 3,
                                                pointStyle: 'circle'
                                            },
                                            {
                                                text: 'Total Health',
                                                fillStyle: '#10b981', // Green color for health
                                                strokeStyle: '#10b981', 
                                                lineWidth: 3,
                                                pointStyle: 'circle'
                                            }
                                        ];
                                    }
                                    return Chart.defaults.plugins.legend.labels.generateLabels(chart);
                                },
                                usePointStyle: true,
                                padding: 20,
                                font: {
                                    size: 14,
                                    weight: 'bold'
                                }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                title: function(context) {
                                    return 'Date: ' + context[0].label;
                                },
                                label: function(context) {
                                    const datasetLabel = context.dataset.label;
                                    const value = context.parsed.y;
                                    
                                    // Enhanced tooltips for line chart mode
                                    if (chartType === 'line') {
                                        const dataIndex = context.dataIndex;
                                        const historyEntry = historyData[dataIndex];
                                        
                                        // Detailed breakdown for Total Cats line
                                        if (datasetLabel === 'Total Cats') {
                                            return [
                                                `Total Cats: ${value}`,
                                                `--- Population Breakdown ---`,
                                                `Newborn (0-8wks): ${parseInt(historyEntry.cats_newborn || historyEntry.cats_babies) || 0}`,
                                                `Kitten (2-5mo): ${parseInt(historyEntry.cats_kitten || historyEntry.cats_kittens) || 0}`, 
                                                `Cat (6mo-8yrs): ${parseInt(historyEntry.cats_cat || historyEntry.cats_adults) || 0}`,
                                                `Senior (8+ yrs): ${parseInt(historyEntry.cats_senior || historyEntry.cats_seniors) || 0}`
                                            ];
                                        }
                                        
                                        // Detailed breakdown for Total Health line
                                        if (datasetLabel === 'Total Health') {
                                            const healthEntry = healthData[dataIndex];
                                            return [
                                                `Total Health: ${Math.round(value)}%`,
                                                `--- Health Component Breakdown ---`,
                                                `Food Security: ${healthEntry.food.toFixed(1)} pts (${historyEntry.food_security || 'Not set'})`,
                                                `Water Security: ${healthEntry.water.toFixed(1)} pts (${historyEntry.water_security || 'Not set'})`,
                                                `Location Safety: ${healthEntry.location.toFixed(1)} pts (${historyEntry.safe_location || 'Not set'})`,
                                                `TNR Progress: ${healthEntry.tnr.toFixed(1)} pts (${parseInt(historyEntry.tipped_ears) || 0} tipped ears)`,
                                                `Shelters: ${healthEntry.shelter.toFixed(1)} pts (${parseInt(historyEntry.winter_shelters) || 0} shelters)`
                                            ];
                                        }
                                    }
                                    
                                    // Default tooltip for bar chart mode
                                    if (context.dataset.stack === 'health') {
                                        return `${datasetLabel}: ${value.toFixed(1)}% of total health`;
                                    }
                                    
                                    return `${datasetLabel}: ${value}`;
                                },
                                // Add footer to show total health breakdown  
                                footer: function(tooltipItems) {
                                    if (chartType === 'bar') {
                                        // Check if this is a health component tooltip
                                        const healthTooltips = tooltipItems.filter(item => item.dataset.stack === 'health');
                                        if (healthTooltips.length > 0) {
                                            const dataIndex = healthTooltips[0].dataIndex;
                                            const healthEntry = healthData[dataIndex];
                                            const total = healthEntry.totalHealthScore;
                                            return `Total Colony Health: ${Math.round(total)}%`;
                                        }
                                    }
                                    return '';
                                }
                            }
                        }
                    }
                }
            });
            
            // Store chart instance 
            canvas._chartInstance = chart;
        },
        
        
        /**
         * Map security levels to numbers for charting
         */
        mapSecurityToNumber: function(securityLevel) {
            if (!securityLevel) return 0;
            const level = securityLevel.toLowerCase();
            switch (level) {
                case 'insufficient': return 1;
                case 'marginal': return 2;
                case 'sufficient': return 3;
                case 'good': return 4;
                case 'very good': return 5;
                // Handle safety location variants
                case 'dangerous': return 1;
                case 'unsafe': return 2;
                case 'somewhat safe': return 3;
                case 'safe': return 4;
                case 'very safe': return 5;
                default: return 0;
            }
        },
        
        
        /**
         * Export colony data to CSV
         */
        exportColonyData: function() {
            if (!this.colonies || this.colonies.length === 0) {
                this.showAlert('No colony data to export.', 'warning');
                return;
            }

            const csvHeaders = [
                'Colony Name', 'Street Address', 'City', 'State', 'ZIP Code',
                'Newborn (0-8wks)', 'Kitten (2-5mo)', 'Cat (6mo-8yrs)', 'Senior (8+ yrs)', 'Total Cats',
                'Food Security', 'Water Security', 'Safe Location', 'TNR', 'Shelters',
                'Notes', 'Created Date'
            ];

            const csvRows = this.colonies.map(colony => [
                colony.name || '',
                colony.street_address || '',
                colony.city || '',
                colony.state || '',
                colony.zip || '',
                colony.babies || 0,
                colony.kittens || 0,
                colony.adults || 0,
                colony.seniors || 0,
                colony.cats_total || 0,
                colony.food_security || '',
                colony.water_security || '',
                colony.safe_location || '',
                colony.tipped_ears || '',
                colony.winter_shelters || '',
                colony.notes || '',
                colony.created_date || ''
            ]);

            const csvContent = [csvHeaders, ...csvRows]
                .map(row => row.map(field => `"${String(field).replace(/"/g, '""')}"`).join(','))
                .join('\n');

            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `colony-data-${new Date().toISOString().split('T')[0]}.csv`;
            a.click();
            window.URL.revokeObjectURL(url);

            this.showAlert('Colony data exported successfully!', 'success');
        },

    });

})();