/**
 * CLAWS Main Application JavaScript
 * Handles all frontend functionality for the CLAWS app
 */

(function($) {
    'use strict';

    // Constants and Configuration
    const CLAWS_CONSTANTS = {
        // Color Scheme
        COLORS: {
            // UI Colors
            GRAY_600: '#6b7280',
            GRAY_200: '#e5e7eb',
            GRAY_100: '#f3f4f6',
            GRAY_50: '#f9fafb',
            WHITE: '#ffffff',
            
            // Status Colors  
            SUCCESS: '#10b981',
            ERROR: '#ef4444',
            WARNING: '#f59e0b',
            INFO: '#3b82f6',
            
            // Health Score Colors
            EXCELLENT: '#22c55e',  // green
            GOOD: '#4ade80',       // light green
            FAIR: '#eab308',       // yellow
            POOR: '#f97316',       // orange
            CRITICAL: '#ef4444',   // red
            
            // Chart Colors
            CHART_COLORS: [
                '#E53E3E', '#FF8C00', '#FFD700', '#38A169', 
                '#3182CE', '#4C51BF', '#9F7AEA', '#ec4899'
            ],
            
            // Team/Role Colors
            ADMINISTRATOR: '#dc2626',
            COORDINATOR: '#7c3aed',
            VOLUNTEER: '#059669',
            
            // Activity Colors
            FEEDING: '#10b981',
            SHELTER_BUILDS: '#f59e0b',
            EDUCATION: '#8b5cf6',
            ADMINISTRATION: '#ef4444',
            TRAINING: '#3b82f6',
            MEDICAL: '#ec4899'
        },
        
        // Health Score Thresholds
        HEALTH_THRESHOLDS: {
            EXCELLENT: 80,
            GOOD: 60,
            FAIR: 40
        },
        
        // App Configuration
        VERSION: '1.2.0',
        
        // Chart Configuration
        CHART_DEFAULTS: {
            BORDER_WIDTH: 2,
            POINT_RADIUS: 4,
            FONT_SIZE: 12
        },
        
        // Element IDs
        ELEMENT_IDS: {
            COLONY_CONTENT: 'claws-colony-content',
            COLONY_NAME: 'claws-colony-name',
            COLONY_DATE: 'claws-colony-date',
            TOTAL_COLONIES: 'claws-total-colonies',
            TOTAL_CATS: 'claws-total-cats',
            COLONY_MAP: 'claws-colony-map',
            COLONY_HEALTH_LIST: 'claws-colony-health-list'
        }
    };

    // Global CLAWS App Object
    window.CLAWSApp = {
        
        // App state
        currentTab: 'colony',
        currentVolunteerSubTab: 'mytime',
        colonies: [],
        intakeRecords: [],
        dischargeRecords: [],
        feedingRecords: [],
        babyKittens: [],
        
        // Map and chart objects
        colonyMap: null,
        colonyChart: null,
        colonyHistoryChart: null,
        colonyMarkers: [],
        
        // Intake/Discharge chart objects
        intakeTypeChart: null,
        intakeGenderChart: null,
        intakeAgeChart: null,
        dischargeOutcomeChart: null,
        
        // Neonate care objects
        neonateWeightChart: null,
        selectedAgeRange: '0-1-weeks',
        ageRangeStartDate: null,
        chartDisplayMode: 'sawtooth', // 'sawtooth' or 'smooth'
        
        // Form state
        currentCoordinates: { lat: null, lng: null },
        
        // Configuration
        config: {
            isLoggedIn: false,
            demoMode: true,
            apiUrl: '/wp-json/claws/v1/',
            nonce: '',
            loginUrl: '/wp-login.php'
        },

        /**
         * Get master header colors from CSS custom properties
         */
        getMasterColors: function() {
            const computedStyle = getComputedStyle(document.documentElement);
            return {
                primary: computedStyle.getPropertyValue('--claws-master-bg-primary').trim(),
                secondary: computedStyle.getPropertyValue('--claws-master-bg-secondary').trim(),
                textColor: computedStyle.getPropertyValue('--claws-master-text-color').trim(),
                accentColor: computedStyle.getPropertyValue('--claws-master-accent-color').trim(),
                background: computedStyle.getPropertyValue('--claws-master-bg').trim()
            };
        },


        /**
         * Initialize the CLAWS app
         */
        initialize: function() {
            console.log(`Initializing CLAWS App v${CLAWS_CONSTANTS.VERSION}...`);
            
            // Load configuration from WordPress
            this.loadConfig();
            
            // Initialize components
            this.initializeIcons();
            this.initializeEventListeners();
            
            // Load initial data and UI
            this.switchTab('colony');
            
            console.log('CLAWS App initialized successfully');
        },

        /**
         * Load configuration from WordPress localized data
         */
        loadConfig: function() {
            if (typeof clawsData !== 'undefined') {
                this.config = {
                    ...this.config,
                    ...clawsData,
                    demoMode: !clawsData.isLoggedIn
                };
            }
            
            // Update UI based on login status
            this.updateLoginStatus();
        },

        /**
         * Update UI based on login status
         */
        updateLoginStatus: function() {
            const userStatus = document.getElementById('claws-user-status');
            const demoBanner = document.getElementById('claws-demo-banner');
            const colonyActions = document.getElementById('claws-colony-actions');
            
            if (userStatus) {
                if (this.config.isLoggedIn) {
                    // Check if user is a pure subscriber
                    const isPureSubscriber = this.config.userRoles && 
                        this.config.userRoles.includes('subscriber') &&
                        !this.config.userRoles.includes('contributor') &&
                        !this.config.userRoles.includes('author') &&
                        !this.config.userRoles.includes('administrator');
                        
                    if (isPureSubscriber) {
                        userStatus.innerHTML = `<span style="color: #f59e0b;">Logged In: ${this.config.currentUser} | ⚠️ View-Only Access - Contact admin for more permissions</span>`;
                        // Hide colony actions for pure subscribers
                        if (colonyActions) {
                            colonyActions.style.display = 'none';
                        }
                    } else {
                        userStatus.innerHTML = `<span style="color: #86efac;">Logged In: ${this.config.currentUser}</span>`;
                        // Show colony actions for contributors/authors/admins
                        if (colonyActions) {
                            colonyActions.style.display = 'block';
                        }
                    }
                } else {
                    userStatus.innerHTML = '<span style="color: #fca5a5;">Demo Mode</span>';
                    // Hide colony actions when not logged in
                    if (colonyActions) {
                        colonyActions.style.display = 'none';
                    }
                }
            }
            
            if (demoBanner) {
                demoBanner.style.display = this.config.demoMode ? 'block' : 'none';
            }
        },

        /**
         * Initialize Lucide icons
         */
        initializeIcons: function() {
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        },

        /**
         * Initialize event listeners
         */
        initializeEventListeners: function() {
            // Tab switching
            document.addEventListener('click', (e) => {
                if (e.target.matches('[onclick*="switchTab"]')) {
                    e.preventDefault();
                    const tabName = e.target.getAttribute('onclick').match(/switchTab\('(\w+)'\)/)[1];
                    this.switchTab(tabName);
                }
            });

            // Modal close on backdrop click
            document.addEventListener('click', (e) => {
                if (e.target.matches('.claws-modal-backdrop') || e.target.id === 'claws-add-colony-modal') {
                    this.hideAddColonyForm();
                }
            });
        },

        /**
         * Switch between app tabs
         */
        switchTab: function(tabName) {
            console.log(`Switching to tab: ${tabName}`);
            
            // Update tab buttons - now using CSS classes for inheritance
            document.querySelectorAll('[id^="claws-tab-"]').forEach(btn => {
                btn.classList.remove('claws-tab-active', 'claws-child-header');
                btn.style.background = 'transparent';
                btn.style.color = CLAWS_CONSTANTS.COLORS.GRAY_600;
            });
            
            const activeTab = document.getElementById(`claws-tab-${tabName}`);
            if (activeTab) {
                activeTab.classList.add('claws-tab-active', 'claws-child-header');
                // Remove inline styles - let CSS classes handle colors
                activeTab.style.background = '';
                activeTab.style.color = '';
            }
            
            // Hide all content sections
            document.querySelectorAll('.claws-content-section').forEach(section => {
                section.classList.add('claws-section-hidden');
            });
            
            // Show/hide map based on tab
            const mapContainer = document.getElementById('claws-map-container');
            if (mapContainer) {
                mapContainer.style.display = tabName === 'colony' ? 'block' : 'none';
            }
            
            // Show selected section
            const targetSection = document.getElementById(`claws-${tabName}-section`);
            if (targetSection) {
                targetSection.classList.remove('claws-section-hidden');
            }
            
            // Load content for the selected tab
            this.currentTab = tabName;
            this.loadTabContent(tabName);
        },

        /**
         * Load content for specific tab - RE-ENABLED SAFELY
         */
        loadTabContent: function(tabName) {
            console.log(`Loading tab content: ${tabName}`);
            switch(tabName) {
                case 'colony':
                    this.initColonyTracker();
                    break;
                case 'intake':
                    this.initIntakeDischarge('intake');
                    break;
                case 'discharge':
                    this.initIntakeDischarge('discharge');
                    break;
                case 'neonate':
                    // Check if neonate section exists (it may be hidden by admin settings)
                    if (document.getElementById('claws-neonate-section')) {
                        this.initNeonateCare();
                    } else {
                        console.log('Neonate care section is disabled');
                        return;
                    }
                    break;
                case 'volunteers':
                    // Check if volunteers section exists (role-based visibility)
                    if (document.getElementById('claws-volunteers-section')) {
                        this.initVolunteers();
                    } else {
                        console.log('Volunteers section is not available for this user role');
                        return;
                    }
                    break;
            }
        },

        /**
         * Initialize Colony Tracker
         */
        initColonyTracker: function() {
            console.log('Initializing Colony Tracker...');
            
            // Initialize map
            setTimeout(() => {
                this.initializeMap();
            }, 100);
            
            // Load colonies
            this.loadColonies();
        },

        /**
         * 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);

                // Default center point - no marker needed

                console.log('Map initialized successfully');
                
                // Update markers with current colony data
                this.updateMapMarkers();
                
            } catch (error) {
                console.error('Map initialization error:', 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>';
            }
        },

        /**
         * Load colonies from API or use demo data
         */
        loadColonies: async function() {
            try {
                // HARD BLOCK: Pure subscribers (not contributors/authors/admins) see NO 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 cacheBuster = new Date().getTime();
                const apiUrl = this.config.apiUrl + 'colonies?_cb=' + cacheBuster;
                
                const response = await fetch(apiUrl, {
                    cache: 'no-cache',
                    headers: {
                        'Cache-Control': 'no-cache',
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (response.ok) {
                    this.colonies = await response.json();
                } else {
                    throw new Error('Failed to load from API: ' + response.status);
                }
            } catch (error) {
                console.log('Using demo data:', error);
                this.loadDemoColonies();
            }
            
            this.updateColonyUI();
        },

        /**
         * Load demo colony data (empty - real data will be loaded from API)
         */
        loadDemoColonies: function() {
            this.colonies = [];
        },

        /**
         * Update all colony-related UI elements
         */
        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;
        },

        /**
         * Update map markers
         */
        updateMapMarkers: function() {
            if (!this.colonyMap) return;
            
            // Clear existing colony markers
            this.colonyMarkers.forEach(marker => {
                this.colonyMap.removeLayer(marker);
            });
            this.colonyMarkers = [];
            
            // HARD BLOCK: Pure subscribers see NO map pins whatsoever
            const isPureSubscriber = clawsData.userRoles && 
                clawsData.userRoles.includes('subscriber') &&
                !clawsData.userRoles.includes('contributor') &&
                !clawsData.userRoles.includes('author') &&
                !clawsData.userRoles.includes('administrator');
                
            if (isPureSubscriber) {
                return; // Exit early, no markers added
            }
            
            // Add markers for each colony
            this.colonies.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.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>Health Score:</span>
                                    <span style="font-weight: 500;">${healthScore}%</span>
                                </div>
                                <div style="display: flex; justify-content: space-between;">
                                    <span>TNR Progress:</span>
                                    <span>${Math.round(((colony.tippedEars || 0) / Math.max((colony.cats || 1) - (colony.babies || 0), 1)) * 100)}%</span>
                                </div>
                                <div style="display: flex; justify-content: space-between;">
                                    <span>Added by:</span>
                                    <span>${colony.addedBy || 'Unknown'}</span>
                                </div>
                            </div>
                            <button onclick="CLAWSApp.viewColonyDetails(${colony.id})" style="margin-top: 0.5rem; padding: 0.25rem 0.75rem; background: var(--claws-primary, #2563eb); color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">
                                View Details
                            </button>
                        </div>
                    `);
                    
                    this.colonyMarkers.push(marker);
                }
            });
        },

        /**
         * Update pie chart
         */
        updatePieChart: function() {
            const canvas = document.getElementById('claws-colony-pie-chart');
            if (!canvas) {
                // Create pie chart container if it doesn't exist
                this.createPieChartContainer();
                return;
            }
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.colonyChart) {
                this.colonyChart.destroy();
            }
            
            if (this.colonies.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No colonies to display', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            // Prepare chart data using Roy G. Biv color system
            const chartData = this.colonies.map((colony, index) => ({
                label: colony.name,
                data: colony.cats || 0,
                backgroundColor: this.getChartColor(index),
                borderColor: '#ffffff',
                borderWidth: 2
            }));
            
            this.colonyChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map((d, index) => {
                            return CLAWSApp.getChartColor(index);
                        }),
                        borderColor: chartData.map(d => d.borderColor),
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((context.raw / total) * 100).toFixed(1);
                                    return `${context.label}: ${context.raw} cats (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
            
            // Update legend
            this.updateChartLegend(chartData);
        },

        /**
         * Create pie chart container
         */
        createPieChartContainer: function() {
            const colonyContent = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_CONTENT);
            if (!colonyContent) return;
            
            const pieChartHTML = `
                <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: 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" style="max-height: 250px;"></canvas>
                    </div>
                    <div id="claws-chart-legend" style="margin-top: 1rem; font-size: 0.75rem; color: #6b7280;">
                        <!-- Legend will be populated here -->
                    </div>
                </div>
            `;
            
            // Insert pie chart after statistics
            const existingPieChart = document.getElementById('claws-colony-pie-chart');
            if (!existingPieChart) {
                colonyContent.insertAdjacentHTML('beforeend', pieChartHTML);
                // REMOVED: setTimeout(() => this.updatePieChart(), 100); - this causes infinite loops!
                console.log('Pie chart container created, chart will be updated on next data load');
            }
        },

        /**
         * Create colony history chart container
         */
        createColonyHistoryChartContainer: function() {
            const colonyContent = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_CONTENT);
            if (!colonyContent) return;
            
            const historyChartHTML = `
                <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: 1rem;">
                    <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; font-size: 0.875rem; text-align: center;">Colony Population History</h3>
                    <div style="position: relative; height: 400px; display: flex; align-items: center; justify-content: center;">
                        <canvas id="colony-history-chart" style="max-height: 400px;"></canvas>
                    </div>
                    <div style="margin-top: 1rem; font-size: 0.75rem; color: #6b7280; text-align: center;">
                        <p>Track changes in colony population, TNR progress, and shelter availability over time</p>
                    </div>
                </div>
            `;
            
            // Insert history chart after pie chart
            const existingHistoryChart = document.getElementById('colony-history-chart');
            if (!existingHistoryChart) {
                colonyContent.insertAdjacentHTML('beforeend', historyChartHTML);
                // Load and display history for the first colony as an example
                if (this.colonies.length > 0) {
                    this.loadAndDisplayColonyHistory(this.colonies[0].id);
                }
            }
        },

        /**
         * Load and display colony history for a specific colony
         */
        loadAndDisplayColonyHistory: async function(colonyId) {
            this.trackCall('loadAndDisplayColonyHistory');
            try {
                const historyData = await this.loadColonyHistory(colonyId);
                this.updateColonyHistoryChart(colonyId, historyData);
            } catch (error) {
                console.error('Error loading colony history:', error);
            }
        },

        /**
         * Update chart legend
         */
        updateChartLegend: function(chartData) {
            const legendContainer = document.getElementById('claws-chart-legend');
            if (!legendContainer) return;
            
            const total = chartData.reduce((sum, item) => sum + item.data, 0);
            
            legendContainer.innerHTML = chartData.map(item => {
                const percentage = total > 0 ? ((item.data / total) * 100).toFixed(1) : 0;
                return `
                    <div style="display: flex; align-items: center; justify-content: space-between; padding: 0.25rem 0;">
                        <div style="display: flex; align-items: center;">
                            <div style="width: 12px; height: 12px; background: ${item.backgroundColor}; border-radius: 2px; margin-right: 0.5rem;"></div>
                            <span>${item.label}</span>
                        </div>
                        <span>${item.data} cats (${percentage}%)</span>
                    </div>
                `;
            }).join('');
        },

        /**
         * Update intake charts (type, gender, age)
         */
        updateIntakeCharts: function() {
            // SIMPLIFIED - no color updates to prevent loops
            this.updateIntakeTypeChart();
            this.updateIntakeGenderChart();
            this.updateIntakeAgeChart();
        },

        /**
         * Update intake type pie chart
         */
        updateIntakeTypeChart: function() {
            const canvas = document.getElementById('claws-intake-type-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.intakeTypeChart) {
                this.intakeTypeChart.destroy();
            }
            
            // Count by type
            const typeCounts = {};
            this.intakeRecords.forEach(record => {
                const type = record.type || 'Unknown';
                typeCounts[type] = (typeCounts[type] || 0) + 1;
            });
            
            const chartData = Object.entries(typeCounts).map(([type, count], index) => ({
                label: type,
                data: count,
                backgroundColor: this.getChartColor(index)
            }));
            
            if (chartData.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No intake data', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.intakeTypeChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor),
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        },

        /**
         * Update intake gender pie chart
         */
        updateIntakeGenderChart: function() {
            const canvas = document.getElementById('claws-intake-gender-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.intakeGenderChart) {
                this.intakeGenderChart.destroy();
            }
            
            // Count by gender
            const genderCounts = {};
            this.intakeRecords.forEach(record => {
                const gender = record.gender || 'Unknown';
                genderCounts[gender] = (genderCounts[gender] || 0) + 1;
            });
            
            const chartData = Object.entries(genderCounts).map(([gender, count], index) => ({
                label: gender,
                data: count,
                backgroundColor: this.getChartColor(index)
            }));
            
            if (chartData.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No intake data', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.intakeGenderChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor),
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        },

        /**
         * Update intake age pie chart
         */
        updateIntakeAgeChart: function() {
            const canvas = document.getElementById('claws-intake-age-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.intakeAgeChart) {
                this.intakeAgeChart.destroy();
            }
            
            // Count by age
            const ageCounts = {};
            this.intakeRecords.forEach(record => {
                const age = record.age || 'Unknown';
                ageCounts[age] = (ageCounts[age] || 0) + 1;
            });
            
            const chartData = Object.entries(ageCounts).map(([age, count], index) => ({
                label: age,
                data: count,
                backgroundColor: this.getChartColor(index)
            }));
            
            if (chartData.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No intake data', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.intakeAgeChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor),
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        },

        /**
         * Update discharge charts
         */
        updateDischargeCharts: function() {
            this.updateDischargeOutcomeChart();
        },

        /**
         * Update discharge outcome pie chart
         */
        updateDischargeOutcomeChart: function() {
            const canvas = document.getElementById('claws-discharge-outcome-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.dischargeOutcomeChart) {
                this.dischargeOutcomeChart.destroy();
            }
            
            // Count by outcome
            const outcomeCounts = {};
            this.dischargeRecords.forEach(record => {
                const outcome = record.outcome || 'Unknown';
                outcomeCounts[outcome] = (outcomeCounts[outcome] || 0) + 1;
            });
            
            const chartData = Object.entries(outcomeCounts).map(([outcome, count], index) => ({
                label: outcome,
                data: count,
                backgroundColor: this.getChartColor(index)
            }));
            
            if (chartData.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No discharge data', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.dischargeOutcomeChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map((d, index) => {
                            return CLAWSApp.getChartColor(index);
                        }),
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        },

        /**
         * Get chart color by index
         */
        getChartColor: function(index) {
            return CLAWS_CONSTANTS.COLORS.CHART_COLORS[index % CLAWS_CONSTANTS.COLORS.CHART_COLORS.length];
        },

        /**
         * Render colony content (statistics, actions, etc.)
         */
        renderColonyContent: function() {
            const colonyContent = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_CONTENT);
            if (!colonyContent) return;
            
            const totalColonies = this.colonies.length;
            
            // Show message when no colonies are available
            if (totalColonies === 0) {
                if (!clawsData.isLoggedIn) {
                    colonyContent.innerHTML = `
                        <div style="text-align: center; padding: 3rem 1rem; color: #6b7280;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">🔒</div>
                            <h3 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem;">Login Required</h3>
                            <p style="margin: 0;">Please log in to view colony data and access all features.</p>
                        </div>
                    `;
                } else {
                    colonyContent.innerHTML = `
                        <div style="text-align: center; padding: 3rem 1rem; color: #6b7280;">
                            <div style="font-size: 3rem; margin-bottom: 1rem;">📍</div>
                            <h3 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem;">No Colonies Available</h3>
                            <p style="margin: 0 0 2rem;">You haven't created any colonies yet and none have been assigned to you. Click "Add New Colony" to get started!</p>
                            
                            <div style="max-width: 300px; margin: 0 auto;">
                                <div class="claws-child-header" style="border-radius: 1rem; padding: 1.5rem;">
                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                                        <h3 style="font-weight: 600; font-size: 1.125rem; margin: 0; color: inherit;">Quick Actions</h3>
                                        <span style="font-size: 1.5rem;">➕</span>
                                    </div>
                                    <button onclick="CLAWSApp.showAddColonyForm(); console.log('Add Colony button clicked!');" style="width: 100%; background: rgba(255, 255, 255, 0.2); border: none; border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; transition: background 0.2s; text-align: left; color: inherit;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                                        <span style="font-weight: 500;">🏠 Add New Colony</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;
                }
                return;
            }
            
            const totalCats = this.colonies.reduce((sum, colony) => sum + (colony.cats || 0), 0);
            
            colonyContent.innerHTML = `
                <!-- Statistics Cards -->
                <div style="padding: 0 1rem;">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <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;">
                            <div style="width: 3rem; height: 3rem; background: #dbeafe; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin-bottom: 1rem;">
                                <span style="color: #2563eb; font-size: 1.5rem;">📍</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.5rem; font-size: 0.875rem;">Active Colonies</h3>
                            <p style="font-size: 1.875rem; font-weight: bold; color: #2563eb; margin: 0;" id="claws-total-colonies">${totalColonies}</p>
                        </div>
                        <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;">
                            <div style="width: 3rem; height: 3rem; background: #dcfce7; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin-bottom: 1rem;">
                                <span style="color: #16a34a; font-size: 1.5rem;">❤️</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.5rem; font-size: 0.875rem;">Cats Tracked</h3>
                            <p style="font-size: 1.875rem; font-weight: bold; color: #16a34a; margin: 0;" id="claws-total-cats">${totalCats}</p>
                        </div>
                    </div>
                </div>
                
                <!-- Colony Health Summary -->
                <div style="padding: 0 1rem; margin-bottom: 1rem;">
                    <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: 1rem;">Colony Health Summary</h3>
                        
                        <!-- Health Status Key -->
                        <div style="margin-bottom: 1rem; padding: 0.75rem; background: #f9fafb; border-radius: 0.5rem;">
                            <p style="font-size: 0.75rem; font-weight: 500; color: #374151; margin: 0 0 0.5rem;">Health Status Key:</p>
                            <div style="display: flex; align-items: center; gap: 1rem; font-size: 0.75rem;">
                                <div style="display: flex; align-items: center;">
                                    <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; background: #ef4444; margin-right: 0.25rem;"></span>
                                    <span style="color: #6b7280;">Action Needed</span>
                                </div>
                                <div style="display: flex; align-items: center;">
                                    <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; background: #eab308; margin-right: 0.25rem;"></span>
                                    <span style="color: #6b7280;">Monitor</span>
                                </div>
                                <div style="display: flex; align-items: center;">
                                    <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; background: #22c55e; margin-right: 0.25rem;"></span>
                                    <span style="color: #6b7280;">Good</span>
                                </div>
                            </div>
                        </div>

                        <!-- Colony List -->
                        <div id="claws-colony-health-list" style="display: flex; flex-direction: column; gap: 0.75rem;">
                            <!-- Colony health items will be populated here -->
                        </div>
                    </div>
                </div>
                
                <!-- Quick Actions -->
                <div style="padding: 1rem;">
                    <div class="claws-child-header" style="border-radius: 1rem; padding: 1.5rem;">
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h3 style="font-weight: 600; font-size: 1.125rem; margin: 0; color: inherit;">Quick Actions</h3>
                            <span style="font-size: 1.5rem;">➕</span>
                        </div>
                        <button onclick="CLAWSApp.showAddColonyForm(); console.log('Add Colony button clicked!');" style="width: 100%; background: rgba(255, 255, 255, 0.2); border: none; border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; transition: background 0.2s; text-align: left; color: inherit;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                            <span style="font-weight: 500;">🏠 Add New Colony</span>
                        </button>
                    </div>
                </div>
            `;
            
            // Update colony health summary
            this.updateColonyHealthList();
            
            // Add pie chart
            this.createPieChartContainer();
            
            // Add colony history chart
            this.createColonyHistoryChartContainer();
        },

        /**
         * Check if current user can edit a specific colony
         */
        canUserEditColony: function(colony) {
            // Not logged in - cannot edit
            if (!clawsData.isLoggedIn) {
                return false;
            }
            
            // Admins can edit any colony
            if (clawsData.isAdmin) {
                return true;
            }
            
            // Users can edit colonies they created
            if (colony.addedByUserId && colony.addedByUserId == clawsData.userId) {
                return true;
            }
            
            // Users can edit colonies assigned to them
            if (colony.assignedUserId && colony.assignedUserId == clawsData.userId) {
                return true;
            }
            
            return false;
        },

        /**
         * Calculate colony health score
         */
        calculateHealthScore: function(colony) {
            if (!colony.cats || colony.cats === 0) return 0;
            
            const tnrEligible = Math.max(colony.cats - (colony.babies || 0), 1);
            const tnrProgress = ((colony.tippedEars || 0) / tnrEligible) * 100;
            
            const shelterNeeded = Math.max((colony.adults || 0) + (colony.seniors || 0), 1);
            const shelterProgress = ((colony.winterShelters || 0) / shelterNeeded) * 100;
            
            const securityScores = {
                'Insufficient': 20, 'Dangerous': 20,
                'Marginal': 40, 'Unsafe': 40,
                'Sufficient': 60, 'Somewhat Safe': 60,
                'Good': 80, 'Safe': 80,
                'Very Good': 100, 'Very Safe': 100
            };
            
            const foodScore = securityScores[colony.foodSecurity] || 0;
            const waterScore = securityScores[colony.waterSecurity] || 0;
            const safetyScore = securityScores[colony.safeLocation] || 0;
            
            return Math.round((Math.min(tnrProgress, 100) + Math.min(shelterProgress, 100) + foodScore + waterScore + safetyScore) / 5);
        },

        /**
         * Update colony health summary list
         */
        updateColonyHealthList: function() {
            const healthList = document.getElementById('claws-colony-health-list');
            if (!healthList) return;
            
            healthList.innerHTML = '';

            this.colonies.forEach(colony => {
                const tnrEligible = Math.max(colony.cats - (colony.babies || 0), 1);
                const tnrRatio = Math.round(((colony.tippedEars || 0) / tnrEligible) * 100);
                const adultsAndSeniors = (colony.adults || 0) + (colony.seniors || 0);
                const shelterRatio = adultsAndSeniors > 0 ? Math.round(((colony.winterShelters || 0) / adultsAndSeniors) * 100) : 0;
                const totalHealth = this.calculateHealthScore(colony);

                const colonyCard = document.createElement('div');
                colonyCard.style.cssText = `
                    padding: 0.75rem;
                    border: 1px solid #e5e7eb;
                    border-radius: 0.5rem;
                    cursor: pointer;
                    transition: all 0.2s ease-in-out;
                `;
                colonyCard.onclick = () => this.viewColonyDetails(colony.id);
                
                // Add hover effect
                colonyCard.onmouseenter = () => {
                    colonyCard.style.transform = 'translateY(-2px)';
                    colonyCard.style.boxShadow = '0 10px 25px rgba(0, 0, 0, 0.1)';
                };
                colonyCard.onmouseleave = () => {
                    colonyCard.style.transform = 'translateY(0)';
                    colonyCard.style.boxShadow = 'none';
                };
                
                colonyCard.innerHTML = `
                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem;">
                        <h4 style="font-weight: 500; color: #1f2937; margin: 0; font-size: 0.875rem;">${colony.name}</h4>
                        <span style="font-size: 0.75rem; color: #6b7280;">${colony.cats} cats</span>
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 0.25rem; font-size: 0.75rem; margin-bottom: 0.5rem;">
                        <div style="display: flex; align-items: center;">
                            <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; margin-right: 0.25rem; background: ${this.getProgressColor(tnrRatio)};"></span>
                            <span style="font-size: 0.6rem;">TNR: ${tnrRatio}%</span>
                        </div>
                        <div style="display: flex; align-items: center;">
                            <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; margin-right: 0.25rem; background: ${this.getProgressColor(shelterRatio)};"></span>
                            <span style="font-size: 0.6rem;">Shelter: ${shelterRatio}%</span>
                        </div>
                        <div style="display: flex; align-items: center;">
                            <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; margin-right: 0.25rem; background: ${this.getSecurityColor(colony.foodSecurity)};"></span>
                            <span style="font-size: 0.6rem;">Food</span>
                        </div>
                        <div style="display: flex; align-items: center;">
                            <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; margin-right: 0.25rem; background: ${this.getSecurityColor(colony.waterSecurity)};"></span>
                            <span style="font-size: 0.6rem;">Water</span>
                        </div>
                        <div style="display: flex; align-items: center;">
                            <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; margin-right: 0.25rem; background: ${this.getSecurityColor(colony.safeLocation)};"></span>
                            <span style="font-size: 0.6rem;">Safety</span>
                        </div>
                    </div>
                    <div style="padding-top: 0.5rem; border-top: 1px solid #f3f4f6;">
                        <div style="display: flex; align-items: center; justify-content: space-between; font-size: 0.75rem;">
                            <span style="font-weight: 500; color: #374151;">Total Colony Health:</span>
                            <div style="display: flex; align-items: center;">
                                <span style="width: 0.5rem; height: 0.5rem; border-radius: 50%; margin-right: 0.25rem; background: ${this.getProgressColor(totalHealth)};"></span>
                                <span style="font-weight: 500; color: #1f2937;">${totalHealth}%</span>
                            </div>
                        </div>
                    </div>
                `;
                
                healthList.appendChild(colonyCard);
            });
        },

        /**
         * Get progress color based on percentage
         */
        getProgressColor: function(percentage) {
            if (percentage >= CLAWS_CONSTANTS.HEALTH_THRESHOLDS.EXCELLENT) return CLAWS_CONSTANTS.COLORS.EXCELLENT;
            if (percentage >= CLAWS_CONSTANTS.HEALTH_THRESHOLDS.GOOD) return CLAWS_CONSTANTS.COLORS.FAIR;
            if (percentage >= CLAWS_CONSTANTS.HEALTH_THRESHOLDS.FAIR) return CLAWS_CONSTANTS.COLORS.POOR;
            return CLAWS_CONSTANTS.COLORS.CRITICAL;
        },

        /**
         * Get security color based on level
         */
        getSecurityColor: function(level) {
            const colors = {
                'Very Good': CLAWS_CONSTANTS.COLORS.EXCELLENT, 'Very Safe': CLAWS_CONSTANTS.COLORS.EXCELLENT,
                'Good': CLAWS_CONSTANTS.COLORS.GOOD, 'Safe': CLAWS_CONSTANTS.COLORS.GOOD,
                'Sufficient': CLAWS_CONSTANTS.COLORS.POOR, 'Somewhat Safe': CLAWS_CONSTANTS.COLORS.POOR,
                'Marginal': '#fb7185', 'Unsafe': '#fb7185',
                'Insufficient': CLAWS_CONSTANTS.COLORS.CRITICAL, 'Dangerous': CLAWS_CONSTANTS.COLORS.CRITICAL
            };
            return colors[level] || CLAWS_CONSTANTS.COLORS.GRAY_600;
        },

        /**
         * Show add colony form
         */
        showAddColonyForm: function() {
            if (this.config.demoMode) {
                const proceed = confirm('You are in demo mode. Your changes will not be saved permanently. Continue?');
                if (!proceed) return;
            }
            
            const modal = document.getElementById('claws-add-colony-modal');
            if (modal) {
                modal.style.display = 'flex';
                this.resetColonyForm();
                this.setupFormEventListeners();
                
                // Initialize the form map after modal is shown
                setTimeout(() => {
                    this.initializeFormMap();
                }, 100);
            }
        },

        /**
         * Hide add colony form
         */
        hideAddColonyForm: function() {
            const modal = document.getElementById('claws-add-colony-modal');
            if (modal) {
                modal.style.display = 'none';
                
                // Clean up form map
                if (this.formMap) {
                    this.formMap.remove();
                    this.formMap = null;
                    this.formMarker = null;
                }
            }
        },

        /**
         * Initialize the form map for manual pin placement
         */
        initializeFormMap: function() {
            const mapElement = document.getElementById('claws-form-map');
            if (!mapElement || this.formMap) {
                return;
            }
            
            try {
                // Use configured default coordinates from settings
                const defaultLat = this.config.defaultLatitude || 39.8283; // US center fallback
                const defaultLng = this.config.defaultLongitude || -98.5795; // US center fallback
                const defaultCenter = [defaultLat, defaultLng];
                
                this.formMap = L.map('claws-form-map').setView(defaultCenter, 15);
                
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors',
                    maxZoom: 18
                }).addTo(this.formMap);

                // Click handler for placing pins
                this.formMap.on('click', (e) => {
                    const lat = e.latlng.lat;
                    const lng = e.latlng.lng;
                    
                    // Remove existing marker
                    if (this.formMarker) {
                        this.formMap.removeLayer(this.formMarker);
                    }
                    
                    // Add new marker
                    this.formMarker = L.marker([lat, lng]).addTo(this.formMap);
                    
                    // Update coordinates display
                    document.getElementById('claws-selected-coords').textContent = 
                        `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
                    
                    // Store coordinates for form submission
                    this.selectedCoordinates = { lat, lng };
                });
                
                console.log('Form map initialized successfully');
                
            } catch (error) {
                console.error('Form map initialization error:', error);
            }
        },

        /**
         * Reset colony form to default values
         */
        resetColonyForm: function() {
            document.getElementById('claws-colony-name').value = '';
            // Set date field to today's date
            document.getElementById('claws-colony-date').value = new Date().toISOString().split('T')[0];
            document.getElementById('claws-colony-street').value = '';
            document.getElementById('claws-colony-city').value = '';
            document.getElementById('claws-colony-state').value = '';
            document.getElementById('claws-colony-zip').value = '';
            document.getElementById('claws-babies-count').value = '0';
            document.getElementById('claws-kittens-count').value = '0';
            document.getElementById('claws-adults-count').value = '0';
            document.getElementById('claws-seniors-count').value = '0';
            document.getElementById('claws-tipped-ears').value = '';
            document.getElementById('claws-winter-shelters').value = '';
            document.getElementById('claws-food-security').value = '';
            document.getElementById('claws-water-security').value = '';
            document.getElementById('claws-safe-location').value = '';
            document.getElementById('claws-capture-method').value = '';
            document.getElementById('claws-vaccinated-count').value = '';
            document.getElementById('claws-microchip-count').value = '';
            document.getElementById('claws-tnr-no-tipping').checked = false;
            document.getElementById('claws-help-feed').checked = false;
            document.getElementById('claws-help-trap').checked = false;
            document.getElementById('claws-help-house-pre').checked = false;
            document.getElementById('claws-help-transport-to').checked = false;
            document.getElementById('claws-help-transport-from').checked = false;
            document.getElementById('claws-help-recovery').checked = false;
            document.getElementById('claws-help-monitor').checked = false;
            document.getElementById('claws-help-return').checked = false;
            document.getElementById('claws-help-watch').checked = false;
            document.getElementById('claws-help-donate').checked = false;
            document.getElementById('claws-assign-user').value = '';
            document.getElementById('claws-selected-coords').textContent = 'Click map to select';
            this.selectedCoordinates = null;
            
            // Reset colony help checkboxes
            document.querySelectorAll('.claws-help-option').forEach(checkbox => {
                checkbox.checked = false;
            });
            
            // Reset caregiver fields - keep only the first caregiver entry and clear it
            const caregiverContainer = document.getElementById('claws-caregivers-container');
            if (caregiverContainer) {
                const caregiverEntries = caregiverContainer.querySelectorAll('.claws-caregiver-entry');
                
                // Remove all additional caregiver entries (keep first one)
                for (let i = 1; i < caregiverEntries.length; i++) {
                    caregiverEntries[i].remove();
                }
                
                // Clear the first caregiver entry
                if (caregiverEntries[0]) {
                    const firstEntry = caregiverEntries[0];
                    firstEntry.querySelector('.claws-caregiver-name').value = '';
                    firstEntry.querySelector('.claws-caregiver-email').value = '';
                    firstEntry.querySelector('.claws-caregiver-phone').value = '';
                    firstEntry.querySelector('.claws-caregiver-public').checked = true;
                    
                    // Reset contact method checkboxes
                    const textCheckbox = firstEntry.querySelector('.claws-caregiver-contact-text');
                    const emailCheckbox = firstEntry.querySelector('.claws-caregiver-contact-email');
                    const phoneCheckbox = firstEntry.querySelector('.claws-caregiver-contact-phone');
                    if (textCheckbox) textCheckbox.checked = false;
                    if (emailCheckbox) emailCheckbox.checked = false;
                    if (phoneCheckbox) phoneCheckbox.checked = false;
                }
            }
            
            this.updateFormCalculations();
        },

        /**
         * Edit existing colony - load data into form
         */
        editColony: function(colonyId) {
            console.log('Edit colony function called for ID:', colonyId);
            
            // Find the colony data
            const colony = this.colonies.find(c => c.id === colonyId);
            if (!colony) {
                this.showAlert('Colony not found.', 'error');
                return;
            }
            
            // Close the details modal
            const detailsModal = document.getElementById('claws-colony-details-modal');
            if (detailsModal) {
                detailsModal.remove();
            }
            
            // Show the add colony form (which we'll use for editing)
            this.showAddColonyForm();
            
            // Pre-populate the form with existing data
            setTimeout(() => {
                this.populateColonyForm(colony);
                
                // Update the form title and button text
                const modalHeader = document.querySelector('#claws-add-colony-modal .claws-modal-header h2');
                if (modalHeader) {
                    modalHeader.textContent = 'Edit Colony';
                }
                
                // Change the save button to update mode
                const saveButton = document.querySelector('button[onclick="CLAWSApp.saveColony()"]');
                if (saveButton) {
                    saveButton.textContent = 'Update Colony';
                    saveButton.onclick = () => this.updateColony(colonyId);
                    saveButton.style.background = this.getGradientStyle();
                }
                
                this.showAlert('Colony loaded for editing. Click "Update Colony" to save changes.', 'info');
            }, 100);
        },

        /**
         * Populate colony form with existing data
         */
        populateColonyForm: function(colony) {
            
            // Basic info
            document.getElementById('claws-colony-name').value = colony.name || '';
            
            // Set date to today for this update entry
            document.getElementById('claws-colony-date').value = new Date().toISOString().split('T')[0];
            
            
            // Check if form fields exist
            const streetField = document.getElementById('claws-colony-street');
            const cityField = document.getElementById('claws-colony-city');
            const stateField = document.getElementById('claws-colony-state');
            const zipField = document.getElementById('claws-colony-zip');
            
            
            // Address fields - handle both individual fields and combined address
            if (colony.street || colony.city || colony.state || colony.zip) {
                // Use individual fields if available
                if (streetField) streetField.value = colony.street || '';
                if (cityField) cityField.value = colony.city || '';
                if (stateField) stateField.value = colony.state || '';
                if (zipField) zipField.value = colony.zip || '';
            } else if (colony.address) {
                // Parse combined address if individual fields are empty
                const addressParts = this.parseAddress(colony.address);
                if (streetField) streetField.value = addressParts.street || '';
                if (cityField) cityField.value = addressParts.city || '';
                if (stateField) stateField.value = addressParts.state || '';
                if (zipField) zipField.value = addressParts.zip || '';
            } else {
                // Clear fields if no address data
                if (streetField) streetField.value = '';
                if (cityField) cityField.value = '';
                if (stateField) stateField.value = '';
                if (zipField) zipField.value = '';
            }
            
            
            // Population counts
            document.getElementById('claws-babies-count').value = colony.babies || 0;
            document.getElementById('claws-kittens-count').value = colony.kittens || 0;
            document.getElementById('claws-adults-count').value = colony.adults || 0;
            document.getElementById('claws-seniors-count').value = colony.seniors || 0;
            
            // Health metrics
            document.getElementById('claws-tipped-ears').value = colony.tippedEars || '';
            document.getElementById('claws-winter-shelters').value = colony.winterShelters || '';
            
            // Security selects
            if (colony.foodSecurity) {
                document.getElementById('claws-food-security').value = colony.foodSecurity;
            }
            if (colony.waterSecurity) {
                document.getElementById('claws-water-security').value = colony.waterSecurity;
            }
            if (colony.safeLocation) {
                document.getElementById('claws-safe-location').value = colony.safeLocation;
            }
            
            // Set assigned user
            if (colony.assignedUserId) {
                document.getElementById('claws-assign-user').value = colony.assignedUserId;
            }
            
            // Additional fields
            if (colony.captureMethod) {
                document.getElementById('claws-capture-method').value = colony.captureMethod;
            }
            if (colony.vaccinatedCount !== undefined && colony.vaccinatedCount !== 'unknown') {
                document.getElementById('claws-vaccinated-count').value = colony.vaccinatedCount;
            }
            if (colony.microchipCount !== undefined && colony.microchipCount !== 'unknown') {
                document.getElementById('claws-microchip-count').value = colony.microchipCount;
            }
            if (colony.tnrNoTipping !== undefined) {
                document.getElementById('claws-tnr-no-tipping').checked = colony.tnrNoTipping;
            }
            
            // Set coordinates for map
            if (colony.lat && colony.lng) {
                this.selectedCoordinates = {
                    lat: parseFloat(colony.lat),
                    lng: parseFloat(colony.lng)
                };
                
                // Update map if it's initialized
                setTimeout(() => {
                    if (this.formMap) {
                        this.formMap.setView([this.selectedCoordinates.lat, this.selectedCoordinates.lng], 15);
                        
                        // Clear existing markers and add new one
                        this.formMap.eachLayer(layer => {
                            if (layer instanceof L.Marker) {
                                this.formMap.removeLayer(layer);
                            }
                        });
                        
                        L.marker([this.selectedCoordinates.lat, this.selectedCoordinates.lng])
                            .addTo(this.formMap);
                            
                        // Update coordinates display
                        const coordsDisplay = document.getElementById('claws-selected-coords');
                        if (coordsDisplay) {
                            coordsDisplay.textContent = `${this.selectedCoordinates.lat.toFixed(6)}, ${this.selectedCoordinates.lng.toFixed(6)}`;
                        }
                    }
                }, 200);
            }
            
            // Populate caregivers
            if (colony.caregivers && colony.caregivers.length > 0) {
                // Reset to first caregiver entry and populate it
                const firstCaregiver = colony.caregivers[0];
                const firstEntry = document.querySelector('.claws-caregiver-entry');
                if (firstEntry && firstCaregiver) {
                    firstEntry.querySelector('.claws-caregiver-name').value = firstCaregiver.name || '';
                    firstEntry.querySelector('.claws-caregiver-email').value = firstCaregiver.email || '';
                    firstEntry.querySelector('.claws-caregiver-phone').value = firstCaregiver.phone || '';
                    firstEntry.querySelector('.claws-caregiver-public').checked = firstCaregiver.isPublic !== false;
                }
                
                // Add additional caregivers if there are more than one
                for (let i = 1; i < colony.caregivers.length; i++) {
                    this.addAdditionalCaregiver();
                    
                    // Populate the newly added caregiver
                    setTimeout(() => {
                        const caregiverEntries = document.querySelectorAll('.claws-caregiver-entry');
                        const currentEntry = caregiverEntries[i];
                        if (currentEntry && colony.caregivers[i]) {
                            currentEntry.querySelector('.claws-caregiver-name').value = colony.caregivers[i].name || '';
                            currentEntry.querySelector('.claws-caregiver-email').value = colony.caregivers[i].email || '';
                            currentEntry.querySelector('.claws-caregiver-phone').value = colony.caregivers[i].phone || '';
                            currentEntry.querySelector('.claws-caregiver-public').checked = colony.caregivers[i].isPublic !== false;
                        }
                    }, 50);
                }
            }
            
            // Trigger calculations
            this.updateHealthMetrics();
        },

        /**
         * Parse combined address into components
         */
        parseAddress: function(address) {
            if (!address) return { street: '', city: '', state: '', zip: '' };
            
            console.log('🔍 Parsing address:', address);
            
            // Handle format: "89 Elliot Dr., Lebanon, VA 24266"
            const parts = address.split(',').map(part => part.trim());
            
            let street = '', city = '', state = '', zip = '';
            
            if (parts.length >= 3) {
                // Standard format: Street, City, State Zip
                street = parts[0] || '';
                city = parts[1] || '';
                
                // Parse "VA 24266" into state and zip
                const stateZipPart = parts[2] || '';
                const stateZipMatch = stateZipPart.match(/^([A-Z]{2})\s+(\d{5}(?:-\d{4})?)$/);
                if (stateZipMatch) {
                    state = stateZipMatch[1];
                    zip = stateZipMatch[2];
                } else {
                    // Fallback: treat entire last part as state
                    state = stateZipPart;
                }
            } else if (parts.length === 2) {
                // Format: Street, City/State/Zip
                street = parts[0] || '';
                const remaining = parts[1] || '';
                
                // Try to extract zip from end
                const zipMatch = remaining.match(/(\d{5}(?:-\d{4})?)$/);
                if (zipMatch) {
                    zip = zipMatch[1];
                    const beforeZip = remaining.replace(zipMatch[0], '').trim();
                    
                    // Try to split remaining into city and state
                    const cityStateMatch = beforeZip.match(/^(.+?)\s+([A-Z]{2})$/);
                    if (cityStateMatch) {
                        city = cityStateMatch[1];
                        state = cityStateMatch[2];
                    } else {
                        city = beforeZip;
                    }
                } else {
                    city = remaining;
                }
            } else {
                // Single part - probably just street
                street = address;
            }
            
            const result = { street, city, state, zip };
            console.log('🔍 Parsed result:', result);
            return result;
        },

        /**
         * Setup form event listeners for real-time calculations
         */
        setupFormEventListeners: function() {
            const formInputs = [
                'claws-babies-count', 'claws-kittens-count', 'claws-adults-count', 'claws-seniors-count', 
                'claws-tipped-ears', 'claws-winter-shelters', 'claws-food-security', 'claws-water-security', 'claws-safe-location'
            ];
            
            formInputs.forEach(inputId => {
                const input = document.getElementById(inputId);
                if (input) {
                    // Remove existing listeners to prevent duplicates
                    input.removeEventListener('input', this.updateFormCalculations);
                    input.removeEventListener('change', this.updateFormCalculations);
                    
                    // Add new listeners
                    input.addEventListener('input', () => this.updateFormCalculations());
                    input.addEventListener('change', () => this.updateFormCalculations());
                }
            });
        },

        /**
         * Update form calculations in real-time
         */
        updateFormCalculations: function() {
            const babies = parseInt(document.getElementById('claws-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-kittens-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-adults-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-seniors-count').value) || 0;
            const tippedEars = parseInt(document.getElementById('claws-tipped-ears').value) || 0;
            const winterShelters = parseInt(document.getElementById('claws-winter-shelters').value) || 0;

            const totalCats = babies + kittens + adults + seniors;
            document.getElementById('claws-total-cats-display').textContent = totalCats;

            // TNR Progress
            const tnrEligible = Math.max(totalCats - babies, 1);
            const tnrPercentage = Math.round((tippedEars / tnrEligible) * 100);
            document.getElementById('claws-tnr-percentage').textContent = `${tnrPercentage}%`;
            const tnrBar = document.getElementById('claws-tnr-progress-bar');
            tnrBar.style.width = `${Math.min(tnrPercentage, 100)}%`;
            tnrBar.style.background = this.getProgressColor(tnrPercentage);

            // Shelter Progress
            const shelterNeeded = Math.max(adults + seniors, 1);
            const shelterPercentage = Math.round((winterShelters / shelterNeeded) * 100);
            document.getElementById('claws-shelter-percentage').textContent = `${shelterPercentage}%`;
            const shelterBar = document.getElementById('claws-shelter-progress-bar');
            shelterBar.style.width = `${Math.min(shelterPercentage, 100)}%`;
            shelterBar.style.background = this.getProgressColor(shelterPercentage);

            // Total Health Score
            const foodSecurity = document.getElementById('claws-food-security').value;
            const waterSecurity = document.getElementById('claws-water-security').value;
            const safeLocation = document.getElementById('claws-safe-location').value;

            const securityScores = {
                'Insufficient': 20, 'Dangerous': 20,
                'Marginal': 40, 'Unsafe': 40,
                'Sufficient': 60, 'Somewhat Safe': 60,
                'Good': 80, 'Safe': 80,
                'Very Good': 100, 'Very Safe': 100
            };

            const foodScore = securityScores[foodSecurity] || 0;
            const waterScore = securityScores[waterSecurity] || 0;
            const safetyScore = securityScores[safeLocation] || 0;

            const totalHealth = Math.round((Math.min(tnrPercentage, 100) + Math.min(shelterPercentage, 100) + foodScore + waterScore + safetyScore) / 5);
            document.getElementById('claws-total-health-score').textContent = `${totalHealth}%`;
            const healthBar = document.getElementById('claws-total-health-bar');
            healthBar.style.width = `${totalHealth}%`;
            healthBar.style.background = this.getProgressColor(totalHealth);
        },


        /**
         * Add additional caregiver field to the form
         */
        addAdditionalCaregiver: function() {
            const container = document.getElementById('claws-caregivers-container');
            if (!container) return;
            
            const currentCaregivers = container.querySelectorAll('.claws-caregiver-entry');
            const nextIndex = currentCaregivers.length;
            
            // Create new caregiver entry
            const newCaregiver = document.createElement('div');
            newCaregiver.className = 'claws-caregiver-entry';
            newCaregiver.setAttribute('data-caregiver-index', nextIndex);
            newCaregiver.style.cssText = 'margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;';
            
            newCaregiver.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; width: 100%;">
                    <h4 style="font-weight: 500; color: #1f2937; margin: 0; font-size: 0.875rem;">Additional Caregiver ${nextIndex}</h4>
                    <button type="button" onclick="this.parentElement.parentElement.remove()" style="background: #ef4444; color: white; padding: 0.25rem 0.5rem; border-radius: 0.25rem; border: none; font-size: 0.75rem; cursor: pointer;">
                        Remove
                    </button>
                </div>
                <div style="margin-bottom: 0.75rem; width: 100%;">
                    <label class="claws-form-label">Caregiver</label>
                    <input type="text" class="claws-form-input claws-caregiver-name" placeholder="Name of person caring for this colony" style="width: 100%; box-sizing: border-box;" />
                </div>
                <div style="margin-bottom: 0.75rem; width: 100%;">
                    <label class="claws-form-label">Email</label>
                    <input type="email" class="claws-form-input claws-caregiver-email" placeholder="caregiver@example.com" style="width: 100%; box-sizing: border-box;" />
                </div>
                <div style="margin-bottom: 0.75rem; width: 100%;">
                    <label class="claws-form-label">Phone Number</label>
                    <input type="tel" class="claws-form-input claws-caregiver-phone" placeholder="(555) 123-4567" style="width: 100%; box-sizing: border-box;" />
                </div>
                <div style="margin-bottom: 0.75rem; width: 100%;">
                    <label class="claws-form-label">Preferred Contact Method (check all that apply)</label>
                    <div style="display: flex; flex-direction: column; gap: 0.5rem; margin-top: 0.5rem;">
                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; color: #374151;">
                            <input type="checkbox" class="claws-caregiver-contact-text" style="margin: 0; accent-color: ${clawsData.primaryColor};" />
                            Text Messaging
                        </label>
                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; color: #374151;">
                            <input type="checkbox" class="claws-caregiver-contact-email" style="margin: 0; accent-color: ${clawsData.primaryColor};" />
                            Email
                        </label>
                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; color: #374151;">
                            <input type="checkbox" class="claws-caregiver-contact-phone" style="margin: 0; accent-color: ${clawsData.primaryColor};" />
                            Phone
                        </label>
                    </div>
                </div>
                <div style="padding-top: 0.5rem; width: 100%;">
                    <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; color: #374151;">
                        <input type="checkbox" class="claws-caregiver-public" checked style="margin: 0; accent-color: ${clawsData.primaryColor};" />
                        Show contact info on app?
                    </label>
                </div>
            `;
            
            container.appendChild(newCaregiver);
        },

        /**
         * Save colony data to database
         */
        saveColony: async function() {
            console.log('Save function called');
            
            const colonyName = document.getElementById('claws-colony-name').value;
            
            if (!colonyName) {
                this.showAlert('Please enter a colony name.', 'error');
                return;
            }

            // Validate date
            const selectedDate = document.getElementById('claws-colony-date').value;
            if (!selectedDate) {
                this.showAlert('Please select a date for this colony data.', 'error');
                return;
            }
            
            // Check if date is in the future (allowing today)
            const today = new Date().toISOString().split('T')[0];
            if (selectedDate > today) {
                this.showAlert('Cannot enter colony data for future dates. Please select today or an earlier date.', 'error');
                return;
            }

            // Check if coordinates were manually selected
            if (!this.selectedCoordinates) {
                this.showAlert('Please click on the map to select the colony location.', 'error');
                return;
            }

            const babies = parseInt(document.getElementById('claws-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-kittens-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-adults-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-seniors-count').value) || 0;
            const totalCats = babies + kittens + adults + seniors;

            if (totalCats === 0) {
                this.showAlert('Please enter at least one cat in the population.', 'error');
                return;
            }

            // Validate address fields
            const street = document.getElementById('claws-colony-street').value.trim();
            const city = document.getElementById('claws-colony-city').value.trim();
            const state = document.getElementById('claws-colony-state').value.trim();
            const zip = document.getElementById('claws-colony-zip').value.trim();
            
            if (!street || !city || !state || !zip) {
                this.showAlert('Please fill in all address fields (Street, City, State, Zip).', 'error');
                return;
            }

            // Validate caregiver information
            const caregiverName = document.querySelector('.claws-caregiver-name').value.trim();
            const caregiverEmail = document.querySelector('.claws-caregiver-email').value.trim();
            const caregiverPhone = document.querySelector('.claws-caregiver-phone').value.trim();
            
            if (!caregiverName) {
                this.showAlert('Please enter the caregiver name.', 'error');
                return;
            }
            
            if (!caregiverEmail && !caregiverPhone) {
                this.showAlert('Please provide either an email or phone number for the caregiver.', 'error');
                return;
            }

            // Validate contact method checkboxes
            const contactText = document.querySelector('.claws-caregiver-contact-text').checked;
            const contactEmail = document.querySelector('.claws-caregiver-contact-email').checked;
            const contactPhone = document.querySelector('.claws-caregiver-contact-phone').checked;
            
            if (!contactText && !contactEmail && !contactPhone) {
                this.showAlert('Please select at least one preferred contact method.', 'error');
                return;
            }

            // Validate security selections
            const foodSecurity = document.getElementById('claws-food-security').value;
            const waterSecurity = document.getElementById('claws-water-security').value;
            const safeLocation = document.getElementById('claws-safe-location').value;
            
            if (!foodSecurity) {
                this.showAlert('Please select the food security level.', 'error');
                return;
            }
            
            if (!waterSecurity) {
                this.showAlert('Please select the water security level.', 'error');
                return;
            }
            
            if (!safeLocation) {
                this.showAlert('Please select the safety level.', 'error');
                return;
            }

            // Show loading
            this.showLoading();

            try {
                // Combine address fields into a full address (already extracted in validation)
                
                let fullAddress = '';
                if (street) fullAddress = street;
                if (city) fullAddress += (fullAddress ? ', ' : '') + city;
                if (state) fullAddress += (fullAddress ? ', ' : '') + state;
                if (zip) fullAddress += (fullAddress ? ' ' : '') + zip;
                
                const colonyData = {
                    name: colonyName,
                    address: fullAddress,
                    street: street,
                    city: city,
                    state: state,
                    zip: zip,
                    lat: this.selectedCoordinates.lat,
                    lng: this.selectedCoordinates.lng,
                    babies: babies,
                    kittens: kittens,
                    adults: adults,
                    seniors: seniors,
                    cats: totalCats,
                    tippedEars: parseInt(document.getElementById('claws-tipped-ears').value) || 0,
                    winterShelters: parseInt(document.getElementById('claws-winter-shelters').value) || 0,
                    foodSecurity: document.getElementById('claws-food-security').value,
                    waterSecurity: document.getElementById('claws-water-security').value,
                    safeLocation: document.getElementById('claws-safe-location').value,
                    captureMethod: document.getElementById('claws-capture-method').value,
                    vaccinatedCount: document.getElementById('claws-vaccinated-count').value.trim() !== '' ? parseInt(document.getElementById('claws-vaccinated-count').value) : 'unknown',
                    microchipCount: document.getElementById('claws-microchip-count').value.trim() !== '' ? parseInt(document.getElementById('claws-microchip-count').value) : 'unknown',
                    tnrNoTipping: document.getElementById('claws-tnr-no-tipping').checked,
                    volunteerHelp: {
                        feed: document.getElementById('claws-help-feed').checked,
                        trap: document.getElementById('claws-help-trap').checked,
                        housePre: document.getElementById('claws-help-house-pre').checked,
                        transportTo: document.getElementById('claws-help-transport-to').checked,
                        transportFrom: document.getElementById('claws-help-transport-from').checked,
                        recovery: document.getElementById('claws-help-recovery').checked,
                        monitor: document.getElementById('claws-help-monitor').checked,
                        return: document.getElementById('claws-help-return').checked,
                        watch: document.getElementById('claws-help-watch').checked,
                        donate: document.getElementById('claws-help-donate').checked
                    },
                    assignedUserId: document.getElementById('claws-assign-user').value || null
                };
                
                // Collect colony help requests
                const colonyHelpOptions = document.querySelectorAll('.claws-help-option');
                const colonyHelp = {};
                colonyHelpOptions.forEach(option => {
                    const helpType = option.getAttribute('data-help-type');
                    colonyHelp[helpType] = option.checked;
                });
                colonyData.colonyHelp = colonyHelp;

                // Collect caregiver information
                const caregiverEntries = document.querySelectorAll('.claws-caregiver-entry');
                const caregivers = [];
                
                caregiverEntries.forEach(entry => {
                    const name = entry.querySelector('.claws-caregiver-name').value.trim();
                    const email = entry.querySelector('.claws-caregiver-email').value.trim();
                    const phone = entry.querySelector('.claws-caregiver-phone').value.trim();
                    const isPublic = entry.querySelector('.claws-caregiver-public').checked;
                    
                    // Collect preferred contact methods
                    const contactMethods = [];
                    if (entry.querySelector('.claws-caregiver-contact-text') && entry.querySelector('.claws-caregiver-contact-text').checked) {
                        contactMethods.push('Text Messaging');
                    }
                    if (entry.querySelector('.claws-caregiver-contact-email') && entry.querySelector('.claws-caregiver-contact-email').checked) {
                        contactMethods.push('Email');
                    }
                    if (entry.querySelector('.claws-caregiver-contact-phone') && entry.querySelector('.claws-caregiver-contact-phone').checked) {
                        contactMethods.push('Phone');
                    }
                    
                    // Only add caregiver if at least a name is provided
                    if (name) {
                        caregivers.push({
                            name: name,
                            email: email,
                            phone: phone,
                            isPublic: isPublic,
                            preferredContactMethods: contactMethods
                        });
                    }
                });
                
                colonyData.caregivers = caregivers;

                console.log('Sending colony data:', colonyData);
                console.log('API URL:', this.config.apiUrl + 'colony');
                console.log('Nonce:', this.config.nonce);

                // Save to database via API
                const response = await fetch(this.config.apiUrl + 'colony', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(colonyData)
                });

                console.log('Response status:', response.status);
                console.log('Response OK:', response.ok);

                const responseText = await response.text();
                console.log('Raw response:', responseText);

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${responseText}`);
                }

                let result;
                try {
                    result = JSON.parse(responseText);
                    console.log('Parsed response:', result);
                } catch (e) {
                    throw new Error('Invalid response format: ' + responseText);
                }

                if (result.success && result.id) {
                    // Reload colonies from server to get complete saved data
                    await this.loadColonies();
                    
                    // Save initial colony history entry
                    await this.saveColonyHistoryEntry(result.id, colonyData);
                    
                    this.updateColonyUI();
                    this.hideAddColonyForm();
                    this.showAlert(`Colony saved successfully! Post ID: ${result.id}`, 'success');
                } else {
                    throw new Error('Save failed: ' + JSON.stringify(result));
                }

            } catch (error) {
                console.error('Save error:', error);
                this.showAlert('Save failed: ' + error.message, 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Update existing colony data
         */
        updateColony: async function(colonyId) {
            console.log('Update function called for colony ID:', colonyId);
            
            const colonyName = document.getElementById('claws-colony-name').value;
            
            if (!colonyName) {
                this.showAlert('Please enter a colony name.', 'error');
                return;
            }

            // Validate date
            const selectedDate = document.getElementById('claws-colony-date').value;
            if (!selectedDate) {
                this.showAlert('Please select a date for this colony data update.', 'error');
                return;
            }
            
            // Check if date is in the future (allowing today)
            const today = new Date().toISOString().split('T')[0];
            if (selectedDate > today) {
                this.showAlert('Cannot enter colony data for future dates. Please select today or an earlier date.', 'error');
                return;
            }
            
            // Check if coordinates were manually selected
            if (!this.selectedCoordinates) {
                this.showAlert('Please click on the map to select the colony location.', 'error');
                return;
            }
            
            const babies = parseInt(document.getElementById('claws-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-kittens-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-adults-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-seniors-count').value) || 0;
            const totalCats = babies + kittens + adults + seniors;
            
            if (totalCats === 0) {
                this.showAlert('Please enter at least one cat in the population.', 'error');
                return;
            }
            
            // Show loading
            this.showLoading();
            
            try {
                // Combine address fields into a full address
                const street = document.getElementById('claws-colony-street').value.trim();
                const city = document.getElementById('claws-colony-city').value.trim();
                const state = document.getElementById('claws-colony-state').value.trim();
                const zip = document.getElementById('claws-colony-zip').value.trim();
                
                let fullAddress = '';
                if (street) fullAddress = street;
                if (city) fullAddress += (fullAddress ? ', ' : '') + city;
                if (state) fullAddress += (fullAddress ? ', ' : '') + state;
                if (zip) fullAddress += (fullAddress ? ' ' : '') + zip;
                
                const colonyData = {
                    name: colonyName,
                    address: fullAddress,
                    street: street,
                    city: city,
                    state: state,
                    zip: zip,
                    lat: this.selectedCoordinates.lat,
                    lng: this.selectedCoordinates.lng,
                    babies: babies,
                    kittens: kittens,
                    adults: adults,
                    seniors: seniors,
                    cats: totalCats,
                    tippedEars: parseInt(document.getElementById('claws-tipped-ears').value) || 0,
                    winterShelters: parseInt(document.getElementById('claws-winter-shelters').value) || 0,
                    foodSecurity: document.getElementById('claws-food-security').value,
                    waterSecurity: document.getElementById('claws-water-security').value,
                    safeLocation: document.getElementById('claws-safe-location').value,
                    captureMethod: document.getElementById('claws-capture-method').value,
                    vaccinatedCount: document.getElementById('claws-vaccinated-count').value.trim() !== '' ? parseInt(document.getElementById('claws-vaccinated-count').value) : 'unknown',
                    microchipCount: document.getElementById('claws-microchip-count').value.trim() !== '' ? parseInt(document.getElementById('claws-microchip-count').value) : 'unknown',
                    tnrNoTipping: document.getElementById('claws-tnr-no-tipping').checked,
                    volunteerHelp: {
                        feed: document.getElementById('claws-help-feed').checked,
                        trap: document.getElementById('claws-help-trap').checked,
                        housePre: document.getElementById('claws-help-house-pre').checked,
                        transportTo: document.getElementById('claws-help-transport-to').checked,
                        transportFrom: document.getElementById('claws-help-transport-from').checked,
                        recovery: document.getElementById('claws-help-recovery').checked,
                        monitor: document.getElementById('claws-help-monitor').checked,
                        return: document.getElementById('claws-help-return').checked,
                        watch: document.getElementById('claws-help-watch').checked,
                        donate: document.getElementById('claws-help-donate').checked
                    },
                    assignedUserId: document.getElementById('claws-assign-user').value || null
                };
                
                // Collect caregiver data
                const caregivers = [];
                const caregiverEntries = document.querySelectorAll('.claws-caregiver-entry');
                caregiverEntries.forEach(entry => {
                    const name = entry.querySelector('.claws-caregiver-name').value.trim();
                    const email = entry.querySelector('.claws-caregiver-email').value.trim();
                    const phone = entry.querySelector('.claws-caregiver-phone').value.trim();
                    const isPublic = entry.querySelector('.claws-caregiver-public').checked;
                    
                    // Collect preferred contact methods
                    const contactMethods = [];
                    if (entry.querySelector('.claws-caregiver-contact-text') && entry.querySelector('.claws-caregiver-contact-text').checked) {
                        contactMethods.push('Text Messaging');
                    }
                    if (entry.querySelector('.claws-caregiver-contact-email') && entry.querySelector('.claws-caregiver-contact-email').checked) {
                        contactMethods.push('Email');
                    }
                    if (entry.querySelector('.claws-caregiver-contact-phone') && entry.querySelector('.claws-caregiver-contact-phone').checked) {
                        contactMethods.push('Phone');
                    }
                    
                    if (name || email || phone) {
                        caregivers.push({
                            name: name,
                            email: email,
                            phone: phone,
                            isPublic: isPublic,
                            preferredContactMethods: contactMethods
                        });
                    }
                });
                
                colonyData.caregivers = caregivers;

                console.log('Sending update data:', colonyData);
                console.log('API URL:', this.config.apiUrl + 'colony/' + colonyId);
                console.log('Nonce:', this.config.nonce);

                // Update via API
                const response = await fetch(this.config.apiUrl + 'colony/' + colonyId, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(colonyData)
                });

                console.log('Response status:', response.status);
                console.log('Response OK:', response.ok);

                const responseText = await response.text();
                console.log('Raw response:', responseText);

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${responseText}`);
                }

                let result;
                try {
                    result = JSON.parse(responseText);
                    console.log('Parsed response:', result);
                } catch (e) {
                    throw new Error('Invalid response format: ' + responseText);
                }

                if (result.success) {
                    // Reload colonies from server to get complete updated data
                    await this.loadColonies();
                    
                    // Save colony history entry for this update
                    await this.saveColonyHistoryEntry(colonyId, colonyData);
                    
                    this.updateColonyUI();
                    this.hideAddColonyForm();
                    this.showAlert('Colony updated successfully!', 'success');
                } else {
                    throw new Error('Update failed: ' + JSON.stringify(result));
                }

            } catch (error) {
                console.error('Update error:', error);
                this.showAlert('Update failed: ' + error.message, 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Save colony history entry - creates a data point for tracking colony changes over time
         */
        saveColonyHistoryEntry: async function(colonyId, colonyData) {
            try {
                // Get the selected date from the form, or use today's date as fallback
                const selectedDate = document.getElementById('claws-colony-date')?.value || new Date().toISOString().split('T')[0];
                
                const historyData = {
                    colony_id: colonyId,
                    date: selectedDate, // Use selected date from form
                    time: new Date().toTimeString().split(' ')[0], // Current time in HH:MM:SS format
                    babies: colonyData.babies || 0,
                    kittens: colonyData.kittens || 0,
                    adults: colonyData.adults || 0,
                    seniors: colonyData.seniors || 0,
                    total_cats: colonyData.cats || 0,
                    tipped_ears: colonyData.tippedEars || 0,
                    winter_shelters: colonyData.winterShelters || 0,
                    vaccinated_count: colonyData.vaccinatedCount === 'unknown' ? null : colonyData.vaccinatedCount,
                    microchip_count: colonyData.microchipCount === 'unknown' ? null : colonyData.microchipCount,
                    food_security: colonyData.foodSecurity,
                    water_security: colonyData.waterSecurity,
                    safe_location: colonyData.safeLocation,
                    notes: `Colony data updated` // Could be expanded to include user notes
                };

                const response = await fetch(this.config.apiUrl + 'colony-history', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(historyData)
                });

                if (!response.ok) {
                    console.warn('Failed to save colony history entry:', response.status);
                    // Don't throw error - history is supplementary, shouldn't block main save
                    return;
                }

                const result = await response.json();
                console.log('Colony history entry saved:', result);

            } catch (error) {
                console.warn('Error saving colony history entry:', error);
                // Don't throw error - history is supplementary, shouldn't block main save
            }
        },

        /**
         * Load colony history data for displaying charts
         */
        loadColonyHistory: async function(colonyId) {
            this.trackCall('loadColonyHistory');
            try {
                const response = await fetch(this.config.apiUrl + `colony-history/${colonyId}`, {
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    }
                });

                if (!response.ok) {
                    throw new Error('Failed to load colony history');
                }

                const history = await response.json();
                return history || [];

            } catch (error) {
                console.error('Error loading colony history:', error);
                return [];
            }
        },

        /**
         * Update colony history chart - similar to neonate weight chart
         */
        updateColonyHistoryChart: function(colonyId, historyData) {
            const canvas = document.getElementById('colony-history-chart');
            if (!canvas) return;

            const ctx = canvas.getContext('2d');

            // Destroy existing chart
            if (this.colonyHistoryChart) {
                this.colonyHistoryChart.destroy();
            }

            if (!historyData || historyData.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No history data available', canvas.width / 2, canvas.height / 2);
                return;
            }

            // Prepare data for Chart.js using Roy G. Biv colors
            const labels = historyData.map(entry => entry.date);
            
            const datasets = [
                {
                    label: 'Total Cats',
                    data: historyData.map(entry => entry.total_cats),
                    borderColor: this.getChartColor(0), // Red
                    backgroundColor: this.getChartColor(0),
                    tension: 0.1,
                    fill: false
                },
                {
                    label: 'Kittens',
                    data: historyData.map(entry => entry.kittens),
                    borderColor: this.getChartColor(1), // Orange
                    backgroundColor: this.getChartColor(1),
                    tension: 0.1,
                    fill: false
                },
                {
                    label: 'Adults',
                    data: historyData.map(entry => entry.adults),
                    borderColor: this.getChartColor(2), // Yellow
                    backgroundColor: this.getChartColor(2),
                    tension: 0.1,
                    fill: false
                },
                {
                    label: 'Seniors',
                    data: historyData.map(entry => entry.seniors),
                    borderColor: this.getChartColor(3), // Green
                    backgroundColor: this.getChartColor(3),
                    tension: 0.1,
                    fill: false
                },
                {
                    label: 'Tipped Ears',
                    data: historyData.map(entry => entry.tipped_ears),
                    borderColor: this.getChartColor(4), // Blue
                    backgroundColor: this.getChartColor(4),
                    tension: 0.1,
                    fill: false
                },
                {
                    label: 'Winter Shelters',
                    data: historyData.map(entry => entry.winter_shelters),
                    borderColor: this.getChartColor(5), // Indigo
                    backgroundColor: this.getChartColor(5),
                    tension: 0.1,
                    fill: false
                }
            ];

            this.colonyHistoryChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        title: {
                            display: true,
                            text: 'Colony Population History'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Count'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Date'
                            }
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
        },

        /**
         * Geocode address to get GPS coordinates with improved accuracy
         */
        geocodeAddress: async function(address) {
            try {
                // For McDonald's Clutch, use exact coordinates we know are correct
                if (address.toLowerCase().includes('1158') && address.toLowerCase().includes('main')) {
                    console.log('Using exact coordinates for McDonald\'s Clutch location');
                    return {
                        lat: 36.8671,
                        lng: -82.10523
                    };
                }

                // Clean and format the address for better results
                let fullAddress = address.trim();
                
                // Add default location context if not already included
                const defaultLocation = this.config.defaultLocation || 'United States';
                if (!fullAddress.toLowerCase().includes(defaultLocation.toLowerCase())) {
                    fullAddress = `${fullAddress}, ${defaultLocation}`;
                }

                console.log('Geocoding address:', fullAddress);

                // Try multiple geocoding services for better accuracy
                const services = [
                    // Nominatim with street-level search
                    `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(fullAddress)}&limit=3&addressdetails=1&extratags=1`
                ];

                for (let serviceUrl of services) {
                    try {
                        const response = await fetch(serviceUrl, {
                            headers: {
                                'User-Agent': 'CLAWS-App/1.0'
                            }
                        });
                        
                        if (!response.ok) continue;

                        const data = await response.json();
                        console.log('Geocoding results from', serviceUrl, ':', data);
                        
                        if (data && data.length > 0) {
                            // Find the best match - prioritize specific address types
                            let bestMatch = null;
                            
                            for (let result of data) {
                                // Prioritize house numbers and specific addresses
                                if (result.type === 'house' || result.class === 'place' || result.type === 'building') {
                                    bestMatch = result;
                                    break;
                                }
                            }
                            
                            // Last resort - use first result
                            if (!bestMatch) {
                                bestMatch = data[0];
                            }
                            
                            if (bestMatch) {
                                const coordinates = {
                                    lat: parseFloat(bestMatch.lat),
                                    lng: parseFloat(bestMatch.lon)
                                };
                                
                                console.log('Selected coordinates:', coordinates, 'from result:', bestMatch);
                                return coordinates;
                            }
                        }
                    } catch (serviceError) {
                        console.warn('Geocoding service failed:', serviceError);
                        continue;
                    }
                }
                
                return null;
            } catch (error) {
                console.error('Geocoding error:', error);
                return null;
            }
        },

        /**
         * View colony details
         */
        viewColonyDetails: function(colonyId) {
            const colony = this.colonies.find(c => c.id === colonyId);
            if (!colony) return;
            
            const healthScore = this.calculateHealthScore(colony);
            
            // Build caregiver information
            let caregiverInfo = '';
            if (colony.caregivers && Array.isArray(colony.caregivers) && colony.caregivers.length > 0) {
                const publicCaregivers = colony.caregivers.filter(caregiver => caregiver.isPublic);
                
                if (publicCaregivers.length > 0) {
                    caregiverInfo = '\n\nCaregivers:';
                    publicCaregivers.forEach((caregiver, index) => {
                        caregiverInfo += `\n• ${caregiver.name || 'Unnamed'}`;
                        if (caregiver.email) {
                            caregiverInfo += `\n  📧 ${caregiver.email}`;
                        }
                        if (caregiver.phone) {
                            caregiverInfo += `\n  📞 ${caregiver.phone}`;
                        }
                        if (index < publicCaregivers.length - 1) {
                            caregiverInfo += '\n';
                        }
                    });
                }
            }
            
            const details = `${colony.name}

Total Cats: ${colony.cats || 0}
• Babies: ${colony.babies || 0}
• Kittens: ${colony.kittens || 0}  
• Adults: ${colony.adults || 0}
• Seniors: ${colony.seniors || 0}

Health Metrics:
• TNR Progress: ${Math.round(((colony.tippedEars || 0) / Math.max((colony.cats || 1) - (colony.babies || 0), 1)) * 100)}%
• Health Score: ${healthScore}%
• Food Security: ${colony.foodSecurity || 'Not set'}
• Water Security: ${colony.waterSecurity || 'Not set'}
• Safety Level: ${colony.safeLocation || 'Not set'}${caregiverInfo}

Added by: ${colony.addedBy || 'Unknown'}`;

            this.showColonyDetailsModal(colony, details);
        },
        
        /**
         * Show colony details modal with photo upload
         */
        showColonyDetailsModal: function(colony, details) {
            // Remove existing modal if it exists
            const existingModal = document.getElementById('claws-colony-details-modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modal = document.createElement('div');
            modal.id = 'claws-colony-details-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            // Build photos gallery HTML
            let photosHtml = '';
            if (colony.photos && colony.photos.length > 0) {
                photosHtml = `
                    <div style="margin-bottom: 1rem;">
                        <h4 style="font-weight: 500; color: #1f2937; margin: 0 0 0.5rem; font-size: 0.875rem;">Colony Photos</h4>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(80px, 1fr)); gap: 0.5rem; margin-bottom: 0.5rem;">
                            ${colony.photos.map(photo => `
                                <img src="${photo.thumbnail}" alt="${photo.alt || 'Colony photo'}" 
                                     style="width: 80px; height: 80px; object-fit: cover; border-radius: 0.375rem; border: 1px solid #e5e7eb; cursor: pointer;"
                                     onclick="window.open('${photo.url}', '_blank')" />
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 28rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">Colony Details</h2>
                            <button onclick="this.closest('#claws-colony-details-modal').remove()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <!-- Colony Info -->
                        <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb; margin-bottom: 1rem; white-space: pre-line; font-size: 0.875rem; line-height: 1.4;">
                            ${details}
                        </div>
                        
                        <!-- Photos Section -->
                        ${photosHtml}
                        
                        <!-- Photo Upload -->
                        <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb; margin-bottom: 1rem;">
                            <h4 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Add Colony Photo</h4>
                            <div>
                                <input type="file" id="claws-colony-photo" accept="image/jpeg,image/png,image/webp" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" />
                                <div id="claws-colony-photo-preview" style="margin-top: 0.5rem; display: none;">
                                    <img id="claws-colony-photo-img" style="max-width: 100%; height: 100px; object-fit: cover; border-radius: 0.375rem; border: 1px solid #e5e7eb;" />
                                </div>
                                <p style="font-size: 0.625rem; color: #6b7280; margin: 0.25rem 0 0;">JPG, PNG, or WebP. Max 5MB.</p>
                                <button onclick="CLAWSApp.uploadColonyPhoto(${colony.id})" style="margin-top: 0.5rem; padding: 0.5rem 1rem; background: ${this.getGradientStyle()}; color: white; border: none; border-radius: 0.375rem; font-size: 0.75rem; font-weight: 500; cursor: pointer;">
                                    Upload Photo
                                </button>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div style="display: flex; gap: 0.75rem; justify-content: center; flex-wrap: wrap;">
                            ${this.canUserEditColony(colony) ? `
                            <button onclick="CLAWSApp.editColony(${colony.id})" style="padding: 0.75rem 1.5rem; background: ${this.getGradientStyle()}; color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Edit Colony
                            </button>
                            ` : ''}
                            <button onclick="CLAWSApp.viewColonyHistory(${colony.id})" style="padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                📊 View History
                            </button>
                            <button onclick="this.closest('#claws-colony-details-modal').remove()" style="padding: 0.75rem 1.5rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // Add photo preview functionality
            this.setupPhotoPreview('claws-colony-photo', 'claws-colony-photo-preview', 'claws-colony-photo-img');
        },

        /**
         * View colony history
         */
        viewColonyHistory: async function(colonyId) {
            try {
                this.showLoading('Loading colony history...');
                
                const response = await fetch(this.config.apiUrl + 'colony/' + colonyId + '/history', {
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (!response.ok) {
                    throw new Error('Failed to load colony history');
                }
                
                const history = await response.json();
                this.showColonyHistoryModal(colonyId, history);
                
            } catch (error) {
                console.error('Error loading colony history:', error);
                this.showAlert('Failed to load colony history. Please try again.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Show colony history modal
         */
        showColonyHistoryModal: function(colonyId, history) {
            const colony = this.colonies.find(c => c.id === colonyId);
            if (!colony) return;
            
            // Remove existing modal if it exists
            const existingModal = document.getElementById('claws-colony-history-modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modal = document.createElement('div');
            modal.id = 'claws-colony-history-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            let historyHtml = '';
            if (history.length === 0) {
                historyHtml = '<p style="text-align: center; color: #6b7280; font-style: italic;">No history records found.</p>';
            } else {
                historyHtml = history.map((record, index) => {
                    const date = new Date(record.created_at).toLocaleDateString();
                    const time = new Date(record.created_at).toLocaleTimeString();
                    const isLatest = index === 0;
                    
                    return `
                        <div style="background: ${isLatest ? '#f0f9ff' : '#f9fafb'}; padding: 1rem; border-radius: 0.5rem; border: 1px solid ${isLatest ? '#0ea5e9' : '#e5e7eb'}; margin-bottom: 1rem; position: relative;">
                            ${isLatest ? '<div style="position: absolute; top: -0.5rem; left: 1rem; background: #0ea5e9; color: white; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 500;">Latest</div>' : ''}
                            <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 0.75rem;">
                                <h4 style="font-weight: 500; color: #1f2937; margin: 0; font-size: 0.875rem;">${record.colony_name}</h4>
                                <span style="font-size: 0.75rem; color: #6b7280;">${date} ${time}</span>
                            </div>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.5rem; font-size: 0.75rem;">
                                <div><strong>Total Cats:</strong> ${record.cats_total}</div>
                                <div><strong>Babies:</strong> ${record.cats_babies}</div>
                                <div><strong>Kittens:</strong> ${record.cats_kittens}</div>
                                <div><strong>Adults:</strong> ${record.cats_adults}</div>
                                <div><strong>Seniors:</strong> ${record.cats_seniors}</div>
                                <div><strong>TNR'd:</strong> ${record.tipped_ears}</div>
                                <div><strong>Shelters:</strong> ${record.winter_shelters}</div>
                                <div><strong>Food Security:</strong> ${record.food_security || 'Not set'}</div>
                                <div><strong>Water Security:</strong> ${record.water_security || 'Not set'}</div>
                                <div><strong>Safe Location:</strong> ${record.safe_location || 'Not set'}</div>
                            </div>
                            ${record.notes ? `<div style="margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid #e5e7eb; font-size: 0.75rem;"><strong>Notes:</strong> ${record.notes}</div>` : ''}
                        </div>
                    `;
                }).join('');
            }
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 48rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">📊 ${colony.name} - History</h2>
                            <button onclick="this.closest('#claws-colony-history-modal').remove()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <!-- History Content -->
                        <div style="max-height: 70vh; overflow-y: auto;">
                            ${historyHtml}
                        </div>
                        
                        <!-- Action Buttons -->
                        <div style="display: flex; gap: 0.75rem; justify-content: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;">
                            <button onclick="CLAWSApp.viewColonyDetails(${colonyId}); this.closest('#claws-colony-history-modal').remove();" style="padding: 0.75rem 1.5rem; background: ${this.getGradientStyle()}; color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Back to Details
                            </button>
                            <button onclick="this.closest('#claws-colony-history-modal').remove()" style="padding: 0.75rem 1.5rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
        },

        /**
         * Show system analytics modal
         */
        showSystemAnalytics: async function() {
            try {
                this.showLoading('Loading system analytics...');
                
                // Load all colonies using the working method (admin can see all)
                const cacheBuster = new Date().getTime();
                const response = await fetch(this.config.apiUrl + 'colonies?_cb=' + cacheBuster, {
                    cache: 'no-cache',
                    headers: {
                        'Cache-Control': 'no-cache',
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (!response.ok) {
                    throw new Error('Failed to load colonies data');
                }
                
                const colonies = await response.json();
                console.log('Loaded colonies for system analytics:', colonies.length);
                
                // Calculate system metrics from colonies data
                const systemData = this.calculateSystemMetrics(colonies);
                this.showSystemAnalyticsModal(systemData);
                
            } catch (error) {
                console.error('Error loading system analytics:', error);
                this.showAlert('Failed to load system analytics. Please try again.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Calculate system metrics from colonies data
         */
        calculateSystemMetrics: function(colonies) {
            console.log('Calculating system metrics from', colonies.length, 'colonies');
            
            const totals = {
                total_colonies: colonies.length,
                total_cats: 0,
                total_babies: 0,
                total_kittens: 0,
                total_adults: 0,
                total_seniors: 0,
                total_tnr: 0,
                total_shelters: 0,
                overall_tnr_percentage: 0
            };
            
            // Sum up all the metrics from colonies using actual colony data structure
            colonies.forEach(colony => {
                console.log('Processing colony for system metrics:', colony.name, colony);
                
                totals.total_cats += parseInt(colony.cats) || 0;
                totals.total_babies += parseInt(colony.babies) || 0;
                totals.total_kittens += parseInt(colony.kittens) || 0;
                totals.total_adults += parseInt(colony.adults) || 0;
                totals.total_seniors += parseInt(colony.seniors) || 0;
                totals.total_tnr += parseInt(colony.tippedEars) || 0;
                totals.total_shelters += parseInt(colony.winterShelters) || 0;
            });
            
            // Calculate TNR percentage
            const eligibleForTNR = totals.total_adults + totals.total_seniors;
            if (eligibleForTNR > 0) {
                totals.overall_tnr_percentage = Math.round((totals.total_tnr / eligibleForTNR) * 100);
            }
            
            console.log('Calculated system totals:', totals);
            
            return {
                current_totals: totals,
                trends: [] // Empty for now, can be implemented later if needed
            };
        },

        /**
         * Show system analytics modal
         */
        showSystemAnalyticsModal: function(data) {
            // Remove existing modal if it exists
            const existingModal = document.getElementById('claws-system-analytics-modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modal = document.createElement('div');
            modal.id = 'claws-system-analytics-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            const totals = data.current_totals;
            const trends = data.trends.slice(0, 10); // Last 10 data points
            
            let trendsHtml = '';
            if (trends.length === 0) {
                trendsHtml = '<p style="text-align: center; color: #6b7280; font-style: italic;">No trend data available yet.</p>';
            } else {
                trendsHtml = trends.map((record, index) => {
                    const date = new Date(record.date).toLocaleDateString();
                    const isLatest = index === 0;
                    
                    return `
                        <div style="background: ${isLatest ? '#f0f9ff' : '#f9fafb'}; padding: 1rem; border-radius: 0.5rem; border: 1px solid ${isLatest ? '#0ea5e9' : '#e5e7eb'}; margin-bottom: 1rem; position: relative;">
                            ${isLatest ? '<div style="position: absolute; top: -0.5rem; left: 1rem; background: #0ea5e9; color: white; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 500;">Latest</div>' : ''}
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem;">
                                <h4 style="font-weight: 500; color: #1f2937; margin: 0; font-size: 0.875rem;">${date}</h4>
                                <span style="font-size: 0.75rem; color: #6b7280;">${record.active_colonies} active colonies</span>
                            </div>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.5rem; font-size: 0.75rem;">
                                <div><strong>Total Cats:</strong> ${record.total_cats}</div>
                                <div><strong>Babies:</strong> ${record.total_babies}</div>
                                <div><strong>Kittens:</strong> ${record.total_kittens}</div>
                                <div><strong>Adults:</strong> ${record.total_adults}</div>
                                <div><strong>Seniors:</strong> ${record.total_seniors}</div>
                                <div><strong>TNR'd:</strong> ${record.total_tnr}</div>
                                <div><strong>Shelters:</strong> ${record.total_shelters}</div>
                                <div><strong>Avg Cats/Colony:</strong> ${parseFloat(record.avg_cats_per_colony).toFixed(1)}</div>
                                <div><strong>Avg TNR %:</strong> ${parseFloat(record.avg_tnr_percentage).toFixed(1)}%</div>
                            </div>
                        </div>
                    `;
                }).join('');
            }
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 56rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">📊 System Analytics</h2>
                            <button onclick="this.closest('#claws-system-analytics-modal').remove()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <!-- Current Totals -->
                        <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 1.5rem; border-radius: 1rem; color: white; margin-bottom: 1.5rem;">
                            <h3 style="font-weight: 600; font-size: 1.125rem; margin: 0 0 1rem;">Current System Overview</h3>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem;">
                                <div style="text-align: center;">
                                    <div style="font-size: 2rem; font-weight: bold;">${totals.total_colonies}</div>
                                    <div style="font-size: 0.875rem; opacity: 0.9;">Active Colonies</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 2rem; font-weight: bold;">${totals.total_cats}</div>
                                    <div style="font-size: 0.875rem; opacity: 0.9;">Total Cats</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 2rem; font-weight: bold;">${totals.total_tnr}</div>
                                    <div style="font-size: 0.875rem; opacity: 0.9;">TNR'd Cats</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 2rem; font-weight: bold;">${totals.overall_tnr_percentage}%</div>
                                    <div style="font-size: 0.875rem; opacity: 0.9;">TNR Rate</div>
                                </div>
                                <div style="text-align: center;">
                                    <div style="font-size: 2rem; font-weight: bold;">${totals.total_shelters}</div>
                                    <div style="font-size: 0.875rem; opacity: 0.9;">Winter Shelters</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Age Breakdown -->
                        <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb; margin-bottom: 1.5rem;">
                            <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Population Breakdown</h3>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); gap: 0.75rem; font-size: 0.75rem;">
                                <div style="text-align: center; padding: 0.5rem; background: white; border-radius: 0.375rem;">
                                    <div style="font-weight: bold; color: #8b5cf6;">${totals.total_babies}</div>
                                    <div>Babies</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: white; border-radius: 0.375rem;">
                                    <div style="font-weight: bold; color: #06b6d4;">${totals.total_kittens}</div>
                                    <div>Kittens</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: white; border-radius: 0.375rem;">
                                    <div style="font-weight: bold; color: #10b981;">${totals.total_adults}</div>
                                    <div>Adults</div>
                                </div>
                                <div style="text-align: center; padding: 0.5rem; background: white; border-radius: 0.375rem;">
                                    <div style="font-weight: bold; color: #f59e0b;">${totals.total_seniors}</div>
                                    <div>Seniors</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Recent Trends -->
                        <div>
                            <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 1rem; font-size: 1rem;">Recent Trends</h3>
                            <div style="max-height: 50vh; overflow-y: auto;">
                                ${trendsHtml}
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div style="display: flex; gap: 0.75rem; justify-content: center; margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; flex-wrap: wrap;">
                            <button onclick="CLAWSApp.showColonyComparison()" style="padding: 0.75rem 1.5rem; background: ${this.getGradientStyle()}; color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                🏆 Colony Comparison
                            </button>
                            <button onclick="CLAWSApp.exportSystemData()" style="padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                📁 Export Data
                            </button>
                            <button onclick="this.closest('#claws-system-analytics-modal').remove()" style="padding: 0.75rem 1.5rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
        },

        /**
         * Show colony comparison
         */
        showColonyComparison: function() {
            // Simple summary of all colonies
            const totalColonies = this.colonies.length;
            const totalCats = this.colonies.reduce((sum, colony) => sum + (colony.cats || 0), 0);
            const totalTNR = this.colonies.reduce((sum, colony) => sum + (colony.tnrCats || 0), 0);
            const totalShelters = this.colonies.reduce((sum, colony) => sum + (colony.winterShelters || 0), 0);
            
            const averageTNR = totalCats > 0 ? Math.round((totalTNR / totalCats) * 100) : 0;
            
            // Show simple comparison modal
            const modal = document.createElement('div');
            modal.id = 'claws-colony-comparison-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 100%; max-height: 80vh; overflow-y: auto; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                        <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">🏆 Colony Summary</h2>
                        <button onclick="this.closest('#claws-colony-comparison-modal').remove()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.5rem;">×</button>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
                        <div style="text-align: center; padding: 1rem; background: #f3f4f6; border-radius: 0.5rem;">
                            <div style="font-size: 1.5rem; font-weight: bold; color: #1f2937;">${totalColonies}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">Colonies</div>
                        </div>
                        <div style="text-align: center; padding: 1rem; background: #f3f4f6; border-radius: 0.5rem;">
                            <div style="font-size: 1.5rem; font-weight: bold; color: #1f2937;">${totalCats}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">Total Cats</div>
                        </div>
                        <div style="text-align: center; padding: 1rem; background: #f3f4f6; border-radius: 0.5rem;">
                            <div style="font-size: 1.5rem; font-weight: bold; color: #1f2937;">${averageTNR}%</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">Avg TNR</div>
                        </div>
                        <div style="text-align: center; padding: 1rem; background: #f3f4f6; border-radius: 0.5rem;">
                            <div style="font-size: 1.5rem; font-weight: bold; color: #1f2937;">${totalShelters}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">Shelters</div>
                        </div>
                    </div>
                    
                    <div style="text-align: center;">
                        <button onclick="this.closest('#claws-colony-comparison-modal').remove()" style="padding: 0.75rem 2rem; background: #6b7280; color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                            Close
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // Close on backdrop click
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        },

        /**
         * REMOVED: Complex comparison functions to prevent infinite loops
         * prepareColonyComparisonData, showColonyComparisonModal, renderColonyBar, 
         * getSecurityLevel, renderSecurityLevels have all been removed
         */
        
        /**
         * Legacy function placeholder - now uses simple summary
         */
        prepareColonyComparisonData: function(colonies) {
            
            const comparisonColonies = colonies.map(colony => {
                // Use actual colony data structure (not history)
                const totalCats = parseInt(colony.cats) || 0;
                const totalAdultsAndSeniors = (parseInt(colony.adults) || 0) + (parseInt(colony.seniors) || 0);
                const tnrCount = parseInt(colony.tippedEars) || 0;
                const tnrPercentage = totalAdultsAndSeniors > 0 ? Math.round((tnrCount / totalAdultsAndSeniors) * 100) : 0;
                
                const processedColony = {
                    colony_name: colony.name || 'Unnamed Colony',
                    total_cats: totalCats,
                    cats_babies: parseInt(colony.babies) || 0,
                    cats_kittens: parseInt(colony.kittens) || 0,
                    cats_adults: parseInt(colony.adults) || 0,
                    cats_seniors: parseInt(colony.seniors) || 0,
                    tipped_ears: tnrCount,
                    winter_shelters: parseInt(colony.winterShelters) || 0,
                    tnr_percentage: tnrPercentage,
                    last_updated: colony.updated_at || colony.created_at || 'Unknown',
                    // Add security data using correct field names from colony structure
                    food_security: colony.foodSecurity || null,
                    water_security: colony.waterSecurity || null,
                    overall_safety: colony.safeLocation || null
                };
                
                return processedColony;
            });
            
            // Filter out colonies with no data (0 cats)
            const validColonies = comparisonColonies.filter(colony => colony.total_cats > 0);
            
            // Sort by total cats (descending), then by TNR percentage (descending)
            validColonies.sort((a, b) => {
                if (b.total_cats !== a.total_cats) {
                    return b.total_cats - a.total_cats;
                }
                return b.tnr_percentage - a.tnr_percentage;
            });
            
            console.log('Final processed comparison colonies:', validColonies);
            return validColonies;
        },

        /**
         * Show colony comparison modal
         */
        showColonyComparisonModal: function(colonies) {
            const modal = document.createElement('div');
            modal.id = 'claws-colony-comparison-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            let chartHtml = '';
            if (colonies.length === 0) {
                chartHtml = '<p style="text-align: center; color: #6b7280; font-style: italic; padding: 3rem;">No colonies found.</p>';
            } else {
                // Find max values for scaling
                const maxCats = Math.max(...colonies.map(c => c.total_cats));
                const maxTNR = Math.max(...colonies.map(c => c.tipped_ears));
                const maxShelters = Math.max(...colonies.map(c => c.winter_shelters));
                const maxHeight = Math.max(maxCats, 25); // Minimum height for security bars (5 levels × 5 cats each)
                
                chartHtml = `
                    <div style="display: flex; align-items: end; gap: 1rem; padding: 2rem 1rem; overflow-x: auto; min-height: 400px;">
                        ${colonies.map((colony, index) => this.renderColonyBar(colony, index + 1, maxHeight)).join('')}
                    </div>
                    
                    <!-- Legend -->
                    <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; margin-top: 1rem;">
                        <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem;">Legend</h4>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; font-size: 0.875rem;">
                            <div>
                                <strong>Cat Population:</strong><br>
                                <span style="background: #fee2e2; color: #991b1b; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Babies</span>
                                <span style="background: #fef3c7; color: #92400e; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Kittens</span>
                                <span style="background: #dcfce7; color: #166534; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Adults</span>
                                <span style="background: #dbeafe; color: #1e40af; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Seniors</span>
                            </div>
                            <div>
                                <strong>TNR Progress:</strong><br>
                                <span style="background: #8b5cf6; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Tipped Ears</span>
                            </div>
                            <div>
                                <strong>Winter Shelters:</strong><br>
                                <span style="background: #f59e0b; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Available</span>
                            </div>
                            <div>
                                <strong>Security Levels:</strong><br>
                                <span style="background: #dc2626; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Poor</span>
                                <span style="background: #ea580c; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Fair</span>
                                <span style="background: #ca8a04; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Good</span>
                                <span style="background: #16a34a; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Very Good</span>
                                <span style="background: #059669; color: white; padding: 0.125rem 0.25rem; border-radius: 0.25rem;">Excellent</span>
                            </div>
                        </div>
                    </div>
                `;
            }
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 70rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">🏆 Colony Comparison Analytics</h2>
                            <button onclick="this.closest('#claws-colony-comparison-modal').remove()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <p style="color: #6b7280; margin-bottom: 1.5rem; font-size: 0.875rem;">Comparative view of colony health metrics. Each bar shows population, TNR progress, shelter availability, and security levels.</p>
                        
                        <!-- Colony Chart -->
                        <div style="background: white; border: 1px solid #e5e7eb; border-radius: 0.5rem; overflow: hidden;">
                            ${chartHtml}
                        </div>
                        
                        <!-- Action Buttons -->
                        <div style="display: flex; gap: 0.75rem; justify-content: center; margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;">
                            <button onclick="CLAWSApp.showSystemAnalytics(); this.closest('#claws-colony-comparison-modal').remove();" style="padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Back to Analytics
                            </button>
                            <button onclick="this.closest('#claws-colony-comparison-modal').remove()" style="padding: 0.75rem 1.5rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
        },
        
        /**
         * Render a colony bar for the comparison chart
         */
        renderColonyBar: function(colony, rank, maxHeight) {
            const barHeight = 300; // Fixed pixel height for all bars
            const columnWidth = 25; // Width of each column in pixels
            const gap = 2; // Gap between columns
            
            // Calculate heights proportional to maxHeight
            const catBarHeight = Math.max((colony.total_cats / maxHeight) * barHeight, 10);
            const tnrBarHeight = Math.max((colony.tipped_ears / maxHeight) * barHeight, 10);
            const shelterBarHeight = Math.max((colony.winter_shelters / maxHeight) * barHeight, 10);
            
            // Get security levels (assume these come from colony data - will need to be implemented)
            const foodSecurity = this.getSecurityLevel(colony, 'food');
            const waterSecurity = this.getSecurityLevel(colony, 'water');
            const overallSafety = this.getSecurityLevel(colony, 'safety');
            
            return `
                <div style="display: flex; flex-direction: column; align-items: center; min-width: ${columnWidth * 6 + gap * 5}px;">
                    <!-- Colony rank and name -->
                    <div style="text-align: center; margin-bottom: 0.5rem; font-size: 0.75rem; font-weight: 600; color: #374151;">
                        #${rank}
                    </div>
                    <div style="text-align: center; margin-bottom: 1rem; font-size: 0.875rem; font-weight: 500; color: #1f2937; word-break: break-word; max-width: 120px;">
                        ${colony.colony_name}
                    </div>
                    
                    <!-- Multi-column bar chart -->
                    <div style="display: flex; align-items: end; gap: ${gap}px; height: ${barHeight}px;">
                        <!-- Column 1: Cat Population (stacked) -->
                        <div style="width: ${columnWidth}px; height: ${catBarHeight}px; background: ${colony.total_cats > 0 ? `linear-gradient(to top, 
                            #fee2e2 0%, 
                            #fee2e2 ${(colony.cats_babies / colony.total_cats) * 100}%, 
                            #fef3c7 ${(colony.cats_babies / colony.total_cats) * 100}%, 
                            #fef3c7 ${((colony.cats_babies + colony.cats_kittens) / colony.total_cats) * 100}%, 
                            #dcfce7 ${((colony.cats_babies + colony.cats_kittens) / colony.total_cats) * 100}%, 
                            #dcfce7 ${((colony.cats_babies + colony.cats_kittens + colony.cats_adults) / colony.total_cats) * 100}%, 
                            #dbeafe ${((colony.cats_babies + colony.cats_kittens + colony.cats_adults) / colony.total_cats) * 100}%, 
                            #dbeafe 100%)` : '#f3f4f6'}; 
                            border: 1px solid #d1d5db; border-radius: 2px; position: relative;" 
                            title="Total Cats: ${colony.total_cats} (Babies: ${colony.cats_babies}, Kittens: ${colony.cats_kittens}, Adults: ${colony.cats_adults}, Seniors: ${colony.cats_seniors})">
                            <div style="position: absolute; bottom: -1.5rem; left: 50%; transform: translateX(-50%); font-size: 0.625rem; font-weight: 600; color: #374151; white-space: nowrap;">${colony.total_cats}</div>
                        </div>
                        
                        <!-- Column 2: TNR Progress -->
                        <div style="width: ${columnWidth}px; height: ${tnrBarHeight}px; background: #8b5cf6; border: 1px solid #d1d5db; border-radius: 2px; position: relative;" 
                            title="Tipped Ears: ${colony.tipped_ears} (${colony.tnr_percentage}% TNR)">
                            <div style="position: absolute; bottom: -1.5rem; left: 50%; transform: translateX(-50%); font-size: 0.625rem; font-weight: 600; color: #374151; white-space: nowrap;">${colony.tipped_ears}</div>
                        </div>
                        
                        <!-- Column 3: Winter Shelters -->
                        <div style="width: ${columnWidth}px; height: ${shelterBarHeight}px; background: #f59e0b; border: 1px solid #d1d5db; border-radius: 2px; position: relative;" 
                            title="Winter Shelters: ${colony.winter_shelters}">
                            <div style="position: absolute; bottom: -1.5rem; left: 50%; transform: translateX(-50%); font-size: 0.625rem; font-weight: 600; color: #374151; white-space: nowrap;">${colony.winter_shelters}</div>
                        </div>
                        
                        <!-- Column 4: Food Security -->
                        ${this.renderSecurityLevels(foodSecurity, columnWidth, 'Food')}
                        
                        <!-- Column 5: Water Security -->
                        ${this.renderSecurityLevels(waterSecurity, columnWidth, 'Water')}
                        
                        <!-- Column 6: Overall Safety -->
                        ${this.renderSecurityLevels(overallSafety, columnWidth, 'Safety')}
                    </div>
                    
                    <!-- TNR percentage below -->
                    <div style="text-align: center; margin-top: 2rem; font-size: 0.75rem; color: #6b7280;">
                        ${colony.tnr_percentage}% TNR
                    </div>
                </div>
            `;
        },
        
        /**
         * Get security level for a colony metric (1-5 scale)
         */
        getSecurityLevel: function(colony, type) {
            // Convert text-based security levels to numeric values
            const securityLevelMap = {
                'Poor': 1,
                'Fair': 2, 
                'Good': 3,
                'Very Good': 4,
                'Excellent': 5,
                'Very Safe': 5  // For safety field
            };
            
            switch(type) {
                case 'food':
                    if (colony.foodSecurity !== null && colony.foodSecurity !== undefined && colony.foodSecurity !== '') {
                        const level = securityLevelMap[colony.foodSecurity] || parseInt(colony.foodSecurity) || 0;
                        return Math.max(level, 1); // Ensure at least level 1
                    }
                    // Fallback: Food security based on winter shelters and total cats ratio
                    const foodRatio = colony.winterShelters / Math.max(colony.cats, 1);
                    const foodLevel = foodRatio >= 0.8 ? 5 : foodRatio >= 0.6 ? 4 : foodRatio >= 0.4 ? 3 : foodRatio >= 0.2 ? 2 : 1;
                    return foodLevel;
                    
                case 'water':
                    if (colony.waterSecurity !== null && colony.waterSecurity !== undefined && colony.waterSecurity !== '') {
                        const level = securityLevelMap[colony.waterSecurity] || parseInt(colony.waterSecurity) || 0;
                        return Math.max(level, 1); // Ensure at least level 1
                    }
                    // Fallback: Water security based on TNR percentage (better managed colonies have better water)
                    const waterLevel = colony.tnrPercentage >= 80 ? 5 : colony.tnrPercentage >= 60 ? 4 : colony.tnrPercentage >= 40 ? 3 : colony.tnrPercentage >= 20 ? 2 : 1;
                    return waterLevel;
                    
                case 'safety':
                    if (colony.safeLocation !== null && colony.safeLocation !== undefined && colony.safeLocation !== '') {
                        const level = securityLevelMap[colony.safeLocation] || parseInt(colony.safeLocation) || 0;
                        return Math.max(level, 1); // Ensure at least level 1
                    }
                    // Fallback: Overall safety based on combination of factors
                    const safetyScore = (colony.tnrPercentage / 20) + (colony.winterShelters > 0 ? 1 : 0);
                    const safetyLevel = safetyScore >= 4.5 ? 5 : safetyScore >= 3.5 ? 4 : safetyScore >= 2.5 ? 3 : safetyScore >= 1.5 ? 2 : 1;
                    return safetyLevel;
                    
                default:
                    return 3; // Default to middle level
            }
        },
        
        /**
         * Render security levels as stacked colored segments (gummy worm style)
         */
        renderSecurityLevels: function(level, columnWidth, label) {
            const colors = [
                '#dc2626', // 1 - Poor - Red
                '#ea580c', // 2 - Fair - Orange
                '#ca8a04', // 3 - Good - Yellow
                '#16a34a', // 4 - Very Good - Green
                '#059669'  // 5 - Excellent - Emerald
            ];
            
            // Each segment represents 5 cats worth of height
            const segmentHeight = 12; // Height of each colored segment
            const totalHeight = level * segmentHeight;
            
            // Build segments from bottom (poor) to top (excellent)
            let segments = '';
            for (let i = 0; i < level; i++) {
                const segmentColor = colors[i];
                
                segments += `
                    <div style="position: absolute; 
                        bottom: ${i * segmentHeight}px; 
                        left: 0; 
                        width: 100%; 
                        height: ${segmentHeight}px; 
                        background: ${segmentColor};">
                    </div>
                `;
            }
            
            return `
                <div style="width: ${columnWidth}px; height: ${totalHeight}px; border: 1px solid #d1d5db; border-radius: 2px; position: relative;" 
                    title="${label} Security: Level ${level}/5">
                    ${segments}
                    <div style="position: absolute; bottom: -1.5rem; left: 50%; transform: translateX(-50%); font-size: 0.625rem; font-weight: 600; color: #374151; white-space: nowrap;">${level}/5</div>
                </div>
            `;
        },

        /**
         * Export system data
         */
        exportSystemData: function() {
            const url = this.config.apiUrl + 'colonies/export?format=csv&_wpnonce=' + encodeURIComponent(this.config.nonce);
            
            // Create a temporary link and click it to trigger download
            const link = document.createElement('a');
            link.href = url;
            link.download = 'colony-history-' + new Date().toISOString().split('T')[0] + '.csv';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            this.showAlert('Export started! Check your downloads folder.', 'success');
        },

        /**
         * Initialize Intake/Discharge functionality
         */
        initIntakeDischarge: function(tabType) {
            console.log(`Initializing ${tabType} tab...`);
            
            if (tabType === 'intake') {
                this.initIntakeTab();
            } else if (tabType === 'discharge') {
                this.initDischargeTab();
            }
            
            // Apply color scheme after charts are created
            setTimeout(() => {
                this.applyColorScheme();
            }, 500);
        },

        /**
         * Initialize Intake Tab
         */
        initIntakeTab: function() {
            const content = this.renderIntakeContent();
            const targetContent = document.getElementById('claws-intake-content');
            if (targetContent) {
                targetContent.innerHTML = content;
                this.loadIntakeData();
            }
        },

        /**
         * Initialize Discharge Tab  
         */
        initDischargeTab: function() {
            const content = this.renderDischargeContent();
            const targetContent = document.getElementById('claws-discharge-content');
            if (targetContent) {
                targetContent.innerHTML = content;
                this.loadDischargeData();
                this.loadIntakeData(); // Also load intake data for cat dropdown
            }
        },

        /**
         * Render intake content
         */
        renderIntakeContent: function() {
            return `
                <div style="padding: 1rem;">
                    <!-- Intake Statistics -->
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-bottom: 1rem;">
                        <div style="background: white; border-radius: 1rem; padding: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; text-align: center;">
                            <div style="width: 2.5rem; height: 2.5rem; background: #dbeafe; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin: 0 auto 0.5rem;">
                                <span style="color: #2563eb; font-size: 1.25rem;">❤️</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">Total Intakes</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #2563eb; margin: 0;" id="claws-total-intakes">0</p>
                        </div>
                        <div style="background: white; border-radius: 1rem; padding: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; text-align: center;">
                            <div style="width: 2.5rem; height: 2.5rem; background: #f3e8ff; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin: 0 auto 0.5rem;">
                                <span style="color: #7c3aed; font-size: 1.25rem;">📅</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">This Week</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #7c3aed; margin: 0;" id="claws-week-intakes">0</p>
                        </div>
                        <div style="background: white; border-radius: 1rem; padding: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; text-align: center;">
                            <div style="width: 2.5rem; height: 2.5rem; background: #dcfce7; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin: 0 auto 0.5rem;">
                                <span style="color: #059669; font-size: 1.25rem;">➕</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">This Month</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #059669; margin: 0;" id="claws-month-intakes">0</p>
                        </div>
                    </div>
                    
                    <!-- Intake Actions -->
                    <div class="claws-child-header" style="border-radius: 1rem; padding: 1.5rem; margin-bottom: 1rem;">
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h3 style="font-weight: 600; font-size: 1.125rem; margin: 0; color: inherit;">Intake Actions</h3>
                            <span style="font-size: 1.5rem;">➕</span>
                        </div>
                        <button onclick="CLAWSApp.showIntakeForm()" style="width: 100%; background: rgba(255, 255, 255, 0.2); border: none; border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; font-weight: 500; transition: background 0.2s; color: inherit;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                            New Cat Intake
                        </button>
                    </div>

                    <!-- Recent Intakes -->
                    <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;">Recent Intakes</h3>
                        <div id="claws-recent-intakes" style="display: flex; flex-direction: column; gap: 0.75rem;">
                            <!-- Recent intakes will be populated here -->
                        </div>
                    </div>

                    <!-- Intake Analysis Charts (Bottom Section) -->
                    <div style="display: flex; flex-direction: column; gap: 1rem; max-width: 400px; margin: 0 auto;">
                        <h2 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; text-align: center; font-size: 1.125rem;">My Intake Analytics</h2>
                        
                        <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: 1rem; text-align: center;">By Type</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-intake-type-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                        
                        <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: 1rem; text-align: center;">By Gender</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-intake-gender-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                        
                        <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: 1rem; text-align: center;">By Age</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-intake-age-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    ${this.config.isAdmin ? `
                    <!-- Admin Aggregate Analytics Section -->
                    <div style="display: flex; flex-direction: column; gap: 1rem; max-width: 500px; margin: 2rem auto 0;">
                        <h2 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; text-align: center; font-size: 1.125rem; border-top: 2px solid #e5e7eb; padding-top: 2rem;">
                            🔧 System-Wide Intake Analytics (Admin)
                        </h2>
                        
                        <!-- Admin Stats Grid -->
                        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-bottom: 1rem;">
                            <div style="background: linear-gradient(135deg, #f59e0b, #d97706); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.75rem;">System Total</h3>
                                <p style="font-size: 1.5rem; font-weight: bold; margin: 0;" id="claws-admin-total-intakes">0</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.75rem;">System Week</h3>
                                <p style="font-size: 1.5rem; font-weight: bold; margin: 0;" id="claws-admin-week-intakes">0</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #10b981, #059669); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.75rem;">System Month</h3>
                                <p style="font-size: 1.5rem; font-weight: bold; margin: 0;" id="claws-admin-month-intakes">0</p>
                            </div>
                        </div>
                        
                        <!-- Admin Charts -->
                        <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: 1rem; text-align: center;">System-Wide by Type</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-admin-intake-type-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                        
                        <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: 1rem; text-align: center;">By Volunteer</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-admin-intake-volunteer-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                    ` : ''}
                </div>
            `;
        },

        /**
         * Render discharge content
         */
        renderDischargeContent: function() {
            return `
                <div style="padding: 1rem;">
                    <!-- Discharge Statistics -->
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-bottom: 1rem;">
                        <div style="background: white; border-radius: 1rem; padding: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; text-align: center;">
                            <div style="width: 2.5rem; height: 2.5rem; background: #dcfce7; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin: 0 auto 0.5rem;">
                                <span style="color: #16a34a; font-size: 1.25rem;">➡️</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">Total Outcomes</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #16a34a; margin: 0;" id="claws-total-discharges">0</p>
                        </div>
                        <div style="background: white; border-radius: 1rem; padding: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; text-align: center;">
                            <div style="width: 2.5rem; height: 2.5rem; background: #f3e8ff; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin: 0 auto 0.5rem;">
                                <span style="color: #7c3aed; font-size: 1.25rem;">📅</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">This Week</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #7c3aed; margin: 0;" id="claws-week-discharges">0</p>
                        </div>
                        <div style="background: white; border-radius: 1rem; padding: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; text-align: center;">
                            <div style="width: 2.5rem; height: 2.5rem; background: #fef3c7; border-radius: 0.75rem; display: flex; align-items: center; justify-content: center; margin: 0 auto 0.5rem;">
                                <span style="color: #d97706; font-size: 1.25rem;">🏠</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">Adoptions</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #d97706; margin: 0;" id="claws-adoptions">0</p>
                        </div>
                    </div>
                    
                    <!-- Discharge Actions -->
                    <div class="claws-child-header" style="border-radius: 1rem; padding: 1.5rem; margin-bottom: 1rem;">
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h3 style="font-weight: 600; font-size: 1.125rem; margin: 0; color: inherit;">Record Outcomes</h3>
                            <span style="font-size: 1.5rem;">📋</span>
                        </div>
                        <button onclick="CLAWSApp.showDischargeForm()" style="width: 100%; background: rgba(255, 255, 255, 0.2); border: none; border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; font-weight: 500; transition: background 0.2s; color: inherit;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                            Record Outcome
                        </button>
                    </div>

                    <!-- Recent Discharges -->
                    <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;">Recent Outcomes</h3>  
                        <div id="claws-recent-discharges" style="display: flex; flex-direction: column; gap: 0.75rem;">
                            <!-- Recent discharges will be populated here -->
                        </div>
                    </div>

                    <!-- Discharge Outcome Analysis (Bottom Section) -->
                    <div style="max-width: 500px; margin: 0 auto;">
                        <h2 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; text-align: center; font-size: 1.125rem;">My Discharge Analytics</h2>
                        <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: 1rem; text-align: center;">Outcome Analysis</h3>
                            <div style="position: relative; height: 350px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-discharge-outcome-chart" style="max-height: 350px;"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    ${this.config.isAdmin ? `
                    <!-- Admin Aggregate Discharge Analytics Section -->
                    <div style="display: flex; flex-direction: column; gap: 1rem; max-width: 500px; margin: 2rem auto 0;">
                        <h2 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; text-align: center; font-size: 1.125rem; border-top: 2px solid #e5e7eb; padding-top: 2rem;">
                            🔧 System-Wide Discharge Analytics (Admin)
                        </h2>
                        
                        <!-- Admin Stats Grid -->
                        <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.75rem; margin-bottom: 1rem;">
                            <div style="background: linear-gradient(135deg, #f59e0b, #d97706); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.7rem;">System Total</h3>
                                <p style="font-size: 1.25rem; font-weight: bold; margin: 0;" id="claws-admin-total-discharges">0</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.7rem;">System Week</h3>
                                <p style="font-size: 1.25rem; font-weight: bold; margin: 0;" id="claws-admin-week-discharges">0</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #10b981, #059669); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.7rem;">System Month</h3>
                                <p style="font-size: 1.25rem; font-weight: bold; margin: 0;" id="claws-admin-month-discharges">0</p>
                            </div>
                            <div style="background: linear-gradient(135deg, #dc2626, #b91c1c); border-radius: 1rem; padding: 1rem; text-align: center; color: white;">
                                <h3 style="font-weight: 600; margin: 0 0 0.25rem; font-size: 0.7rem;">Adoptions</h3>
                                <p style="font-size: 1.25rem; font-weight: bold; margin: 0;" id="claws-admin-adoptions">0</p>
                            </div>
                        </div>
                        
                        <!-- Admin Charts -->
                        <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: 1rem; text-align: center;">System-Wide by Outcome</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-admin-discharge-outcome-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                        
                        <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: 1rem; text-align: center;">By Volunteer</h3>
                            <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                                <canvas id="claws-admin-discharge-volunteer-chart" style="max-height: 300px;"></canvas>
                            </div>
                        </div>
                    </div>
                    ` : ''}
                </div>
            `;
        },

        /**
         * Load intake data and update statistics
         */
        loadIntakeData: async function() {
            try {
                // Add aggressive cache-busting and user context
                const timestamp = new Date().getTime();
                const randomParam = Math.random().toString(36).substring(7);
                const response = await fetch(this.config.apiUrl + 'intakes?_=' + timestamp + '&r=' + randomParam + '&user_id=' + this.config.userId, {
                    credentials: 'include',
                    cache: 'no-cache',
                    headers: {
                        'X-WP-Nonce': this.config.nonce,
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0',
                        'Last-Modified': new Date(0).toUTCString()
                    }
                });
                if (response.ok) {
                    this.intakeRecords = await response.json();
                    console.log('Loaded intake records:', this.intakeRecords.length);
                } else {
                    console.error('Failed to load intake data:', response.status, response.statusText);
                    this.intakeRecords = [];
                }
            } catch (error) {
                console.error('Error loading intake data:', error);
                this.intakeRecords = [];
            }
            
            this.updateIntakeStatistics();
            this.updateRecentIntakes();
            this.updateIntakeCharts();
            
            // Load admin analytics if user is admin
            console.log('Checking if user is admin:', this.config.isAdmin);
            if (this.config.isAdmin) {
                console.log('User is admin, loading admin analytics');
                this.loadAdminIntakeAnalytics();
            } else {
                console.log('User is not admin, skipping admin analytics');
            }
        },

        /**
         * Load discharge data and update statistics
         */
        loadDischargeData: async function() {
            try {
                // Add aggressive cache-busting and user context
                const timestamp = new Date().getTime();
                const randomParam = Math.random().toString(36).substring(7);
                const response = await fetch(this.config.apiUrl + 'discharges?_=' + timestamp + '&r=' + randomParam + '&user_id=' + this.config.userId, {
                    credentials: 'include',
                    cache: 'no-cache',
                    headers: {
                        'X-WP-Nonce': this.config.nonce,
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0',
                        'Last-Modified': new Date(0).toUTCString()
                    }
                });
                if (response.ok) {
                    this.dischargeRecords = await response.json();
                } else {
                    this.dischargeRecords = [];
                }
            } catch (error) {
                console.log('Using demo discharge data:', error);
                this.dischargeRecords = [];
            }
            
            this.updateDischargeStatistics();
            this.updateRecentDischarges();
            this.updateDischargeCharts();
            
            // Load admin analytics if user is admin
            if (this.config.isAdmin) {
                this.loadAdminDischargeAnalytics();
            }
            
            // Refresh neonate care kitten dropdown since discharge status may have changed
            // Only reload feeding data if we're in the neonate care context
            if (typeof this.loadFeedingData === 'function' && document.getElementById('neonate-kitten-name')) {
                this.loadFeedingData();
            }
        },

        /**
         * Update intake statistics
         */
        updateIntakeStatistics: function() {
            const total = this.intakeRecords.length;
            const now = new Date();
            const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
            
            const thisWeek = this.intakeRecords.filter(record => new Date(record.date) >= weekAgo).length;
            const thisMonth = this.intakeRecords.filter(record => new Date(record.date) >= monthAgo).length;
            
            const totalElement = document.getElementById('claws-total-intakes');
            const weekElement = document.getElementById('claws-week-intakes');
            const monthElement = document.getElementById('claws-month-intakes');
            
            if (totalElement) totalElement.textContent = total;
            if (weekElement) weekElement.textContent = thisWeek;
            if (monthElement) monthElement.textContent = thisMonth;
        },

        /**
         * Update discharge statistics
         */
        updateDischargeStatistics: function() {
            const total = this.dischargeRecords.length;
            const now = new Date();
            const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
            
            const thisWeek = this.dischargeRecords.filter(record => new Date(record.date) >= weekAgo).length;
            const adoptions = this.dischargeRecords.filter(record => record.outcome === 'Adoption').length;
            
            const totalElement = document.getElementById('claws-total-discharges');
            const weekElement = document.getElementById('claws-week-discharges');
            const adoptionsElement = document.getElementById('claws-adoptions');
            
            if (totalElement) totalElement.textContent = total;
            if (weekElement) weekElement.textContent = thisWeek;
            if (adoptionsElement) adoptionsElement.textContent = adoptions;
        },

        /**
         * Update recent intakes list
         */
        updateRecentIntakes: function() {
            const container = document.getElementById('claws-recent-intakes');
            if (!container) return;
            
            if (this.intakeRecords.length === 0) {
                container.innerHTML = '<p style="color: #6b7280; font-size: 0.875rem; text-align: center; margin: 0;">No intake records yet</p>';
                return;
            }
            
            const recent = this.intakeRecords.slice(0, 5);
            container.innerHTML = recent.map(record => `
                <div style="padding: 0.75rem; border: 1px solid #e5e7eb; border-radius: 0.5rem; background: #f9fafb;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div style="flex: 1;">
                            <div style="font-weight: 500; color: #1f2937;">${record.cat_name || 'Unnamed'}</div>
                            <div style="font-size: 0.75rem; color: #6b7280; margin-top: 0.25rem;">
                                ${record.age || 'Unknown age'} • ${record.gender || 'Unknown gender'}
                            </div>
                        </div>
                        <div style="display: flex; align-items: center; gap: 0.5rem;">
                            <span style="font-size: 0.75rem; color: #6b7280;">${new Date(record.intake_date || record.date).toLocaleDateString()}</span>
                            <button onclick="CLAWSApp.editIntakeRecord(${record.id})" style="background: #3b82f6; color: white; border: none; border-radius: 0.25rem; padding: 0.25rem 0.5rem; font-size: 0.75rem; cursor: pointer;" title="Edit Record">✏️</button>
                        </div>
                    </div>
                </div>
            `).join('');
        },

        /**
         * Update recent discharges list
         */
        updateRecentDischarges: function() {
            const container = document.getElementById('claws-recent-discharges');
            if (!container) return;
            
            if (this.dischargeRecords.length === 0) {
                container.innerHTML = '<p style="color: #6b7280; font-size: 0.875rem; text-align: center; margin: 0;">No discharge records yet</p>';
                return;
            }
            
            const recent = this.dischargeRecords.slice(0, 5);
            container.innerHTML = recent.map(record => `
                <div style="padding: 0.75rem; border: 1px solid #e5e7eb; border-radius: 0.5rem; background: #f9fafb;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span style="font-weight: 500; color: #1f2937;">${record.cat_name || 'Unknown cat'}</span>
                        <span style="font-size: 0.75rem; color: #6b7280;">${new Date(record.date).toLocaleDateString()}</span>
                    </div>
                    <div style="font-size: 0.75rem; color: #6b7280; margin-top: 0.25rem;">
                        Outcome: ${record.outcome || 'Unknown'}
                    </div>
                </div>
            `).join('');
        },

        /**
         * Edit intake record
         */
        editIntakeRecord: function(recordId) {
            const record = this.intakeRecords.find(r => r.id == recordId);
            if (!record) {
                this.showAlert('Record not found.', 'error');
                return;
            }
            
            // Show the intake form modal
            this.showIntakeForm();
            
            // Populate form with existing data
            setTimeout(() => {
                // Use setTimeout to ensure form is rendered
                const fields = {
                    'claws-intake-date': record.intake_date || '',
                    'claws-intake-contact-first-name': record.contact_first_name || '',
                    'claws-intake-contact-last-name': record.contact_last_name || '',
                    'claws-intake-street': record.contact_street || '',
                    'claws-intake-city': record.contact_city || '',
                    'claws-intake-state': record.contact_state || '',
                    'claws-intake-zip': record.contact_zip || '',
                    'claws-intake-phone': record.phone || '',
                    'claws-intake-email': record.email || '',
                    'claws-intake-cat-name': record.cat_name || '',
                    'claws-intake-age': record.age || '',
                    'claws-intake-gender': record.gender || '',
                    'claws-intake-type': record.type || '',
                    'claws-intake-notes': record.notes || ''
                };
                
                Object.keys(fields).forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field) {
                        field.value = fields[fieldId];
                    }
                });
                
                // Change the save button to update mode
                const saveButton = document.querySelector('button[onclick="CLAWSApp.saveIntake()"]');
                if (saveButton) {
                    saveButton.textContent = '✏️ Update Record';
                    saveButton.onclick = () => this.updateIntakeRecord(recordId);
                    saveButton.style.background = this.getGradientStyle();
                }
                
                this.showAlert('Record loaded for editing. Click "Update Record" to save changes.', 'info');
            }, 100);
        },

        /**
         * Update intake record
         */
        updateIntakeRecord: async function(recordId) {
            const intakeData = this.collectIntakeFormData();
            if (!intakeData) {
                this.showAlert('Please fill in all required fields.', 'error');
                return;
            }

            this.showLoading();

            try {
                const response = await fetch(this.config.apiUrl + 'intake/' + recordId, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(intakeData)
                });

                if (response.ok) {
                    this.showAlert('Intake record updated successfully!', 'success');
                    this.resetIntakeSaveButton();
                    this.hideIntakeForm();
                    this.loadIntakeData(); // Refresh data
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to update intake record.', 'error');
                }
            } catch (error) {
                console.error('Intake update error:', error);
                this.showAlert('An error occurred while updating the intake record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Reset intake save button to normal state
         */
        resetIntakeSaveButton: function() {
            const saveButton = document.querySelector('button[onclick*="saveIntake"], button[onclick*="updateIntakeRecord"]');
            if (saveButton) {
                saveButton.textContent = '💾 Save Intake';
                saveButton.onclick = () => this.saveIntake();
                saveButton.style.background = 'linear-gradient(135deg, #10b981, #059669)';
            }
        },

        /**
         * Show intake form
         */
        showIntakeForm: function() {
            if (this.config.demoMode) {
                const proceed = confirm('You are in demo mode. Your changes will not be saved permanently. Continue?');
                if (!proceed) return;
            }
            
            const modal = document.getElementById('claws-intake-form-modal');
            if (modal) {
                modal.style.display = 'flex';
                this.resetIntakeForm();
            } else {
                this.createIntakeFormModal();
            }
        },

        /**
         * Show discharge form
         */
        showDischargeForm: function() {
            if (this.config.demoMode) {
                const proceed = confirm('You are in demo mode. Your changes will not be saved permanently. Continue?');
                if (!proceed) return;
            }
            
            const modal = document.getElementById('claws-discharge-form-modal');
            if (modal) {
                modal.style.display = 'flex';
                this.resetDischargeForm();
                this.populateCatDropdown();
            } else {
                this.createDischargeFormModal();
            }
        },

        /**
         * Initialize Neonate Care functionality
         */
        /**
         * Initialize Neonate Care Tab - Enhanced Version
         */
        initNeonateCare: function() {
            console.log('Initializing Enhanced Neonate Care...');
            
            const content = this.renderNeonateContent();
            const targetContent = document.getElementById('claws-neonate-content');
            if (targetContent) {
                targetContent.innerHTML = content;
                this.loadFeedingData();
                this.initializeNeonateFeatures();
            }
        },

        /**
         * Render enhanced neonate content
         */
        renderNeonateContent: function() {
            return `
                <div style="padding: 1rem; max-width: 1200px; margin: 0 auto;">
                    <!-- Header -->
                    <div style="text-align: center; margin-bottom: 2rem;">
                        <h2 style="font-size: 2rem; font-weight: bold; background: linear-gradient(135deg, #ec4899, #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0 0 0.5rem;">🍼 NeoNate Care</h2>
                        <p style="color: #6b7280; font-size: 1.125rem;">Bottle baby feeding schedule & tracking system</p>
                    </div>

                    <!-- Feeding Guide (Moved to Top) -->
                    <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: 1.5rem;">
                        <h3 style="font-weight: bold; color: #1f2937; margin: 0 0 1rem; display: flex; align-items: center;">
                            <span style="margin-right: 0.5rem;">💝</span> Kitten Feeding Guide
                        </h3>
                        <div style="overflow-x: auto;">
                            <table style="width: 100%; font-size: 0.875rem;">
                                <thead>
                                    <tr style="border-bottom: 2px solid #e5e7eb;">
                                        <th style="text-align: left; padding: 0.75rem; font-weight: bold; color: #374151;">Age</th>
                                        <th style="text-align: left; padding: 0.75rem; font-weight: bold; color: #374151;">Weight</th>
                                        <th style="text-align: left; padding: 0.75rem; font-weight: bold; color: #374151;">Formula</th>
                                        <th style="text-align: left; padding: 0.75rem; font-weight: bold; color: #374151;">Frequency</th>
                                    </tr>
                                </thead>
                                <tbody style="font-size: 0.8125rem;">
                                    <tr style="border-bottom: 1px solid #f3f4f6;" data-age="0-1-weeks">
                                        <td style="padding: 0.75rem;">
                                            <span style="font-weight: 600; color: #1f2937;">0–1 week</span>
                                        </td>
                                        <td style="padding: 0.75rem; color: #6b7280;">50–150g</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">2–6 mL</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">Every 2 hrs</td>
                                    </tr>
                                    <tr style="border-bottom: 1px solid #f3f4f6;" data-age="1-2-weeks">
                                        <td style="padding: 0.75rem;">
                                            <span style="font-weight: 600; color: #1f2937;">1–2 weeks</span>
                                        </td>
                                        <td style="padding: 0.75rem; color: #6b7280;">150–250g</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">6–10 mL</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">Every 2–3 hrs</td>
                                    </tr>
                                    <tr style="border-bottom: 1px solid #f3f4f6;" data-age="2-3-weeks">
                                        <td style="padding: 0.75rem;">
                                            <span style="font-weight: 600; color: #1f2937;">2–3 weeks</span>
                                        </td>
                                        <td style="padding: 0.75rem; color: #6b7280;">250–350g</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">10–14 mL</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">Every 3–4 hrs</td>
                                    </tr>
                                    <tr style="border-bottom: 1px solid #f3f4f6;" data-age="3-4-weeks">
                                        <td style="padding: 0.75rem;">
                                            <span style="font-weight: 600; color: #1f2937;">3–4 weeks</span>
                                        </td>
                                        <td style="padding: 0.75rem; color: #6b7280;">350–450g</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">14–18 mL</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">Every 4–5 hrs</td>
                                    </tr>
                                    <tr style="border-bottom: 1px solid #f3f4f6;" data-age="4-5-weeks">
                                        <td style="padding: 0.75rem;">
                                            <span style="font-weight: 600; color: #1f2937;">4–5 weeks</span>
                                        </td>
                                        <td style="padding: 0.75rem; color: #6b7280;">450–550g</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">18–22 mL</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">Every 5–6 hrs</td>
                                    </tr>
                                    <tr style="border-bottom: 1px solid #f3f4f6;" data-age="5-8-weeks">
                                        <td style="padding: 0.75rem;">
                                            <span style="font-weight: 600; color: #1f2937;">5–8 weeks</span>
                                        </td>
                                        <td style="padding: 0.75rem; color: #6b7280;">550–850g</td>
                                        <td style="padding: 0.75rem; color: #3b82f6; font-weight: 600;">Begin weaning</td>
                                        <td style="padding: 0.75rem; color: #6b7280;">Every 6 hrs</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div style="background: linear-gradient(135deg, #D6E4F0, #B8D4E8); border: 1px solid #00274D; border-radius: 0.75rem; padding: 1rem; margin-top: 1rem;">
                            <p style="color: #00274D; font-size: 0.875rem; margin: 0;">
                                💡 <strong>Tip:</strong> At 5-8 weeks, start offering wet food alongside bottle feeding to help with weaning.
                            </p>
                        </div>
                    </div>


                    <!-- Care Process Section -->
                    <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: 1.5rem;">
                        <div style="display: flex; align-items: center; color: #10b981; font-weight: 600; margin-bottom: 1rem;">
                            <span style="margin-right: 0.5rem;">✅</span>
                            <h3 style="font-weight: bold; color: #10b981; margin: 0;">Care Process</h3>
                        </div>
                        <div style="background: linear-gradient(135deg, #ecfdf5, #d1fae5); border: 1px solid #10b981; border-radius: 0.75rem; padding: 1rem;">
                            <ol style="color: #065f46; font-size: 0.875rem; margin: 0; padding-left: 1.25rem; line-height: 1.6;">
                                <li><strong>Stimulate genitals for urine/defecation</strong><br><span style="color: #047857; font-size: 0.8rem;">(before feeding)</span></li>
                                <li><strong>Pre-feed weight</strong><br><span style="color: #047857; font-size: 0.8rem;">(grams)</span></li>
                                <li><strong>Feed kitten</strong></li>
                                <li><strong>Post-feed weight</strong><br><span style="color: #047857; font-size: 0.8rem;">(grams)</span></li>
                                <li><strong>Clean face/butt</strong><br><span style="color: #047857; font-size: 0.8rem;">(always needed)</span></li>
                                <li><strong>Clean nest 1x per day or as needed</strong><br><span style="color: #047857; font-size: 0.8rem;">(maintain clean environment)</span></li>
                            </ol>
                        </div>
                    </div>

                    <!-- Feeding Form (Enhanced 2-line layout) -->
                    <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: 1.5rem;">
                        <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 1rem; width: 100%;">
                            <div style="display: flex; align-items: center;">
                                <div style="width: 2rem; height: 2rem; background: linear-gradient(135deg, #10b981, #059669); border-radius: 0.5rem; display: flex; align-items: center; justify-content: center; margin-right: 0.5rem;">
                                    <span style="color: white; font-size: 1rem;">📝</span>
                                </div>
                                <h3 style="font-weight: bold; color: #1f2937; margin: 0; font-size: 0.9rem;">Add New Feeding Record</h3>
                            </div>
                        </div>
                        
                        <!-- Line 1: Kitten Name -->
                        <div style="margin-bottom: 1rem;">
                            <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">Kitten Name</label>
                            <select id="neonate-kitten-name" style="width: 100%; padding: 0.75rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; font-size: 0.875rem; background: white; box-sizing: border-box;">
                                <option value="">Select a kitten...</option>
                            </select>
                        </div>
                        
                        <!-- Line 2: Date and Time of Feeding -->
                        <div style="margin-bottom: 1rem;">
                            <h4 style="font-weight: 600; color: #374151; margin: 0 0 0.5rem 0; font-size: 0.875rem; text-align: center;">Date and Time of Feeding</h4>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                                <div>
                                    <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">Date</label>
                                    <input type="date" id="neonate-feeding-date" style="width: 100%; padding: 0.75rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; font-size: 0.875rem; box-sizing: border-box;">
                                </div>
                                <div>
                                    <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">Time</label>
                                    <input type="time" id="neonate-feeding-time" style="width: 100%; padding: 0.75rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; font-size: 0.875rem; box-sizing: border-box;">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Line 3: Weight inputs with proper headers -->
                        <div style="margin-bottom: 1rem;">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 0.5rem;">
                                <h4 style="font-weight: 600; color: #374151; margin: 0; font-size: 0.875rem; text-align: center;">Pre feed weight (g)</h4>
                                <h4 style="font-weight: 600; color: #374151; margin: 0; font-size: 0.875rem; text-align: center;">Post feed weight (g)</h4>
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                                <div>
                                    <input type="number" id="neonate-pre-weight" placeholder="000" style="width: 100%; padding: 1rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; font-size: 1rem; box-sizing: border-box;" min="0" max="9999">
                                </div>
                                <div>
                                    <input type="number" id="neonate-post-weight" placeholder="000" style="width: 100%; padding: 1rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; font-size: 1rem; box-sizing: border-box;" min="0" max="9999">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Line 4: Notes (centered and taller) -->
                        <div style="text-align: center; margin-bottom: 1rem;">
                            <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">Notes & Observations</label>
                            <textarea id="neonate-notes" placeholder="Record any observations about this kitten's feeding behavior, health, or other notes..." style="width: 100%; padding: 0.75rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; font-size: 0.875rem; resize: vertical; box-sizing: border-box;" rows="4"></textarea>
                        </div>
                        
                        <!-- Save Button (moved to bottom) -->
                        <div style="text-align: center;">
                            <button onclick="CLAWSApp.saveFeedingRecord()" style="background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: white; border: none; border-radius: 0.5rem; padding: 0.75rem 1.5rem; font-weight: 600; cursor: pointer; font-size: 0.875rem; box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.4);">
                                💾 Save Record
                            </button>
                        </div>
                    </div>

                    <!-- Weight Progress 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: 1.5rem;">
                        <h3 style="font-weight: bold; color: #1f2937; margin: 0 0 1rem; display: flex; align-items: center;">
                            <span style="margin-right: 0.5rem;">📊</span> Weight Progress Tracking
                        </h3>
                        <div style="position: relative; height: 400px; margin-bottom: 1rem;">
                            <canvas id="neonate-weight-chart" style="max-height: 400px;"></canvas>
                        </div>
                        
                        <!-- Chart Display Options -->
                        <div style="border-top: 1px solid #e5e7eb; padding-top: 1rem; margin-bottom: 1rem;">
                            <h4 style="font-weight: 600; color: #374151; margin: 0 0 0.75rem;">Chart Display Mode:</h4>
                            <div style="display: flex; gap: 1rem;">
                                <label style="display: flex; align-items: center; cursor: pointer; padding: 0.5rem 1rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; transition: all 0.2s;" id="sawtooth-option">
                                    <input type="radio" name="chartDisplayMode" value="sawtooth" checked style="margin-right: 0.5rem; accent-color: #3b82f6;">
                                    <span style="font-weight: 600; color: #374151;">📈 Sawtooth (Pre & Post Weights)</span>
                                </label>
                                <label style="display: flex; align-items: center; cursor: pointer; padding: 0.5rem 1rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; transition: all 0.2s;" id="smooth-option">
                                    <input type="radio" name="chartDisplayMode" value="smooth" style="margin-right: 0.5rem; accent-color: #3b82f6;">
                                    <span style="font-weight: 600; color: #374151;">📊 Smooth (Post Weights Only)</span>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Kitten Selector -->
                        <div style="border-top: 1px solid #e5e7eb; padding-top: 1rem;">
                            <h4 style="font-weight: 600; color: #374151; margin: 0 0 0.75rem;">Select Kittens to Display:</h4>
                            <div id="neonate-kitten-checkboxes" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0.75rem;">
                                <!-- Kitten checkboxes will be populated here -->
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions (Simplified) -->
                    <div class="claws-child-header" style="border-radius: 1rem; padding: 1.5rem; margin-bottom: 1.5rem;">
                        <h3 style="font-weight: bold; color: inherit; margin: 0 0 1rem;">Quick Actions</h3>
                        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem;">
                            <button onclick="CLAWSApp.exportFeedingData()" style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; border: none; border-radius: 0.75rem; padding: 1rem; font-weight: 600; cursor: pointer; transition: transform 0.2s; box-shadow: 0 4px 6px -1px rgba(139, 92, 246, 0.4);" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='translateY(0)'">
                                <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">📊</div>
                                <div>Export Data</div>
                            </button>
                            <button onclick="CLAWSApp.showCareGuide()" style="background: linear-gradient(135deg, #f59e0b, #d97706); color: white; border: none; border-radius: 0.75rem; padding: 1rem; font-weight: 600; cursor: pointer; transition: transform 0.2s; box-shadow: 0 4px 6px -1px rgba(245, 158, 11, 0.4);" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='translateY(0)'">
                                <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">📖</div>
                                <div>Care Guide</div>
                            </button>
                        </div>
                    </div>


                    <!-- Feeding Records -->
                    <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: bold; color: #1f2937; margin: 0 0 1rem;">Feeding Records</h3>
                        <div id="neonate-recent-records" style="max-height: 400px; overflow-y: auto;">
                            <!-- All feeding records will be populated here -->
                        </div>
                    </div>
                </div>
            `;
        },

        /**
         * Initialize neonate features after content is rendered
         */
        initializeNeonateFeatures: function() {
            this.selectedAgeRange = '0-1-weeks';
            this.ageRangeStartDate = new Date().toISOString().split('T')[0]; // Set to today initially
            this.chartDisplayMode = 'sawtooth';
            
            // Updated feeding schedules based on PDF
            this.feedingSchedules = {
                '0-1-weeks': ['5:00 AM', '7:00 AM', '9:00 AM', '11:00 AM', '1:00 PM', '3:00 PM', '5:00 PM', '7:00 PM', '9:00 PM', '11:00 PM', '1:00 AM', '3:00 AM'],
                '1-2-weeks': ['6:00 AM', '9:00 AM', '12:00 PM', '3:00 PM', '6:00 PM', '9:00 PM', '12:00 AM', '3:00 AM'],
                '2-3-weeks': ['6:00 AM', '10:00 AM', '2:00 PM', '6:00 PM', '10:00 PM', '2:00 AM'],
                '3-4-weeks': ['6:00 AM', '11:00 AM', '4:00 PM', '9:00 PM', '2:00 AM'],
                '4-5-weeks': ['7:00 AM', '1:00 PM', '7:00 PM', '1:00 AM'],
                '5-8-weeks': ['7:00 AM', '1:00 PM', '7:00 PM', '1:00 AM']
            };
            
            this.setupNeonateEventListeners();
            this.updateScheduleDisplay();
            this.populateKittenDropdown();
            this.initializeDateTimeInputs();
            this.updateWeightChart();
            this.checkAgeProgression(); // Check if age should auto-advance
        },

        /**
         * Initialize date/time inputs with current date/time
         */
        initializeDateTimeInputs: function() {
            const now = new Date();
            const dateInput = document.getElementById('neonate-feeding-date');
            const timeInput = document.getElementById('neonate-feeding-time');
            
            // Only set date if it's currently empty - don't auto-advance dates
            if (dateInput && !dateInput.value) {
                dateInput.value = now.toISOString().split('T')[0]; // YYYY-MM-DD format
            }
            
            // Always set current time
            if (timeInput) {
                const hours = now.getHours().toString().padStart(2, '0');
                const minutes = now.getMinutes().toString().padStart(2, '0');
                timeInput.value = `${hours}:${minutes}`; // HH:MM format
            }
        },

        /**
         * Setup event listeners for neonate care
         */
        setupNeonateEventListeners: function() {            
            // Chart display mode radio buttons
            document.querySelectorAll('input[name="chartDisplayMode"]').forEach(radio => {
                radio.addEventListener('change', (e) => {
                    if (e.target.checked) {
                        this.chartDisplayMode = e.target.value;
                        this.updateWeightChart();
                        
                        // Update visual styling
                        document.getElementById('sawtooth-option').style.borderColor = e.target.value === 'sawtooth' ? '#3b82f6' : '#e5e7eb';
                        document.getElementById('smooth-option').style.borderColor = e.target.value === 'smooth' ? '#3b82f6' : '#e5e7eb';
                    }
                });
            });
        },

        /**
         * Update age range and related displays
         */
        updateAgeRange: function(newRange, manuallySelected = false) {
            this.selectedAgeRange = newRange;
            
            // If manually selected, reset the age progression timer
            if (manuallySelected) {
                this.ageRangeStartDate = new Date().toISOString().split('T')[0];
                console.log(`Age range manually set to ${newRange}, timer reset to ${this.ageRangeStartDate}`);
            }
            
            // Update display
            const displayText = newRange.replace('-weeks', ' weeks').replace('-', ' to ');
            const displayElement = document.getElementById('current-age-display');
            if (displayElement) {
                displayElement.textContent = displayText;
            }
            
            // Update schedule display
            this.updateScheduleDisplay();
        },

        /**
         * Update feeding schedule display
         */
        updateScheduleDisplay: function() {
            const schedule = this.feedingSchedules[this.selectedAgeRange] || this.feedingSchedules['0-1-weeks'];
            const scheduleText = schedule.join(' → ');
            
            const scheduleElement = document.getElementById('recommended-schedule');
            if (scheduleElement) {
                scheduleElement.textContent = scheduleText;
            }
        },
        
        /**
         * Check if age range should automatically progress after 7 days
         */
        checkAgeProgression: function() {
            if (!this.ageRangeStartDate) {
                return;
            }
            
            const startDate = new Date(this.ageRangeStartDate);
            const currentDate = new Date();
            const daysDiff = Math.floor((currentDate - startDate) / (1000 * 60 * 60 * 24));
            
            if (daysDiff >= 7) {
                const nextAgeRange = this.getNextAgeRange(this.selectedAgeRange);
                if (nextAgeRange && nextAgeRange !== this.selectedAgeRange) {
                    console.log(`Auto-advancing from ${this.selectedAgeRange} to ${nextAgeRange} after ${daysDiff} days`);
                    this.autoAdvanceAge(nextAgeRange);
                }
            }
        },
        
        /**
         * Get the next age range in sequence
         */
        getNextAgeRange: function(currentRange) {
            const ageSequence = ['0-1-weeks', '1-2-weeks', '2-3-weeks', '3-4-weeks', '4-5-weeks', '5-8-weeks'];
            const currentIndex = ageSequence.indexOf(currentRange);
            
            if (currentIndex >= 0 && currentIndex < ageSequence.length - 1) {
                return ageSequence[currentIndex + 1];
            }
            
            return null; // Already at final stage
        },
        
        /**
         * Automatically advance to next age range
         */
        autoAdvanceAge: function(newRange) {
            // Update age range (not manually selected, so don't reset timer)
            this.updateAgeRange(newRange, false);
            
            // Reset the timer for the new age range
            this.ageRangeStartDate = new Date().toISOString().split('T')[0];
            
            // Show notification to user
            this.showAlert(`Age range automatically advanced to ${newRange.replace('-weeks', ' weeks').replace('-', ' to ')} after 7 days of feeding!`, 'info');
        },



        /**
         * Load feeding data
         */
        loadFeedingData: async function() {
            try {
                // Load feeding records with aggressive cache-busting and user context
                const timestamp = new Date().getTime();
                const randomParam = Math.random().toString(36).substring(7);
                const feedingResponse = await fetch(this.config.apiUrl + 'feedings?_=' + timestamp + '&r=' + randomParam + '&user_id=' + this.config.userId, {
                    credentials: 'include',
                    cache: 'no-cache',
                    headers: {
                        'X-WP-Nonce': this.config.nonce,
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0',
                        'Last-Modified': new Date(0).toUTCString()
                    }
                });
                
                if (feedingResponse.ok) {
                    this.feedingRecords = await feedingResponse.json();
                    console.log('Loaded feeding records:', this.feedingRecords.length);
                    console.log('Current user info - ID:', this.config.userId, 'Login:', this.config.userLogin, 'Display:', this.config.currentUser);
                } else {
                    console.error('Failed to load feeding data:', feedingResponse.status, feedingResponse.statusText);
                    this.feedingRecords = [];
                }
                
                // Load baby kittens for dropdown with cache-busting
                const kittensTimestamp = new Date().getTime();
                const kittensResponse = await fetch(this.config.apiUrl + 'baby-kittens?_=' + kittensTimestamp + '&user_id=' + this.config.userId, {
                    credentials: 'include',
                    cache: 'no-cache',
                    headers: {
                        'X-WP-Nonce': this.config.nonce,
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache'
                    }
                });
                
                if (kittensResponse.ok) {
                    this.babyKittens = await kittensResponse.json();
                    this.populateKittenDropdown();
                } else {
                    this.babyKittens = [];
                }
                
                this.updateWeightChart();
                this.updateKittenCheckboxes();
                this.updateRecentRecords();
            } catch (error) {
                console.log('Error loading feeding data:', error);
                this.feedingRecords = [];
                this.babyKittens = [];
            }
        },

        /**
         * Save feeding record
         */
        saveFeedingRecord: async function() {
            const kittenName = document.getElementById('neonate-kitten-name').value;
            const preWeight = document.getElementById('neonate-pre-weight').value;
            const postWeight = document.getElementById('neonate-post-weight').value;
            const notes = document.getElementById('neonate-notes').value;
            const feedingDate = document.getElementById('neonate-feeding-date').value;
            const feedingTime = document.getElementById('neonate-feeding-time').value;
            
            if (!kittenName) {
                this.showAlert('Please select a kitten name.', 'warning');
                return;
            }
            
            if (!preWeight || !postWeight) {
                this.showAlert('Please enter both pre and post weights.', 'warning');
                return;
            }
            
            if (!feedingDate || !feedingTime) {
                this.showAlert('Please select both date and time for the feeding.', 'warning');
                return;
            }
            
            // Convert time to HH:MM:SS format if needed
            const timeWithSeconds = feedingTime.includes(':') && feedingTime.split(':').length === 2 
                ? feedingTime + ':00' 
                : feedingTime;
            
            const feedingData = {
                kitten_name: kittenName,
                pre_weight: parseFloat(preWeight),
                post_weight: parseFloat(postWeight),
                notes: notes,
                date: feedingDate,
                time: timeWithSeconds,
            };
            
            this.showLoading();
            
            try {
                const response = await fetch(this.config.apiUrl + 'feeding', {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(feedingData)
                });
                
                if (response.ok) {
                    this.showAlert('Feeding record saved successfully!', 'success');
                    
                    // Clear form
                    this.clearForm();
                    
                    // Reload data
                    this.loadFeedingData();
                    
                    // Check if age should progress after saving feeding data
                    this.checkAgeProgression();
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to save feeding record.', 'error');
                }
            } catch (error) {
                console.error('Save error:', error);
                this.showAlert('An error occurred while saving the record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Update feeding records display
         */
        updateRecentRecords: function() {
            const container = document.getElementById('neonate-recent-records');
            if (!container) return;
            
            if (this.feedingRecords.length === 0) {
                container.innerHTML = '<p style="color: #6b7280; font-style: italic; text-align: center; padding: 2rem;">No feeding records yet. Add your first record above!</p>';
                return;
            }
            
            container.innerHTML = this.feedingRecords.map((record, index) => {
                // Calculate gain/loss from previous feeding's post-weight
                let weightChangeFromPrevious = null;
                let gainLossText = 'N/A';
                let gainColor = '#6b7280';
                
                // Find the previous feeding record for the same kitten
                for (let i = index + 1; i < this.feedingRecords.length; i++) {
                    if (this.feedingRecords[i].kitten_name === record.kitten_name) {
                        const previousPostWeight = parseFloat(this.feedingRecords[i].post_weight);
                        const currentPostWeight = parseFloat(record.post_weight);
                        weightChangeFromPrevious = (currentPostWeight - previousPostWeight).toFixed(1);
                        gainLossText = `${weightChangeFromPrevious > 0 ? '+' : ''}${weightChangeFromPrevious}g`;
                        gainColor = weightChangeFromPrevious > 0 ? '#10b981' : weightChangeFromPrevious < 0 ? '#ef4444' : '#6b7280';
                        break;
                    }
                }
                
                return `
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; background: #f9fafb; border-radius: 0.5rem; border: 1px solid #e5e7eb; margin-bottom: 0.5rem;">
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #1f2937;">${record.kitten_name}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">${record.feeding_date} ${record.feeding_time}</div>
                        </div>
                        <div style="text-align: center; flex: 1;">
                            <div style="font-size: 0.875rem; color: #374151; font-weight: 600;">Pre: ${record.pre_weight}g | Post: ${record.post_weight}g</div>
                            <div style="font-size: 0.75rem; color: ${gainColor}; font-weight: 600;">
                                Gain/Loss from last feeding: ${gainLossText}
                            </div>
                        </div>
                        <div style="display: flex; gap: 0.5rem;">
                            <button onclick="CLAWSApp.editFeedingRecord(${record.id})" style="background: #3b82f6; color: white; border: none; border-radius: 0.25rem; padding: 0.25rem 0.5rem; font-size: 0.75rem; cursor: pointer;" title="Edit Record">✏️</button>
                            <button onclick="CLAWSApp.deleteFeedingRecord(${record.id})" style="background: #ef4444; color: white; border: none; border-radius: 0.25rem; padding: 0.25rem 0.5rem; font-size: 0.75rem; cursor: pointer;" title="Delete Record">🗑️</button>
                        </div>
                    </div>
                `;
            }).join('');
        },

        /**
         * Update weight progress chart
         */
        updateWeightChart: function() {
            const canvas = document.getElementById('neonate-weight-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.neonateWeightChart) {
                this.neonateWeightChart.destroy();
            }
            
            if (this.feedingRecords.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '16px system-ui';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No feeding data available yet', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            // Group records by kitten
            const kittenData = {};
            this.feedingRecords.forEach(record => {
                const name = record.kitten_name;
                if (!kittenData[name]) {
                    kittenData[name] = [];
                }
                kittenData[name].push({
                    date: new Date(record.feeding_date + ' ' + record.feeding_time),
                    preWeight: parseFloat(record.pre_weight),
                    postWeight: parseFloat(record.post_weight)
                });
            });
            
            // Sort data by date for each kitten
            Object.keys(kittenData).forEach(name => {
                kittenData[name].sort((a, b) => a.date - b.date);
            });
            
            // Calculate daily weight changes for each kitten
            const dailyWeightChanges = {};
            Object.keys(kittenData).forEach(name => {
                dailyWeightChanges[name] = this.calculateDailyWeightChanges(kittenData[name]);
            });
            
            const colors = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899'];
            const datasets = [];
            
            // Calculate min/max weights across all data for dynamic Y-axis
            let allWeights = [];
            Object.keys(kittenData).forEach(name => {
                kittenData[name].forEach(record => {
                    allWeights.push(record.preWeight, record.postWeight);
                });
            });
            
            const minWeight = allWeights.length > 0 ? Math.min(...allWeights) : 0;
            const maxWeight = allWeights.length > 0 ? Math.max(...allWeights) : 100;
            const weightRange = maxWeight - minWeight;
            
            // Dynamic Y-axis bounds
            const yAxisMin = Math.max(0, minWeight - 10); // Don't go below 0
            const yAxisMax = maxWeight + 10;
            
            // Dynamic step size based on range
            let stepSize;
            if (weightRange <= 50) stepSize = 5;      // Very tight range: 5g steps
            else if (weightRange <= 100) stepSize = 10;  // Small range: 10g steps  
            else if (weightRange <= 200) stepSize = 20;  // Medium range: 20g steps
            else stepSize = 25;                          // Large range: 25g steps
            
            if (this.chartDisplayMode === 'sawtooth') {
                // Sawtooth mode: show both pre and post weights with connecting lines
                Object.keys(kittenData).forEach((name, index) => {
                    const color = colors[index % colors.length];
                    const sawtoothData = [];
                    
                    kittenData[name].forEach(record => {
                        // Add pre-weight point at exact feeding time
                        sawtoothData.push({
                            x: record.date, // Exact feeding time
                            y: record.preWeight
                        });
                        // Add post-weight point 15 minutes after feeding
                        sawtoothData.push({
                            x: new Date(record.date.getTime() + 15 * 60000), // 15 minutes after feeding
                            y: record.postWeight
                        });
                    });
                    
                    datasets.push({
                        label: `${name} (Sawtooth)`,
                        data: sawtoothData,
                        borderColor: color,
                        backgroundColor: color + '20',
                        tension: 0.1,
                        pointRadius: 3,
                        pointHoverRadius: 5,
                        hidden: false // Show by default
                    });
                });
            } else {
                // Smooth mode: show only post-feeding weights
                Object.keys(kittenData).forEach((name, index) => {
                    const color = colors[index % colors.length];
                    
                    datasets.push({
                        label: `${name} (Smooth)`,
                        data: kittenData[name].map(record => ({
                            x: record.date,
                            y: record.postWeight
                        })),
                        borderColor: color,
                        backgroundColor: color + '20',
                        tension: 0.4,
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        hidden: false // Show by default
                    });
                });
            }
            
            const chartTitle = this.chartDisplayMode === 'sawtooth' 
                ? 'Kitten Weight Progress (Pre & Post Feeding)'
                : 'Kitten Weight Progress (Post Feeding Only)';
            
            this.neonateWeightChart = new Chart(ctx, {
                type: 'line',
                data: { datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: chartTitle,
                            font: { size: 16, weight: 'bold' }
                        },
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                title: function(context) {
                                    return new Date(context[0].parsed.x).toLocaleString();
                                },
                                label: function(context) {
                                    const weight = context.parsed.y;
                                    const kitten = context.dataset.label.split(' (')[0];
                                    return `${kitten}: ${weight}g`;
                                },
                                afterLabel: function(context) {
                                    // Show daily weight change if available
                                    const kitten = context.dataset.label.split(' (')[0];
                                    const currentDate = new Date(context.parsed.x);
                                    const changes = dailyWeightChanges[kitten];
                                    
                                    if (changes) {
                                        const dayChange = changes.find(change => 
                                            change.date.toDateString() === currentDate.toDateString()
                                        );
                                        
                                        if (dayChange) {
                                            const changeText = dayChange.change >= 0 ? 
                                                `Daily gain: +${dayChange.change.toFixed(1)}g` : 
                                                `Daily loss: ${dayChange.change.toFixed(1)}g`;
                                            return changeText;
                                        }
                                    }
                                    return '';
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                unit: 'day',
                                displayFormats: {
                                    day: 'MMM dd'
                                }
                            },
                            title: {
                                display: true,
                                text: 'Date & Time'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Weight (grams)'
                            },
                            min: yAxisMin,
                            max: yAxisMax,
                            ticks: {
                                stepSize: stepSize
                            }
                        }
                    }
                }
            });
        },

        /**
         * Calculate daily weight changes for a kitten
         */
        calculateDailyWeightChanges: function(kittenRecords) {
            const dailyWeights = {};
            const dailyChanges = [];
            
            // Group records by date and find the last post-weight of each day
            kittenRecords.forEach(record => {
                const dateKey = record.date.toDateString();
                if (!dailyWeights[dateKey] || record.date > dailyWeights[dateKey].date) {
                    dailyWeights[dateKey] = {
                        date: record.date,
                        lastPostWeight: record.postWeight
                    };
                }
            });
            
            // Sort dates and calculate day-to-day changes
            const sortedDates = Object.keys(dailyWeights).sort((a, b) => 
                new Date(a) - new Date(b)
            );
            
            for (let i = 1; i < sortedDates.length; i++) {
                const prevDate = sortedDates[i - 1];
                const currDate = sortedDates[i];
                const prevWeight = dailyWeights[prevDate].lastPostWeight;
                const currWeight = dailyWeights[currDate].lastPostWeight;
                const change = currWeight - prevWeight;
                
                dailyChanges.push({
                    date: new Date(currDate),
                    change: change,
                    previousWeight: prevWeight,
                    currentWeight: currWeight
                });
            }
            
            return dailyChanges;
        },

        /**
         * Calculate daily weight changes for checkbox display (simplified version)
         */
        calculateKittenDailyChanges: function(kittenRecords) {
            const dailyWeights = {};
            
            // Group records by date and find the last post-weight of each day  
            kittenRecords.forEach(record => {
                const date = new Date(record.feeding_date + ' ' + record.feeding_time);
                const dateKey = date.toDateString();
                if (!dailyWeights[dateKey] || date > dailyWeights[dateKey].date) {
                    dailyWeights[dateKey] = {
                        date: date,
                        lastPostWeight: parseFloat(record.post_weight)
                    };
                }
            });
            
            // Sort dates and calculate day-to-day changes
            const sortedDates = Object.keys(dailyWeights).sort((a, b) => 
                new Date(a) - new Date(b)
            );
            
            const dailyChanges = [];
            for (let i = 1; i < sortedDates.length; i++) {
                const prevWeight = dailyWeights[sortedDates[i - 1]].lastPostWeight;
                const currWeight = dailyWeights[sortedDates[i]].lastPostWeight;
                dailyChanges.push(currWeight - prevWeight);
            }
            
            return dailyChanges;
        },

        /**
         * Toggle kitten data on chart
         */
        toggleKittenChart: function(kittenName, show) {
            if (!this.neonateWeightChart) return;
            
            const dataset = this.neonateWeightChart.data.datasets.find(d => 
                d.label.startsWith(kittenName)
            );
            
            if (dataset) {
                dataset.hidden = !show;
                this.neonateWeightChart.update();
            }
        },

        /**
         * Export feeding data
         */
        exportFeedingData: function() {
            if (this.feedingRecords.length === 0) {
                this.showAlert('No feeding data to export.', 'warning');
                return;
            }
            
            const csvData = 'Date,Time,Kitten Name,Pre Weight (g),Post Weight (g),Weight Gain (g),Notes\n' +
                this.feedingRecords.map(record => {
                    const weightGain = (parseFloat(record.post_weight) - parseFloat(record.pre_weight)).toFixed(1);
                    return `${record.feeding_date},${record.feeding_time},"${record.kitten_name}",${record.pre_weight},${record.post_weight},${weightGain},"${record.notes || ''}"`;
                }).join('\n');
            
            const blob = new Blob([csvData], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `neonate_feeding_data_${new Date().toISOString().split('T')[0]}.csv`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            this.showAlert('Feeding data exported successfully!', 'success');
        },

        /**
         * Edit feeding record
         */
        editFeedingRecord: function(recordId) {
            const record = this.feedingRecords.find(r => r.id == recordId);
            if (!record) {
                this.showAlert('Record not found.', 'error');
                return;
            }
            
            // Populate form with existing data (only fields that exist in current form)
            const kittenNameField = document.getElementById('neonate-kitten-name');
            const preWeightField = document.getElementById('neonate-pre-weight');
            const postWeightField = document.getElementById('neonate-post-weight');
            const notesField = document.getElementById('neonate-notes');
            const dateField = document.getElementById('neonate-feeding-date');
            const timeField = document.getElementById('neonate-feeding-time');
            
            if (kittenNameField) kittenNameField.value = record.kitten_name;
            if (preWeightField) preWeightField.value = record.pre_weight;
            if (postWeightField) postWeightField.value = record.post_weight;
            if (notesField) notesField.value = record.notes || '';
            
            // Populate date/time fields
            if (dateField) dateField.value = record.feeding_date;
            if (timeField) {
                const timeValue = record.feeding_time.length === 8 ? record.feeding_time.substring(0, 5) : record.feeding_time;
                timeField.value = timeValue;
            }
            
            // Change save button to update mode
            const saveButton = document.querySelector('button[onclick="CLAWSApp.saveFeedingRecord()"]');
            if (saveButton) {
                saveButton.textContent = '✏️ Update Record';
                saveButton.onclick = () => this.updateFeedingRecord(recordId);
                saveButton.style.background = 'linear-gradient(135deg, #f59e0b, #d97706)';
            }
            
            this.showAlert('Record loaded for editing. Click "Update Record" to save changes.', 'info');
            
            // Scroll to the feeding form for user convenience  
            if (kittenNameField) {
                // Scroll to the form container (parent div)
                const formContainer = kittenNameField.closest('div[style*="background: white"]');
                if (formContainer) {
                    formContainer.scrollIntoView({ 
                        behavior: 'smooth', 
                        block: 'center' 
                    });
                } else {
                    // Fallback to the field itself
                    kittenNameField.scrollIntoView({ 
                        behavior: 'smooth', 
                        block: 'center' 
                    });
                }
            }
        },

        /**
         * Update feeding record
         */
        updateFeedingRecord: async function(recordId) {
            const kittenName = document.getElementById('neonate-kitten-name').value;
            const preWeight = document.getElementById('neonate-pre-weight').value;
            const postWeight = document.getElementById('neonate-post-weight').value;
            const notes = document.getElementById('neonate-notes').value;
            const feedingDate = document.getElementById('neonate-feeding-date').value;
            const feedingTime = document.getElementById('neonate-feeding-time').value;
            
            if (!kittenName) {
                this.showAlert('Please select a kitten name.', 'warning');
                return;
            }
            
            if (!preWeight || !postWeight) {
                this.showAlert('Please enter both pre and post weights.', 'warning');
                return;
            }
            
            if (!feedingDate || !feedingTime) {
                this.showAlert('Please select both date and time for the feeding.', 'warning');
                return;
            }
            
            // Convert time to HH:MM:SS format if needed
            const timeWithSeconds = feedingTime.includes(':') && feedingTime.split(':').length === 2 
                ? feedingTime + ':00' 
                : feedingTime;
            
            const feedingData = {
                kitten_name: kittenName,
                pre_weight: parseFloat(preWeight),
                post_weight: parseFloat(postWeight),
                notes: notes,
                date: feedingDate,
                time: timeWithSeconds,
            };
            
            this.showLoading();
            
            try {
                const response = await fetch(this.config.apiUrl + 'feeding/' + recordId, {
                    method: 'PUT',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(feedingData)
                });
                
                if (response.ok) {
                    this.showAlert('Feeding record updated successfully!', 'success');
                    this.resetSaveButton();
                    this.clearForm();
                    this.loadFeedingData();
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to update feeding record.', 'error');
                }
            } catch (error) {
                console.error('Update error:', error);
                this.showAlert('An error occurred while updating the record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Delete feeding record
         */
        deleteFeedingRecord: async function(recordId) {
            if (!confirm('Are you sure you want to delete this feeding record? This action cannot be undone.')) {
                return;
            }
            
            this.showLoading();
            
            try {
                const response = await fetch(this.config.apiUrl + 'feeding/' + recordId, {
                    method: 'DELETE',
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (response.ok) {
                    this.showAlert('Feeding record deleted successfully!', 'success');
                    this.loadFeedingData();
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to delete feeding record.', 'error');
                }
            } catch (error) {
                console.error('Delete error:', error);
                this.showAlert('An error occurred while deleting the record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Reset save button to normal state
         */
        resetSaveButton: function() {
            const saveButton = document.querySelector('button[onclick*="saveFeedingRecord"], button[onclick*="updateFeedingRecord"]');
            if (saveButton) {
                saveButton.textContent = '💾 Save Record';
                saveButton.onclick = () => this.saveFeedingRecord();
                saveButton.style.background = 'linear-gradient(135deg, #3b82f6, #1d4ed8)';
            }
        },

        /**
         * Clear feeding form
         */
        clearForm: function() {
            const kittenNameField = document.getElementById('neonate-kitten-name');
            const preWeightField = document.getElementById('neonate-pre-weight');
            const postWeightField = document.getElementById('neonate-post-weight');
            const notesField = document.getElementById('neonate-notes');
            
            if (kittenNameField) kittenNameField.value = '';
            if (preWeightField) preWeightField.value = '';
            if (postWeightField) postWeightField.value = '';
            if (notesField) notesField.value = '';
            
            // Reset date/time to current values
            this.initializeDateTimeInputs();
        },

        /**
         * Show care guide
         */
        showCareGuide: function() {
            const guidelines = `🍼 NEONATE KITTEN CARE GUIDELINES

FEEDING:
• Use kitten milk replacer, never cow's milk
• Feed slowly to prevent aspiration
• Burp kitten after feeding (like a baby)
• Weight gain should be steady (10-15g per day)

STIMULATION:
• Use warm, damp cotton ball or cloth
• Gently stimulate genitals before/after feeding
• Essential for elimination in kittens under 3 weeks

TEMPERATURE:
• Keep kittens warm (88-92°F for newborns)
• Use heating pad on low, blankets, or body heat
• Monitor for overheating or chilling

MONITORING:
• Weigh daily at same time
• Watch for lethargy, dehydration, or poor weight gain
• Contact veterinarian if concerns arise

HYGIENE:
• Keep feeding area clean
• Wash hands before handling kittens
• Clean kitten's face after feeding

EMERGENCY SIGNS:
• No weight gain for 2+ days
• Lethargy or weakness
• Diarrhea or vomiting
• Difficulty breathing
• Cold to touch

Contact your veterinarian immediately if any emergency signs appear!`;
            
            alert(guidelines);
        },

        /**
         * Populate kitten dropdown from baby kittens
         */
        populateKittenDropdown: function() {
            const dropdown = document.getElementById('neonate-kitten-name');
            if (!dropdown) {
                console.log('Kitten dropdown element not found');
                return;
            }
            
            console.log('Populating kitten dropdown with:', this.babyKittens);
            
            // Clear existing options except first
            dropdown.innerHTML = '<option value="">Select a kitten...</option>';
            
            if (this.babyKittens.length === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = 'No baby kittens found in intake records';
                option.disabled = true;
                dropdown.appendChild(option);
                console.log('No baby kittens found');
                return;
            }
            
            this.babyKittens.forEach(kitten => {
                const option = document.createElement('option');
                option.value = kitten.name;
                option.textContent = kitten.display_name;
                dropdown.appendChild(option);
                console.log('Added kitten to dropdown:', kitten.name, '- Age:', kitten.age);
            });
        },

        /**
         * Update kitten checkboxes for chart filtering
         */
        updateKittenCheckboxes: function() {
            const container = document.getElementById('neonate-kitten-checkboxes');
            if (!container) return;
            
            container.innerHTML = '';
            
            // Get unique kitten names from feeding records and count their records
            const kittenData = {};
            this.feedingRecords.forEach(record => {
                const name = record.kitten_name;
                if (!kittenData[name]) {
                    kittenData[name] = 0;
                }
                kittenData[name]++;
            });
            
            const kittenNames = Object.keys(kittenData);
            
            if (kittenNames.length === 0) {
                container.innerHTML = '<p style="color: #6b7280; font-style: italic;">No feeding records available yet.</p>';
                return;
            }
            
            // Load saved selections from localStorage
            const savedSelections = this.loadChartSelections();
            
            // Find first kitten with 2+ records for auto-selection
            const firstKittenWithData = kittenNames.find(name => kittenData[name] >= 2);
            
            kittenNames.forEach((name, index) => {
                const colors = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899'];
                const color = colors[index % colors.length];
                
                // Calculate average daily weight gain for this kitten
                const kittenRecords = this.feedingRecords.filter(record => record.kitten_name === name);
                const dailyChanges = this.calculateKittenDailyChanges(kittenRecords);
                const avgDailyChange = dailyChanges.length > 0 ? 
                    dailyChanges.reduce((sum, change) => sum + change, 0) / dailyChanges.length : 0;
                
                const checkboxDiv = document.createElement('div');
                checkboxDiv.style.cssText = `
                    display: flex;
                    flex-direction: column;
                    padding: 0.75rem;
                    background: white;
                    border: 2px solid #e5e7eb;
                    border-radius: 0.5rem;
                    cursor: pointer;
                    transition: all 0.2s;
                `;
                
                // Top row: checkbox, name, color dot
                const topRow = document.createElement('div');
                topRow.style.cssText = `
                    display: flex;
                    align-items: center;
                    width: 100%;
                `;
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.id = 'kitten-' + index;
                checkbox.value = name;
                checkbox.style.cssText = `
                    width: 1rem;
                    height: 1rem;
                    margin-right: 0.5rem;
                    accent-color: ${color};
                `;
                
                // Determine if checkbox should be checked
                // Auto-check all kittens by default, but respect saved preferences
                let shouldCheck = true;
                if (savedSelections.hasOwnProperty(name)) {
                    // Use saved preference if available
                    shouldCheck = savedSelections[name];
                }
                
                checkbox.checked = shouldCheck;
                
                checkbox.addEventListener('change', (e) => {
                    this.toggleKittenChart(name, e.target.checked);
                    this.saveChartSelections(name, e.target.checked);
                });
                
                const label = document.createElement('label');
                label.htmlFor = 'kitten-' + index;
                label.textContent = name;
                label.style.cssText = `
                    font-weight: 600;
                    color: #374151;
                    cursor: pointer;
                    flex: 1;
                `;
                
                const colorDot = document.createElement('div');
                colorDot.style.cssText = `
                    width: 0.75rem;
                    height: 0.75rem;
                    background: ${color};
                    border-radius: 50%;
                    margin-left: 0.5rem;
                `;
                
                topRow.appendChild(checkbox);
                topRow.appendChild(label);
                topRow.appendChild(colorDot);
                
                // Bottom row: average daily weight change
                const bottomRow = document.createElement('div');
                bottomRow.style.cssText = `
                    font-size: 0.75rem;
                    color: #6b7280;
                    margin-top: 0.25rem;
                    padding-left: 1.5rem;
                `;
                
                if (dailyChanges.length > 0) {
                    const changeColor = avgDailyChange >= 0 ? '#10b981' : '#ef4444';
                    const changeText = avgDailyChange >= 0 ? 
                        `Avg daily gain: +${avgDailyChange.toFixed(1)}g` : 
                        `Avg daily loss: ${avgDailyChange.toFixed(1)}g`;
                    bottomRow.innerHTML = `<span style="color: ${changeColor}; font-weight: 500;">${changeText}</span>`;
                } else {
                    bottomRow.textContent = 'Need 2+ days of data';
                }
                
                checkboxDiv.appendChild(topRow);
                checkboxDiv.appendChild(bottomRow);
                
                // Hover effects
                checkboxDiv.addEventListener('mouseenter', () => {
                    checkboxDiv.style.borderColor = color;
                    checkboxDiv.style.transform = 'translateY(-1px)';
                });
                checkboxDiv.addEventListener('mouseleave', () => {
                    checkboxDiv.style.borderColor = '#e5e7eb';
                    checkboxDiv.style.transform = 'translateY(0)';
                });
                
                container.appendChild(checkboxDiv);
                
                // Apply initial chart visibility with small delay to ensure chart exists
                if (shouldCheck) {
                    setTimeout(() => {
                        this.toggleKittenChart(name, true);
                    }, 50);
                }
            });
        },

        /**
         * Save chart selections to localStorage
         */
        saveChartSelections: function(kittenName, isSelected) {
            const selections = this.loadChartSelections();
            selections[kittenName] = isSelected;
            localStorage.setItem('claws_neonate_chart_selections', JSON.stringify(selections));
        },

        /**
         * Load chart selections from localStorage
         */
        loadChartSelections: function() {
            try {
                const saved = localStorage.getItem('claws_neonate_chart_selections');
                return saved ? JSON.parse(saved) : {};
            } catch (error) {
                console.log('Error loading chart selections:', error);
                return {};
            }
        },

        /**
         * Show alert notification
         */
        showAlert: function(message, type = 'info') {
            const alertDiv = document.createElement('div');
            const colors = {
                'success': CLAWS_CONSTANTS.COLORS.SUCCESS,
                'error': CLAWS_CONSTANTS.COLORS.ERROR,
                'warning': CLAWS_CONSTANTS.COLORS.WARNING,
                'info': CLAWS_CONSTANTS.COLORS.INFO
            };
            
            alertDiv.className = 'claws-alert claws-alert-' + type;
            alertDiv.style.cssText = `
                position: fixed;
                top: 1rem;
                right: 1rem;
                padding: 1rem;
                border-radius: 0.5rem;
                color: white;
                z-index: 9999;
                background: ${colors[type]};
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
                max-width: 300px;
                font-size: 0.875rem;
                animation: slideInRight 0.3s ease-out;
            `;
            alertDiv.textContent = message;
            
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 4000);
        },

        /**
         * Show loading indicator
         */
        showLoading: function() {
            const loading = document.getElementById('claws-loading');
            if (loading) {
                loading.style.display = 'block';
            }
        },

        /**
         * Hide loading indicator
         */
        hideLoading: function() {
            const loading = document.getElementById('claws-loading');
            if (loading) {
                loading.style.display = 'none';
            }
        },

        /**
         * Create intake form modal
         */
        createIntakeFormModal: function() {
            const modal = document.createElement('div');
            modal.id = 'claws-intake-form-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 28rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">New Cat Intake</h2>
                            <button onclick="CLAWSApp.hideIntakeForm()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <!-- Form Content -->
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <!-- Date -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Date</label>
                                <input type="date" id="claws-intake-date" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" value="${new Date().toISOString().split('T')[0]}" />
                            </div>

                            <!-- Contact Information -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Contact Information</h3>
                                <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Name *</label>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                            <input type="text" id="claws-intake-contact-first-name" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="First Name" />
                                            <input type="text" id="claws-intake-contact-last-name" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="Last Name" />
                                        </div>
                                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                            <input type="checkbox" id="claws-intake-anonymous" style="margin: 0;" />
                                            Anonymous/Drop off
                                        </label>
                                    </div>
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Address *</label>
                                        <div style="display: grid; grid-template-columns: 1fr; gap: 0.75rem;">
                                            <div>
                                                <input type="text" id="claws-intake-street" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="Street Address" />
                                            </div>
                                            <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 0.5rem;">
                                                <input type="text" id="claws-intake-city" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="City" />
                                                <input type="text" id="claws-intake-state" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="State" />
                                                <input type="text" id="claws-intake-zip" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="Zip Code" />
                                            </div>
                                        </div>
                                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                            <input type="checkbox" id="claws-intake-dropoff" style="margin: 0;" />
                                            Drop Off
                                        </label>
                                    </div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Phone Number *</label>
                                            <input type="tel" id="claws-intake-phone" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="(555) 123-4567" />
                                            <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                                <input type="checkbox" id="claws-intake-phone-unknown" style="margin: 0;" />
                                                Unknown
                                            </label>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Email Address *</label>
                                            <input type="email" id="claws-intake-email" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="email@example.com" />
                                            <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                                <input type="checkbox" id="claws-intake-email-unknown" style="margin: 0;" />
                                                Unknown
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Cat Information -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Cat Information</h3>
                                <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Name *</label>
                                        <input type="text" id="claws-intake-cat-name" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="What do we call this cat?" />
                                    </div>
                                    
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Age *</label>
                                            <select id="claws-intake-age" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                                <option value="">Select age category</option>
                                                <option value="Newborn (0-8 weeks)">Newborn (0-8 weeks)</option>
                                                <option value="Kitten (2-5 months)">Kitten (2-5 months)</option>
                                                <option value="Cat (6 months to 8 years)">Cat (6 months to 8 years)</option>
                                                <option value="Senior (Older than 8 years)">Senior (Older than 8 years)</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Gender *</label>
                                            <select id="claws-intake-gender" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                                <option value="">Select gender</option>
                                                <option value="Male">Male</option>
                                                <option value="Female">Female</option>
                                                <option value="Unknown">Unknown</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Coat *</label>
                                            <select id="claws-intake-coat" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                                <option value="">Select coat type</option>
                                                <option value="Domestic Short Hair">Domestic Short Hair</option>
                                                <option value="Domestic Medium Hair">Domestic Medium Hair</option>
                                                <option value="Domestic Long Hair">Domestic Long Hair</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Color *</label>
                                            <input type="text" id="claws-intake-color" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="e.g., Orange tabby, Black and white" />
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Type *</label>
                                        <select id="claws-intake-type" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" onchange="CLAWSApp.handleIntakeTypeChange()">
                                            <option value="">Select cat type</option>
                                            <option value="Stray">Stray</option>
                                            <option value="Feral">Feral</option>
                                            <option value="Friendly/Socialized">Friendly/Socialized</option>
                                            <option value="Semi-feral">Semi-feral</option>
                                            ${this.hasColonyAccess() ? '<option value="Colony Cat">Colony Cat</option>' : ''}
                                        </select>
                                    </div>
                                    
                                    <!-- Colony Assignment (shows when Colony Cat is selected) -->
                                    <div id="claws-colony-assignment-container" style="display: none;">
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Colony Assignment</label>
                                        <select id="claws-intake-colony" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                            <option value="">Select colony...</option>
                                            ${this.getAccessibleColonies().map(colony => 
                                                `<option value="${colony.id}">${colony.name}</option>`
                                            ).join('')}
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Photo Upload -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Cat Photo (Optional)</h3>
                                <div>
                                    <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Upload Photo</label>
                                    <input type="file" id="claws-intake-photo" accept="image/jpeg,image/png,image/webp" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" onchange="CLAWSApp.handleIntakePhotoUpload(this)" />
                                    <div id="claws-intake-photo-preview" style="margin-top: 0.5rem; display: none;">
                                        <img id="claws-intake-photo-img" style="max-width: 100%; height: 100px; object-fit: cover; border-radius: 0.375rem; border: 1px solid #e5e7eb;" />
                                    </div>
                                    <button type="button" id="claws-ai-analyze-btn" onclick="CLAWSApp.analyzePhotoWithAI()" style="margin-top: 0.5rem; padding: 0.5rem 1rem; background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; border: none; border-radius: 0.375rem; font-size: 0.75rem; cursor: pointer; display: none;">
                                        🤖 AI Analyze Coat & Color
                                    </button>
                                    <div id="claws-ai-results" style="margin-top: 0.5rem; padding: 0.5rem; background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 0.375rem; font-size: 0.75rem; display: none;"></div>
                                    <p style="font-size: 0.625rem; color: #6b7280; margin: 0.25rem 0 0;">JPG, PNG, or WebP. Max 5MB. Upload a photo to enable AI coat analysis.</p>
                                </div>
                            </div>

                            <!-- Notes -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Notes</label>
                                <textarea id="claws-intake-notes" rows="3" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; resize: vertical; box-sizing: border-box;" placeholder="Any additional notes about this cat or situation..."></textarea>
                            </div>

                            <!-- Form Buttons -->
                            <div style="display: flex; flex-direction: column; gap: 0.75rem; padding-top: 0.5rem;">
                                <div style="display: flex; gap: 0.75rem;">
                                    <button onclick="CLAWSApp.hideIntakeForm()" style="flex: 1; padding: 0.75rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">Cancel</button>
                                    <button onclick="CLAWSApp.saveIntake()" style="flex: 1; padding: 0.75rem; background: ${this.getGradientStyle()}; color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">Save Intake</button>
                                </div>
                                <button onclick="CLAWSApp.immediateDischarge()" style="width: 100%; padding: 0.75rem; background: linear-gradient(135deg, #f59e0b, #d97706); color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer; font-size: 0.875rem;">
                                    ⚡ Immediate Discharge
                                    <br><span style="font-size: 0.75rem; opacity: 0.9;">Save intake & go to discharge form</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            modal.style.display = 'flex';
            this.resetIntakeForm();
            
            // Setup photo preview
            this.setupPhotoPreview('claws-intake-photo', 'claws-intake-photo-preview', 'claws-intake-photo-img');
        },

        /**
         * Create discharge form modal
         */
        createDischargeFormModal: function() {
            const modal = document.createElement('div');
            modal.id = 'claws-discharge-form-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 28rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">Record Outcome</h2>
                            <button onclick="CLAWSApp.hideDischargeForm()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <!-- Form Content -->
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <!-- Date -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Record Outcome Date</label>
                                <input type="date" id="claws-discharge-date" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" value="${new Date().toISOString().split('T')[0]}" />
                            </div>

                            <!-- Select Cat -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Select Cat</label>
                                <select id="claws-discharge-cat" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Choose a cat...</option>
                                    <!-- Will be populated dynamically -->
                                </select>
                            </div>

                            <!-- Outcome -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Outcome</label>
                                <select id="claws-discharge-outcome" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" onchange="CLAWSApp.handleDischargeOutcomeChange()">
                                    <option value="">Select outcome...</option>
                                    <option value="Adoption">Adoption</option>
                                    <option value="Transfer">Transfer</option>
                                    <option value="Died">Died</option>
                                    <option value="Euthanasia">Euthanasia</option>
                                    <option value="TNR (Trap, Neuter, Release)">TNR (Trap, Neuter, Release)</option>
                                    <option value="Returned to Owner">Returned to Owner</option>
                                    <option value="Escaped">Escaped</option>
                                    <option value="Foster to Adopt">Foster to Adopt</option>
                                </select>
                            </div>
                            
                            <!-- Colony Released To (shows when TNR is selected and user has colony access) -->
                            <div id="claws-colony-released-container" style="display: none;">
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Colony Released To</label>
                                <select id="claws-discharge-colony" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Select colony...</option>
                                    ${this.getAccessibleColonies().map(colony => 
                                        `<option value="${colony.id}">${colony.name}</option>`
                                    ).join('')}
                                </select>
                            </div>

                            <!-- Photo Upload -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Outcome Photo (Optional)</h3>
                                <div>
                                    <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Upload Photo</label>
                                    <input type="file" id="claws-discharge-photo" accept="image/jpeg,image/png,image/webp" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" />
                                    <div id="claws-discharge-photo-preview" style="margin-top: 0.5rem; display: none;">
                                        <img id="claws-discharge-photo-img" style="max-width: 100%; height: 100px; object-fit: cover; border-radius: 0.375rem; border: 1px solid #e5e7eb;" />
                                    </div>
                                    <p style="font-size: 0.625rem; color: #6b7280; margin: 0.25rem 0 0;">Perfect for adoption photos! JPG, PNG, or WebP. Max 5MB.</p>
                                </div>
                            </div>

                            <!-- Notes -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Notes (optional)</label>
                                <textarea id="claws-discharge-notes" rows="3" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; resize: vertical; box-sizing: border-box;" placeholder="Additional details about the outcome..."></textarea>
                            </div>

                            <!-- Form Buttons -->
                            <div style="display: flex; gap: 0.75rem; padding-top: 0.5rem;">
                                <button onclick="CLAWSApp.hideDischargeForm()" style="flex: 1; padding: 0.75rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">Cancel</button>
                                <button onclick="CLAWSApp.saveDischarge()" class="claws-child-header" style="flex: 1; padding: 0.75rem; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">Record Outcome</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            modal.style.display = 'flex';
            this.resetDischargeForm();
            this.populateCatDropdown();
            
            // Setup photo preview
            this.setupPhotoPreview('claws-discharge-photo', 'claws-discharge-photo-preview', 'claws-discharge-photo-img');
        },

        /**
         * Hide intake form
         */
        hideIntakeForm: function() {
            const modal = document.getElementById('claws-intake-form-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        },

        /**
         * Hide discharge form
         */
        hideDischargeForm: function() {
            const modal = document.getElementById('claws-discharge-form-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        },

        /**
         * Reset intake form
         */
        resetIntakeForm: function() {
            const fields = ['claws-intake-date', 'claws-intake-contact-first-name', 'claws-intake-contact-last-name', 'claws-intake-street', 'claws-intake-city', 'claws-intake-state', 'claws-intake-zip', 'claws-intake-phone', 'claws-intake-email', 'claws-intake-cat-name', 'claws-intake-age', 'claws-intake-gender', 'claws-intake-coat', 'claws-intake-color', 'claws-intake-type', 'claws-intake-notes'];
            
            fields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    if (fieldId === 'claws-intake-date') {
                        field.value = new Date().toISOString().split('T')[0];
                    } else {
                        field.value = '';
                    }
                }
            });
            
            // Reset checkboxes
            const checkboxes = ['claws-intake-anonymous', 'claws-intake-dropoff', 'claws-intake-phone-unknown', 'claws-intake-email-unknown'];
            checkboxes.forEach(checkboxId => {
                const checkbox = document.getElementById(checkboxId);
                if (checkbox) {
                    checkbox.checked = false;
                }
            });
        },

        /**
         * Reset discharge form
         */
        resetDischargeForm: function() {
            const fields = ['claws-discharge-date', 'claws-discharge-cat', 'claws-discharge-outcome', 'claws-discharge-notes'];
            
            fields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    if (fieldId === 'claws-discharge-date') {
                        field.value = new Date().toISOString().split('T')[0];
                    } else {
                        field.value = '';
                    }
                }
            });
        },

        /**
         * Populate cat dropdown for discharge
         */
        populateCatDropdown: function() {
            const select = document.getElementById('claws-discharge-cat');
            if (!select) return;
            
            // Clear existing options except first
            select.innerHTML = '<option value="">Choose a cat...</option>';
            
            // Create a lookup of already discharged cats (case-insensitive)
            const dischargedCats = new Set();
            this.dischargeRecords.forEach(record => {
                if (record.cat_name) {
                    dischargedCats.add(record.cat_name.toLowerCase().trim());
                }
            });
            
            // Add cats from intake records that haven't been discharged
            let availableCats = 0;
            this.intakeRecords.forEach(record => {
                if (record.cat_name) {
                    const catNameLower = record.cat_name.toLowerCase().trim();
                    // Only add if not already discharged
                    if (!dischargedCats.has(catNameLower)) {
                        const option = document.createElement('option');
                        option.value = record.cat_name;
                        option.textContent = record.cat_name;
                        select.appendChild(option);
                        availableCats++;
                    }
                }
            });
            
            if (availableCats === 0) {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = this.intakeRecords.length === 0 ? 'No cats available - add intakes first' : 'No cats available - all have been discharged';
                option.disabled = true;
                select.appendChild(option);
            }
        },

        /**
         * Save intake record
         */
        saveIntake: async function() {
            // Use the standardized data collection method
            const intakeData = this.collectIntakeFormData();
            if (!intakeData) {
                this.showAlert('Please fill in all required fields.', 'error');
                return;
            }

            this.showLoading();

            try {
                const response = await fetch(this.config.apiUrl + 'intake', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(intakeData)
                });

                if (response.ok) {
                    const result = await response.json();
                    
                    // Upload photo if one was selected
                    const photoResult = await this.uploadIntakePhoto(result.id);
                    if (photoResult === false) {
                        // Photo upload failed with validation error, but record was saved
                        this.showAlert('Intake record saved but photo upload failed.', 'warning');
                    } else {
                        // Success (with or without photo)
                        this.showAlert('Intake record saved successfully!', 'success');
                    }
                    
                    this.resetIntakeForm(); // Clear form for next entry
                    this.hideIntakeForm();
                    this.loadIntakeData(); // Refresh data
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to save intake record.', 'error');
                }
            } catch (error) {
                console.error('Intake save error:', error);
                this.showAlert('An error occurred while saving the intake record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Check if current user has access to colonies
         */
        hasColonyAccess: function() {
            return this.colonies && this.colonies.length > 0;
        },

        /**
         * Get colonies accessible to current user
         */
        getAccessibleColonies: function() {
            return this.colonies || [];
        },

        /**
         * Handle intake type change to show/hide colony assignment
         */
        handleIntakeTypeChange: function() {
            const typeSelect = document.getElementById('claws-intake-type');
            const colonyContainer = document.getElementById('claws-colony-assignment-container');
            
            if (typeSelect && colonyContainer) {
                if (typeSelect.value === 'Colony Cat') {
                    colonyContainer.style.display = 'block';
                } else {
                    colonyContainer.style.display = 'none';
                    // Clear the colony selection when hiding
                    const colonySelect = document.getElementById('claws-intake-colony');
                    if (colonySelect) {
                        colonySelect.value = '';
                    }
                }
            }
        },

        /**
         * Handle discharge outcome change to show/hide colony released to field
         */
        handleDischargeOutcomeChange: function() {
            const outcomeSelect = document.getElementById('claws-discharge-outcome');
            const colonyContainer = document.getElementById('claws-colony-released-container');
            
            if (outcomeSelect && colonyContainer) {
                // Show colony released field if TNR is selected AND user has colony access
                if (outcomeSelect.value === 'TNR (Trap, Neuter, Release)' && this.hasColonyAccess()) {
                    colonyContainer.style.display = 'block';
                } else {
                    colonyContainer.style.display = 'none';
                    // Clear the colony selection when hiding
                    const colonySelect = document.getElementById('claws-discharge-colony');
                    if (colonySelect) {
                        colonySelect.value = '';
                    }
                }
            }
        },

        /**
         * Handle immediate discharge workflow
         * Save intake, switch tab, and pre-populate discharge form
         */
        immediateDischarge: async function() {
            console.log('Starting immediate discharge workflow');
            
            try {
                // Collect intake data first
                const intakeData = this.collectIntakeFormData();
                if (!intakeData) {
                    // Check specific validation failure
                    const type = document.getElementById('claws-intake-type')?.value;
                    if (type === 'Colony Cat' && this.hasColonyAccess()) {
                        const colonyId = document.getElementById('claws-intake-colony')?.value;
                        if (!colonyId) {
                            this.showAlert('Please select a colony assignment for Colony Cat type.', 'error');
                            return;
                        }
                    }
                    this.showAlert('Please fill in all required intake fields first.', 'error');
                    return;
                }
                
                this.showLoading('Saving intake record...');
                
                // Save the intake record first
                const intakeResult = await this.saveIntakeData(intakeData);
                if (!intakeResult.success) {
                    throw new Error('Failed to save intake record');
                }
                
                console.log('Intake saved successfully, starting discharge workflow');
                
                // Hide the intake form
                this.hideIntakeForm();
                
                // Switch to discharge tab
                this.switchTab('discharge');
                
                // Wait a moment for tab switch to complete
                setTimeout(() => {
                    // Show discharge form with pre-populated data
                    this.showDischargeFormWithIntakeData(intakeData, intakeResult.id);
                }, 300);
                
                this.hideLoading();
                this.showAlert('Intake saved! Complete the discharge outcome below.', 'success');
                
            } catch (error) {
                console.error('Immediate discharge workflow error:', error);
                this.hideLoading();
                this.showAlert('Error during immediate discharge workflow: ' + error.message, 'error');
            }
        },

        /**
         * Collect intake form data for processing
         */
        collectIntakeFormData: function() {
            const intakeDate = document.getElementById('claws-intake-date')?.value;
            const contactFirstName = document.getElementById('claws-intake-contact-first-name')?.value;
            const contactLastName = document.getElementById('claws-intake-contact-last-name')?.value;
            const catName = document.getElementById('claws-intake-cat-name')?.value;
            const age = document.getElementById('claws-intake-age')?.value;
            const gender = document.getElementById('claws-intake-gender')?.value;
            const coat = document.getElementById('claws-intake-coat')?.value;
            const color = document.getElementById('claws-intake-color')?.value;
            const type = document.getElementById('claws-intake-type')?.value;
            
            // Get checkbox states
            const checkboxes = {
                anonymous: document.getElementById('claws-intake-anonymous')?.checked,
                dropoff: document.getElementById('claws-intake-dropoff')?.checked,
                phoneUnknown: document.getElementById('claws-intake-phone-unknown')?.checked,
                emailUnknown: document.getElementById('claws-intake-email-unknown')?.checked
            };
            
            // Validate required fields with checkbox overrides
            const street = document.getElementById('claws-intake-street')?.value;
            const city = document.getElementById('claws-intake-city')?.value;
            const state = document.getElementById('claws-intake-state')?.value;
            const zip = document.getElementById('claws-intake-zip')?.value;
            const phone = document.getElementById('claws-intake-phone')?.value;
            const email = document.getElementById('claws-intake-email')?.value;
            
            if (!intakeDate || !catName || !age || !gender || !coat || !color || !type) {
                return null;
            }
            
            // Combine name fields
            const contactName = (contactFirstName && contactLastName) ? 
                `${contactFirstName} ${contactLastName}` : 
                (contactFirstName || contactLastName || '');
                
            // Combine address fields
            let fullAddress = '';
            if (street) fullAddress = street;
            if (city) fullAddress += (fullAddress ? ', ' : '') + city;
            if (state) fullAddress += (fullAddress ? ', ' : '') + state;
            if (zip) fullAddress += (fullAddress ? ' ' : '') + zip;
            
            // Contact validation with checkbox overrides
            if (!contactName && !checkboxes.anonymous) return null;
            if (!fullAddress && !checkboxes.dropoff) return null;
            if (!phone && !checkboxes.phoneUnknown) return null;
            if (!email && !checkboxes.emailUnknown) return null;
            
            // Validate colony selection for Colony Cat type
            if (type === 'Colony Cat' && this.hasColonyAccess()) {
                const colonyId = document.getElementById('claws-intake-colony')?.value;
                if (!colonyId) {
                    return null; // Colony selection is required for Colony Cat type
                }
            }
            
            return {
                date: intakeDate,
                contact_name: contactName || '',
                contact_first_name: contactFirstName || '',
                contact_last_name: contactLastName || '',
                contact_address: fullAddress || '',
                contact_street: street || '',
                contact_city: city || '',
                contact_state: state || '',
                contact_zip: zip || '',
                contact_phone: phone || '',
                contact_email: email || '',
                cat_name: catName,
                age: age,
                gender: gender,
                coat: coat,
                color: color,
                type: type,
                colony_id: document.getElementById('claws-intake-colony')?.value || '',
                notes: document.getElementById('claws-intake-notes')?.value || '',
                // Checkbox states
                anonymous: checkboxes.anonymous,
                dropoff: checkboxes.dropoff,
                phone_unknown: checkboxes.phoneUnknown,
                email_unknown: checkboxes.emailUnknown
            };
        },

        /**
         * Save intake data via API
         */
        saveIntakeData: async function(intakeData) {
            const response = await fetch(this.config.apiUrl + 'intake', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': wpApiSettings.nonce
                },
                body: JSON.stringify(intakeData)
            });
            
            if (!response.ok) {
                throw new Error('Failed to save intake record');
            }
            
            return await response.json();
        },

        /**
         * Handle intake photo upload and show AI analysis option
         */
        handleIntakePhotoUpload: function(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                
                // Show photo preview
                const preview = document.getElementById('claws-intake-photo-preview');
                const img = document.getElementById('claws-intake-photo-img');
                const analyzeBtn = document.getElementById('claws-ai-analyze-btn');
                
                if (preview && img && analyzeBtn) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        img.src = e.target.result;
                        preview.style.display = 'block';
                        analyzeBtn.style.display = 'inline-block';
                    };
                    reader.readAsDataURL(file);
                }
            }
        },

        /**
         * Analyze uploaded photo with AI to suggest coat type and color
         */
        analyzePhotoWithAI: function() {
            const analyzeBtn = document.getElementById('claws-ai-analyze-btn');
            const resultsDiv = document.getElementById('claws-ai-results');
            const photoInput = document.getElementById('claws-intake-photo');
            
            if (!analyzeBtn || !resultsDiv || !photoInput || !photoInput.files[0]) {
                this.showAlert('Please upload a photo first.', 'error');
                return;
            }
            
            // Show loading state
            analyzeBtn.innerHTML = '🔄 Analyzing...';
            analyzeBtn.disabled = true;
            resultsDiv.style.display = 'none';
            
            // Prepare form data
            const formData = new FormData();
            formData.append('action', 'claws_analyze_photo');
            formData.append('image', photoInput.files[0]);
            formData.append('nonce', this.config.nonce);
            
            // Call real AI service
            fetch(this.config.ajaxUrl, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    const result = data.data;
                    
                    // Display results
                    let confidenceColor = '#28a745'; // green
                    if (result.confidence < 0.7) confidenceColor = '#ffc107'; // yellow
                    if (result.confidence < 0.5) confidenceColor = '#dc3545'; // red
                    
                    resultsDiv.innerHTML = `
                        <strong>🤖 AI Analysis Results:</strong><br>
                        <strong>Suggested Coat:</strong> ${result.coat}<br>
                        <strong>Suggested Color:</strong> ${result.color}<br>
                        <small style="color: ${confidenceColor};">Confidence: ${Math.round(result.confidence * 100)}% (${result.source})</small><br>
                        <button onclick="CLAWSApp.applyAIResults('${result.coat}', '${result.color}')" style="margin-top: 0.5rem; padding: 0.25rem 0.75rem; background: #0ea5e9; color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">
                            Apply Suggestions
                        </button>
                        ${result.message ? `<br><small style="color: #6b7280;">${result.message}</small>` : ''}
                    `;
                    resultsDiv.style.display = 'block';
                    
                } else {
                    // Handle error or fallback
                    const errorMsg = data.data || 'AI analysis failed';
                    
                    if (errorMsg.includes('not enabled')) {
                        resultsDiv.innerHTML = `
                            <strong>ℹ️ AI Analysis Not Available</strong><br>
                            <small>AI photo analysis is not configured. Using mock suggestions:</small><br>
                            ${this.generateFallbackResults()}
                        `;
                    } else {
                        resultsDiv.innerHTML = `
                            <strong>⚠️ AI Analysis Error</strong><br>
                            <small>${errorMsg}</small><br>
                            ${this.generateFallbackResults()}
                        `;
                    }
                    resultsDiv.style.display = 'block';
                }
                
                // Reset button
                analyzeBtn.innerHTML = '🤖 AI Analyze Coat & Color';
                analyzeBtn.disabled = false;
                
            })
            .catch(error => {
                console.error('AI analysis error:', error);
                
                // Show fallback results
                resultsDiv.innerHTML = `
                    <strong>🔧 Using Fallback Analysis</strong><br>
                    <small>AI service unavailable. Here are some suggestions:</small><br>
                    ${this.generateFallbackResults()}
                `;
                resultsDiv.style.display = 'block';
                
                // Reset button
                analyzeBtn.innerHTML = '🤖 AI Analyze Coat & Color';
                analyzeBtn.disabled = false;
            });
        },

        /**
         * Generate fallback results when AI is unavailable
         */
        generateFallbackResults: function() {
            const mockResults = this.generateMockAIAnalysis();
            
            return `
                <strong>Suggested Coat:</strong> ${mockResults.coat}<br>
                <strong>Suggested Color:</strong> ${mockResults.color}<br>
                <small style="color: #6b7280;">Random suggestion - please verify</small><br>
                <button onclick="CLAWSApp.applyAIResults('${mockResults.coat}', '${mockResults.color}')" style="margin-top: 0.5rem; padding: 0.25rem 0.75rem; background: #6b7280; color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">
                    Apply Suggestions
                </button>
            `;
        },

        /**
         * Generate mock AI analysis results (fallback function)
         */
        generateMockAIAnalysis: function() {
            const coatTypes = ['Domestic Short Hair', 'Domestic Medium Hair', 'Domestic Long Hair'];
            const colors = [
                'Orange tabby', 'Black', 'Black and white', 'Gray tabby', 'Calico', 
                'Tortoiseshell', 'White', 'Brown tabby', 'Tuxedo', 'Gray and white',
                'Orange and white', 'Siamese pointed', 'Russian blue', 'Cream'
            ];
            
            return {
                coat: coatTypes[Math.floor(Math.random() * coatTypes.length)],
                color: colors[Math.floor(Math.random() * colors.length)]
            };
        },

        /**
         * Apply AI-suggested coat and color to form fields
         */
        applyAIResults: function(coat, color) {
            const coatField = document.getElementById('claws-intake-coat');
            const colorField = document.getElementById('claws-intake-color');
            
            if (coatField && colorField) {
                coatField.value = coat;
                colorField.value = color;
                
                this.showAlert('AI suggestions applied! You can modify them if needed.', 'success');
            }
        },

        /**
         * Show discharge form with pre-populated intake data
         */
        showDischargeFormWithIntakeData: function(intakeData, intakeId) {
            // Show the standard discharge form
            this.showDischargeForm();
            
            // Wait for form to be created then populate it
            setTimeout(() => {
                this.populateDischargeFromIntake(intakeData, intakeId);
            }, 100);
        },

        /**
         * Populate discharge form with intake data
         */
        populateDischargeFromIntake: function(intakeData, intakeId) {
            console.log('Populating discharge form with intake data:', intakeData);
            
            // Auto-populate date (same as intake date)
            const dischargeDate = document.getElementById('claws-discharge-date');
            if (dischargeDate) {
                dischargeDate.value = intakeData.date;
            }
            
            // Auto-populate cat name by adding it to the dropdown and selecting it
            const catSelect = document.getElementById('claws-discharge-cat');
            if (catSelect && intakeData.cat_name) {
                // Add the new cat to the dropdown
                const option = document.createElement('option');
                option.value = intakeData.cat_name;
                option.textContent = `${intakeData.cat_name} (just entered)`;
                option.selected = true;
                catSelect.appendChild(option);
                
                // Store the intake ID for reference
                catSelect.dataset.intakeId = intakeId;
            }
            
            // Auto-populate notes with intake information
            const dischargeNotes = document.getElementById('claws-discharge-notes');
            if (dischargeNotes) {
                let notes = `Intake processed: ${intakeData.date}\\n`;
                notes += `Cat: ${intakeData.cat_name} (${intakeData.age}, ${intakeData.gender})\\n`;
                notes += `Type: ${intakeData.type}\\n`;
                if (intakeData.contact_name) {
                    notes += `Contact: ${intakeData.contact_name}\\n`;
                }
                if (intakeData.notes) {
                    notes += `Intake Notes: ${intakeData.notes}\\n`;
                }
                notes += `\\n--- Immediate Discharge ---\\n`;
                dischargeNotes.value = notes;
            }
            
            // Focus on the outcome field for user to complete
            const outcomeField = document.getElementById('claws-discharge-outcome');
            if (outcomeField) {
                outcomeField.focus();
                // Add visual indicator
                outcomeField.style.borderColor = '#f59e0b';
                outcomeField.style.borderWidth = '2px';
                
                // Add a reminder note above the outcome field
                const reminderDiv = document.createElement('div');
                reminderDiv.innerHTML = '<p style="color: #f59e0b; font-size: 0.875rem; margin: 0 0 0.5rem; font-weight: 500;">⚡ Select the outcome for this immediate discharge:</p>';
                outcomeField.parentNode.insertBefore(reminderDiv, outcomeField);
            }
        },

        /**
         * Save discharge record
         */
        saveDischarge: async function() {
            const dischargeData = {
                date: document.getElementById('claws-discharge-date').value,
                cat_name: document.getElementById('claws-discharge-cat').value,
                outcome: document.getElementById('claws-discharge-outcome').value,
                colony_id: document.getElementById('claws-discharge-colony')?.value || '',
                notes: document.getElementById('claws-discharge-notes').value
            };

            // Validation
            if (!dischargeData.date) {
                this.showAlert('Please select a date.', 'error');
                return;
            }
            
            if (!dischargeData.cat_name) {
                this.showAlert('Please select a cat.', 'error');
                return;
            }
            
            if (!dischargeData.outcome) {
                this.showAlert('Please select an outcome.', 'error');
                return;
            }
            
            // Validate colony selection for TNR
            if (dischargeData.outcome === 'TNR (Trap, Neuter, Release)' && this.hasColonyAccess() && !dischargeData.colony_id) {
                this.showAlert('Please select a colony for TNR release.', 'error');
                return;
            }

            this.showLoading();

            try {
                const response = await fetch(this.config.apiUrl + 'discharge', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(dischargeData)
                });

                if (response.ok) {
                    const result = await response.json();
                    
                    // Upload photo if one was selected
                    const photoResult = await this.uploadDischargePhoto(result.id);
                    if (photoResult === false) {
                        // Photo upload failed with validation error, but record was saved
                        this.showAlert('Discharge record saved but photo upload failed.', 'warning');
                    } else {
                        // Success (with or without photo)
                        this.showAlert('Discharge record saved successfully!', 'success');
                    }
                    
                    this.hideDischargeForm();
                    this.loadDischargeData(); // Refresh data
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to save discharge record.', 'error');
                }
            } catch (error) {
                console.error('Discharge save error:', error);
                this.showAlert('An error occurred while saving the discharge record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Upload colony photo
         */
        uploadColonyPhoto: async function(colonyId) {
            const fileInput = document.getElementById('claws-colony-photo');
            if (!fileInput || !fileInput.files[0]) {
                this.showAlert('Please select a photo to upload.', 'error');
                return;
            }

            const file = fileInput.files[0];
            
            // Validate file size
            if (file.size > 5 * 1024 * 1024) {
                this.showAlert('File size must be under 5MB.', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('photo', file);

            this.showLoading();

            try {
                const response = await fetch(`${this.config.apiUrl}colony/${colonyId}/photo`, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: formData
                });

                if (response.ok) {
                    const result = await response.json();
                    this.showAlert('Photo uploaded successfully!', 'success');
                    
                    // Reset file input
                    fileInput.value = '';
                    const preview = document.getElementById('claws-colony-photo-preview');
                    if (preview) preview.style.display = 'none';
                    
                    // Reload colony data to show new photo
                    this.loadColonies();
                    
                    // Close and reopen modal to refresh photos
                    const modal = document.getElementById('claws-colony-details-modal');
                    if (modal) {
                        modal.remove();
                        // Reopen modal with updated data after a brief delay
                        setTimeout(() => {
                            const updatedColony = this.colonies.find(c => c.id === colonyId);
                            if (updatedColony) {
                                this.viewColonyDetails(colonyId);
                            }
                        }, 500);
                    }
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to upload photo.', 'error');
                }
            } catch (error) {
                console.error('Photo upload error:', error);
                this.showAlert('An error occurred while uploading the photo.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Upload intake photo and save with record
         */
        uploadIntakePhoto: async function(intakeId) {
            const fileInput = document.getElementById('claws-intake-photo');
            if (!fileInput || !fileInput.files[0]) {
                return null; // No file selected, continue without photo
            }

            const file = fileInput.files[0];
            
            // Validate file size
            if (file.size > 5 * 1024 * 1024) {
                this.showAlert('Photo file size must be under 5MB.', 'error');
                return false;
            }

            const formData = new FormData();
            formData.append('photo', file);

            try {
                const response = await fetch(`${this.config.apiUrl}intake/${intakeId}/photo`, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: formData
                });

                if (response.ok) {
                    return await response.json();
                } else {
                    console.error('Photo upload failed:', await response.text());
                    return null;
                }
            } catch (error) {
                console.error('Photo upload error:', error);
                return null;
            }
        },

        /**
         * Upload discharge photo and save with record
         */
        uploadDischargePhoto: async function(dischargeId) {
            const fileInput = document.getElementById('claws-discharge-photo');
            if (!fileInput || !fileInput.files[0]) {
                return null; // No file selected, continue without photo
            }

            const file = fileInput.files[0];
            
            // Validate file size
            if (file.size > 5 * 1024 * 1024) {
                this.showAlert('Photo file size must be under 5MB.', 'error');
                return false;
            }

            const formData = new FormData();
            formData.append('photo', file);

            try {
                const response = await fetch(`${this.config.apiUrl}discharge/${dischargeId}/photo`, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: formData
                });

                if (response.ok) {
                    return await response.json();
                } else {
                    console.error('Photo upload failed:', await response.text());
                    return null;
                }
            } catch (error) {
                console.error('Photo upload error:', error);
                return null;
            }
        },

        /**
         * Setup photo preview functionality
         */
        setupPhotoPreview: function(inputId, previewId, imgId) {
            const input = document.getElementById(inputId);
            const preview = document.getElementById(previewId);
            const img = document.getElementById(imgId);
            
            if (!input || !preview || !img) return;
            
            input.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // Validate file type
                    if (!file.type.startsWith('image/')) {
                        alert('Please select an image file.');
                        input.value = '';
                        return;
                    }
                    
                    // Validate file size
                    if (file.size > 5 * 1024 * 1024) {
                        alert('File size must be under 5MB.');
                        input.value = '';
                        return;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        img.src = e.target.result;
                        preview.style.display = 'block';
                    };
                    reader.readAsDataURL(file);
                } else {
                    preview.style.display = 'none';
                }
            });
        },

        /**
         * Initialize Volunteers section
         */
        initVolunteers: function() {
            console.log('Initializing Volunteers section...');
            
            // Set default sub-tab to My Time
            this.currentVolunteerSubTab = 'mytime';
            
            // Initialize sub-tab content if needed
            this.switchVolunteerSubTab('mytime');
        },

        /**
         * Switch volunteer sub-tab
         */
        switchVolunteerSubTab: function(subTabName) {
            console.log(`Switching to volunteer sub-tab: ${subTabName}`);
            
            // Update sub-tab buttons - now using CSS classes for inheritance
            document.querySelectorAll('[id^="claws-volunteers-subtab-"]').forEach(btn => {
                btn.classList.remove('claws-volunteers-subtab-active', 'claws-child-header');
                btn.style.background = 'transparent';
                btn.style.color = '#6b7280';
            });
            
            const activeSubTab = document.getElementById(`claws-volunteers-subtab-${subTabName}`);
            if (activeSubTab) {
                activeSubTab.classList.add('claws-volunteers-subtab-active', 'claws-child-header');
                // Remove inline styles - let CSS classes handle colors
                activeSubTab.style.background = '';
                activeSubTab.style.color = '';
            }
            
            // Hide all sub-tab content sections
            document.querySelectorAll('.claws-volunteers-subtab-section').forEach(section => {
                section.style.display = 'none';
            });
            
            // Show selected sub-tab section
            const targetSection = document.getElementById(`claws-volunteers-${subTabName}`);
            if (targetSection) {
                targetSection.style.display = 'block';
            }
            
            // Load content for the selected sub-tab
            this.currentVolunteerSubTab = subTabName;
            this.loadVolunteerSubTabContent(subTabName);
        },

        /**
         * Load content for specific volunteer sub-tab
         */
        loadVolunteerSubTabContent: function(subTabName) {
            switch(subTabName) {
                case 'mytime':
                    this.loadVolunteerMyTime();
                    break;
                case 'events':
                    this.loadVolunteerEvents();
                    break;
                case 'teams':
                    this.loadVolunteerTeams();
                    break;
                case 'statsgoals':
                    this.loadVolunteerStatsGoals();
                    break;
                case 'comms':
                    this.loadVolunteerComms();
                    break;
                case 'admin':
                    this.loadVolunteerAdmin();
                    break;
            }
        },

        /**
         * Load My Time content
         */
        loadVolunteerMyTime: function() {
            console.log('Loading My Time...');
            this.loadNeedsAttentionItems();
            this.loadPendingItems();
            this.loadApprovedItems();
        },

        /**
         * Load Events content
         */
        loadVolunteerEvents: function() {
            console.log('Loading Events...');
            
            // Load available events
            this.loadAvailableEvents();
        },
        
        /**
         * Load available events from the server
         */
        loadAvailableEvents: function() {
            const container = document.getElementById('claws-events-list');
            if (!container) return;
            
            // Show loading state
            container.innerHTML = `
                <div style="text-align: center; padding: 3rem; color: #6b7280;">
                    <div style="font-size: 3rem; margin-bottom: 1rem;">🔄</div>
                    <p style="font-size: 1.125rem; margin: 0;">Loading available events...</p>
                </div>
            `;
            
            // TODO: Replace with actual API call when backend is implemented
            setTimeout(() => {
                // Placeholder for empty events list
                container.innerHTML = `
                    <div style="text-align: center; padding: 3rem; color: #6b7280;">
                        <div style="font-size: 3rem; margin-bottom: 1rem;">📝</div>
                        <h4 style="color: #1f2937; margin-bottom: 0.5rem;">No Opportunities Available</h4>
                        <p style="font-size: 1rem; margin: 0;">There are currently no volunteer events posted.</p>
                        <p style="font-size: 0.875rem; margin: 0.5rem 0 0; font-style: italic;">Check back later or create a new event!</p>
                    </div>
                `;
            }, 1000);
        },
        
        /**
         * Show add event form
         */
        showAddEventForm: function() {
            console.log('Showing add event form...');
            
            // Reset the form
            this.resetEventForm();
            
            // Auto-populate coordinator information
            this.populateCoordinatorInfo();
            
            // Show the modal
            const modal = document.getElementById('claws-add-event-modal');
            if (modal) {
                modal.style.display = 'flex';
                // Focus on the first field
                setTimeout(() => {
                    const firstField = document.getElementById('claws-event-name');
                    if (firstField) firstField.focus();
                }, 100);
            }
        },

        /**
         * Hide add event form
         */
        hideAddEventForm: function() {
            const modal = document.getElementById('claws-add-event-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        },

        /**
         * Reset event form
         */
        resetEventForm: function() {
            const fields = [
                'claws-event-name',
                'claws-event-category', 
                'claws-event-colony',
                'claws-event-date',
                'claws-event-start-time',
                'claws-event-end-time',
                'claws-event-min-commitment',
                'claws-event-coordinator',
                'claws-event-email',
                'claws-event-phone',
                'claws-event-notes',
                // Address fields
                'claws-event-street',
                'claws-event-city',
                'claws-event-state',
                'claws-event-zip'
            ];
            
            fields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.value = '';
                }
            });
            
            // Reset checkbox
            const tnrCheckbox = document.getElementById('claws-event-tnr-not-colony');
            if (tnrCheckbox) tnrCheckbox.checked = false;
            
            // Hide all location sections
            this.hideAllLocationSections();
        },

        /**
         * Populate coordinator information from user profile
         */
        populateCoordinatorInfo: function() {
            // Auto-populate with current user information from WordPress profile
            const coordinatorField = document.getElementById('claws-event-coordinator');
            const emailField = document.getElementById('claws-event-email');
            const phoneField = document.getElementById('claws-event-phone');
            
            if (coordinatorField && typeof clawsData !== 'undefined') {
                coordinatorField.value = clawsData.currentUser || '';
                emailField.value = clawsData.currentUserEmail || '';
                // Phone would need to be added to user meta in WordPress - for now leave empty
                phoneField.value = '';
            }
            
            // Set up category change handler for colony selection
            this.setupCategoryChangeHandler();
        },
        
        /**
         * Set up category change handler to show/hide colony selection
         */
        setupCategoryChangeHandler: function() {
            const categorySelect = document.getElementById('claws-event-category');
            const colonySection = document.getElementById('claws-event-colony-section');
            const tnrNotColonySection = document.getElementById('claws-event-tnr-not-colony-section');
            const addressSection = document.getElementById('claws-event-address-section');
            
            if (categorySelect) {
                // Populate with unified types
                this.populateEventCategoryDropdown();
                
                categorySelect.addEventListener('change', (e) => {
                    const selectedCategory = e.target.value;
                    
                    // Reset all sections first
                    this.hideAllLocationSections();
                    
                    // Show colony selection for Colony Care categories
                    if (this.requiresColonySelection(selectedCategory)) {
                        colonySection.style.display = 'block';
                        this.populateColonyDropdown();
                        this.setupColonyChangeHandler(); // Setup handler for colony selection
                    }
                    // Show colony selection AND TNR checkbox for TNR Party
                    else if (selectedCategory === 'tnr-party') {
                        colonySection.style.display = 'block';
                        tnrNotColonySection.style.display = 'block';
                        this.populateColonyDropdown();
                        this.setupTNRCheckboxHandler(); // Setup handler for TNR checkbox
                        this.setupColonyChangeHandler(); // Setup handler for colony selection
                    }
                });
            }
        },

        /**
         * Populate event category dropdown with unified types
         */
        populateEventCategoryDropdown: function() {
            const categorySelect = document.getElementById('claws-event-category');
            if (!categorySelect) return;
            
            const unifiedTypes = this.getUnifiedTaskEventTypes();
            
            let optionsHtml = '<option value="">Select category...</option>';
            
            // Group by category for better organization
            const categories = {
                'Colony Care': ['colony-feeding', 'colony-shelter', 'colony-safety', 'colony-monitoring', 'colony-setup'],
                'TNR Activities': ['tnr-party', 'tnr-transport', 'tnr-recovery'],
                'Education & Outreach': ['education', 'community-outreach', 'public-speaking'],
                'Administrative': ['administrative', 'fundraising', 'event-support', 'social-media'],
                'Animal Care': ['foster-care', 'animal-transport', 'medical-support'],
                'Facilities': ['maintenance', 'supply-management'],
                'Other': ['other']
            };
            
            Object.entries(categories).forEach(([categoryName, typeKeys]) => {
                optionsHtml += `<optgroup label="${categoryName}">`;
                typeKeys.forEach(key => {
                    if (unifiedTypes[key]) {
                        optionsHtml += `<option value="${key}">${unifiedTypes[key]}</option>`;
                    }
                });
                optionsHtml += '</optgroup>';
            });
            
            categorySelect.innerHTML = optionsHtml;
        },
        
        /**
         * Hide all location-related sections
         */
        hideAllLocationSections: function() {
            const sections = [
                'claws-event-colony-section',
                'claws-event-tnr-not-colony-section', 
                'claws-event-address-section'
            ];
            
            sections.forEach(sectionId => {
                const section = document.getElementById(sectionId);
                if (section) {
                    section.style.display = 'none';
                }
            });
            
            // Reset checkbox and clear address fields
            const tnrCheckbox = document.getElementById('claws-event-tnr-not-colony');
            if (tnrCheckbox) tnrCheckbox.checked = false;
            this.clearAddressFields();
        },
        
        /**
         * Setup TNR checkbox change handler
         */
        setupTNRCheckboxHandler: function() {
            const tnrCheckbox = document.getElementById('claws-event-tnr-not-colony');
            const colonySelect = document.getElementById('claws-event-colony');
            const addressSection = document.getElementById('claws-event-address-section');
            
            if (tnrCheckbox && addressSection) {
                // Remove any existing listeners
                tnrCheckbox.replaceWith(tnrCheckbox.cloneNode(true));
                const newCheckbox = document.getElementById('claws-event-tnr-not-colony');
                
                newCheckbox.addEventListener('change', (e) => {
                    if (e.target.checked) {
                        // Show address section and clear colony selection
                        addressSection.style.display = 'block';
                        if (colonySelect) colonySelect.value = '';
                        this.clearAddressFields();
                    } else {
                        // Hide address section
                        addressSection.style.display = 'none';
                        this.clearAddressFields();
                    }
                });
            }
        },
        
        /**
         * Setup colony selection change handler
         */
        setupColonyChangeHandler: function() {
            const colonySelect = document.getElementById('claws-event-colony');
            const addressSection = document.getElementById('claws-event-address-section');
            const tnrCheckbox = document.getElementById('claws-event-tnr-not-colony');
            
            if (colonySelect && addressSection) {
                // Remove any existing listeners
                colonySelect.replaceWith(colonySelect.cloneNode(true));
                const newSelect = document.getElementById('claws-event-colony');
                // Re-populate the new select
                this.populateColonyDropdown();
                
                newSelect.addEventListener('change', (e) => {
                    const selectedColonyId = e.target.value;
                    
                    // Only show address if TNR checkbox is NOT checked (for TNR Party) or it's a Colony Care category
                    const category = document.getElementById('claws-event-category').value;
                    const isTNRParty = category === 'tnr-party';
                    const isColonyCare = category.startsWith('colony-');
                    
                    if (selectedColonyId && ((isTNRParty && (!tnrCheckbox || !tnrCheckbox.checked)) || isColonyCare)) {
                        addressSection.style.display = 'block';
                        this.populateColonyAddress(selectedColonyId);
                    } else if (!selectedColonyId) {
                        // If no colony selected, hide address (unless TNR not at colony is checked)
                        if (!tnrCheckbox || !tnrCheckbox.checked) {
                            addressSection.style.display = 'none';
                            this.clearAddressFields();
                        }
                    }
                });
            }
        },
        
        /**
         * Populate address fields with colony data
         */
        populateColonyAddress: function(colonyId) {
            const colony = this.colonies.find(c => c.id == colonyId);
            if (colony) {
                // Populate address fields with colony information
                document.getElementById('claws-event-street').value = colony.street || '';
                document.getElementById('claws-event-city').value = colony.city || '';
                document.getElementById('claws-event-state').value = colony.state || '';
                document.getElementById('claws-event-zip').value = colony.zip || '';
            }
        },
        
        /**
         * Clear address fields
         */
        clearAddressFields: function() {
            const addressFields = [
                'claws-event-street',
                'claws-event-city', 
                'claws-event-state',
                'claws-event-zip'
            ];
            
            addressFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) field.value = '';
            });
        },
        
        /**
         * Populate colony dropdown with active colonies
         */
        populateColonyDropdown: function() {
            const colonySelect = document.getElementById('claws-event-colony');
            if (!colonySelect) return;
            
            // Clear existing options except the first
            colonySelect.innerHTML = '<option value="">Choose a colony...</option>';
            
            // Add colonies from the app's colony data
            if (this.colonies && this.colonies.length > 0) {
                this.colonies.forEach(colony => {
                    const option = document.createElement('option');
                    option.value = colony.id;
                    option.textContent = colony.name;
                    colonySelect.appendChild(option);
                });
            } else {
                // If no colonies are loaded, show a message
                const option = document.createElement('option');
                option.value = '';
                option.textContent = 'No colonies available - load colonies first';
                option.disabled = true;
                colonySelect.appendChild(option);
            }
        },

        /**
         * Save event
         */
        saveEvent: function() {
            console.log('Saving event...');
            
            // Get form values
            const eventName = document.getElementById('claws-event-name').value.trim();
            const category = document.getElementById('claws-event-category').value;
            const colony = document.getElementById('claws-event-colony').value;
            const date = document.getElementById('claws-event-date').value;
            
            // Basic validation
            if (!eventName) {
                this.showAlert('Please enter an event name.', 'error');
                return;
            }
            
            if (!category) {
                this.showAlert('Please select a category.', 'error');
                return;
            }
            
            // Check if colony is required (for colony-care categories and TNR Party)
            if ((category.startsWith('colony-') || category === 'tnr-party') && !colony) {
                // For TNR Party, check if "Not At Colony" is selected
                const tnrNotColony = document.getElementById('claws-event-tnr-not-colony');
                if (category === 'tnr-party' && tnrNotColony && tnrNotColony.checked) {
                    // Validate address fields for TNR Not At Colony
                    const street = document.getElementById('claws-event-street').value.trim();
                    const city = document.getElementById('claws-event-city').value.trim();
                    const state = document.getElementById('claws-event-state').value.trim();
                    const zip = document.getElementById('claws-event-zip').value.trim();
                    
                    if (!street || !city || !state || !zip) {
                        this.showAlert('Please fill in all address fields for TNR not at a colony.', 'error');
                        return;
                    }
                } else {
                    // Colony required for Colony Care or TNR Party at colony
                    const errorMsg = category === 'tnr-party' ? 
                        'Please select a colony or check "TNR, Not At A Colony".' :
                        'Please select a colony for this Colony Care event.';
                    this.showAlert(errorMsg, 'error');
                    return;
                }
            }
            
            if (!date) {
                this.showAlert('Please select a date.', 'error');
                return;
            }
            
            // Collect all form data
            const eventData = {
                name: eventName,
                category: category,
                colony: colony, // Include colony selection
                date: date,
                startTime: document.getElementById('claws-event-start-time').value,
                endTime: document.getElementById('claws-event-end-time').value,
                minCommitment: document.getElementById('claws-event-min-commitment').value,
                coordinator: document.getElementById('claws-event-coordinator').value.trim(),
                email: document.getElementById('claws-event-email').value.trim(),
                phone: document.getElementById('claws-event-phone').value.trim(),
                notes: document.getElementById('claws-event-notes').value.trim(),
                
                // TNR specific fields
                tnrNotAtColony: document.getElementById('claws-event-tnr-not-colony') ? 
                    document.getElementById('claws-event-tnr-not-colony').checked : false,
                
                // Address fields for TNR not at colony or colony addresses
                address: {
                    street: document.getElementById('claws-event-street') ? 
                        document.getElementById('claws-event-street').value.trim() : '',
                    city: document.getElementById('claws-event-city') ? 
                        document.getElementById('claws-event-city').value.trim() : '',
                    state: document.getElementById('claws-event-state') ? 
                        document.getElementById('claws-event-state').value.trim() : '',
                    zip: document.getElementById('claws-event-zip') ? 
                        document.getElementById('claws-event-zip').value.trim() : ''
                }
            };
            
            console.log('Event data:', eventData);
            
            // Show loading
            this.showLoading();
            
            // TODO: Replace with actual API call when backend is implemented
            setTimeout(() => {
                this.hideLoading();
                this.hideAddEventForm();
                this.showAlert('Event created successfully!', 'success');
                
                // Refresh the events list
                this.loadAvailableOpportunities();
            }, 1500);
        },

        /**
         * Show completed task form
         */
        showCompletedTaskForm: function() {
            console.log('Showing completed task form...');
            
            if (this.config.demoMode) {
                const proceed = confirm('You are in demo mode. Your changes will not be saved permanently. Continue?');
                if (!proceed) return;
            }
            
            // Populate coordinator dropdown
            this.loadCoordinators();
            
            // Populate task types dropdown
            this.loadTaskTypes();
            
            const modal = document.getElementById('claws-completed-task-modal');
            if (modal) {
                modal.style.display = 'flex';
            }
        },

        /**
         * Hide completed task form
         */
        hideCompletedTaskForm: function() {
            const modal = document.getElementById('claws-completed-task-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        },

        /**
         * Save completed task
         */
        saveCompletedTask: function() {
            console.log('Saving completed task...');
            
            // Collect form data
            const taskData = {
                date: document.getElementById('claws-task-date')?.value,
                type: document.getElementById('claws-task-type')?.value,
                colony: document.getElementById('claws-task-colony')?.value,
                description: document.getElementById('claws-task-description')?.value,
                hours: document.getElementById('claws-task-hours')?.value,
                coordinator: document.getElementById('claws-task-coordinator')?.value
            };
            
            // Validate required fields
            if (!taskData.date || !taskData.type || !taskData.description || !taskData.hours || !taskData.coordinator) {
                this.showAlert('Please fill in all required fields', 'error');
                return;
            }
            
            // Validate colony selection for colony care tasks
            if (this.requiresColonySelection(taskData.type) && !taskData.colony) {
                this.showAlert('Please select a colony for this type of task', 'error');
                return;
            }
            
            // Get unified type label for display
            const unifiedTypes = this.getUnifiedTaskEventTypes();
            const typeLabel = unifiedTypes[taskData.type] || taskData.type;
            
            console.log('Task data:', taskData);
            
            // Close the form
            this.hideCompletedTaskForm();
            
            // Show success message with task details
            let successMessage = `Task "${typeLabel}" submitted for approval!`;
            if (taskData.colony) {
                // Find colony name
                const colony = this.colonies?.find(c => c.id === taskData.colony);
                if (colony) {
                    successMessage = `Task "${typeLabel}" for ${colony.name} submitted for approval!`;
                }
            }
            
            this.showAlert(successMessage, 'success');
            
            // TODO: Send to backend for storage with "pending" status
            // This would normally make an API call to save the task data
        },

        /**
         * Approve task (coordinator function)
         */
        approveTask: function() {
            console.log('Approving task...');
            
            // Collect task data including coordinator notes
            const taskData = this.collectTaskFormData();
            taskData.status = 'approved';
            taskData.coordinatorNotes = document.getElementById('claws-coordinator-notes')?.value || '';
            taskData.approvedBy = this.config.currentUser;
            taskData.approvedDate = new Date().toISOString();
            
            // Validate required fields
            if (!this.validateTaskData(taskData)) {
                return;
            }
            
            console.log('Approving task data:', taskData);
            
            // Close the form
            this.hideCompletedTaskForm();
            
            // Show success message
            this.showAlert('Task approved successfully! It will appear in the volunteer\'s approved tasks.', 'success');
            
            // TODO: Send to backend with approved status
            // This would normally make an API call to save the task with approved status
        },

        /**
         * Mark task as needs attention (coordinator function)
         */
        needsAttentionTask: function() {
            console.log('Marking task as needs attention...');
            
            // Check if coordinator notes are provided
            const coordinatorNotes = document.getElementById('claws-coordinator-notes')?.value?.trim();
            if (!coordinatorNotes) {
                this.showAlert('Please provide notes explaining why this task needs attention.', 'error');
                return;
            }
            
            // Collect task data including coordinator notes
            const taskData = this.collectTaskFormData();
            taskData.status = 'needs_attention';
            taskData.coordinatorNotes = coordinatorNotes;
            taskData.reviewedBy = this.config.currentUser;
            taskData.reviewedDate = new Date().toISOString();
            
            // Validate required fields
            if (!this.validateTaskData(taskData)) {
                return;
            }
            
            console.log('Needs attention task data:', taskData);
            
            // Close the form
            this.hideCompletedTaskForm();
            
            // Show success message
            this.showAlert('Task marked as needs attention. The volunteer will see your feedback.', 'warning');
            
            // TODO: Send to backend with needs_attention status
            // This would normally make an API call to save the task with needs_attention status
        },

        /**
         * Collect task form data
         */
        collectTaskFormData: function() {
            return {
                date: document.getElementById('claws-task-date')?.value,
                type: document.getElementById('claws-task-type')?.value,
                colony: document.getElementById('claws-task-colony')?.value,
                description: document.getElementById('claws-task-description')?.value,
                startTime: document.getElementById('claws-task-start-time')?.value,
                endTime: document.getElementById('claws-task-end-time')?.value,
                totalHours: document.getElementById('claws-task-total-hours')?.value,
                coordinator: document.getElementById('claws-task-coordinator')?.value
            };
        },

        /**
         * Validate task data
         */
        validateTaskData: function(taskData) {
            // Validate required fields
            if (!taskData.date || !taskData.type || !taskData.description || !taskData.totalHours || !taskData.coordinator) {
                this.showAlert('Please fill in all required fields', 'error');
                return false;
            }
            
            // Validate colony selection for colony care tasks
            if (this.requiresColonySelection(taskData.type) && !taskData.colony) {
                this.showAlert('Please select a colony for this type of task', 'error');
                return false;
            }
            
            return true;
        },

        /**
         * Load Teams content
         */
        loadVolunteerTeams: function() {
            console.log('Loading Teams...');
            this.displayTeamsOverview();
        },

        /**
         * Display teams overview
         */
        displayTeamsOverview: function() {
            const teamsContainer = document.getElementById('claws-volunteers-teams');
            if (!teamsContainer) return;
            
            const unifiedTeams = this.getUnifiedTeams();
            
            // Check if there are any teams (events with volunteers)
            if (Object.keys(unifiedTeams).length === 0) {
                // Show empty state when no events exist
                teamsContainer.innerHTML = `
                    <div style="padding: 1.5rem; max-width: 800px; margin: 0 auto;">
                        <div style="text-align: center; margin-bottom: 2rem;">
                            <h3 style="color: #1f2937; margin-bottom: 0.5rem; font-size: 1.5rem; font-weight: 600;">Volunteer Teams</h3>
                            <p style="color: #6b7280; font-size: 1rem;">Teams are automatically formed when volunteers sign up for events. Each event with volunteers creates a temporary team for the duration of that event.</p>
                        </div>
                        
                        <div style="text-align: center; padding: 3rem; background: #f9fafb; border-radius: 1rem; border: 1px solid #e5e7eb;">
                            <div style="font-size: 4rem; margin-bottom: 1rem;">👥</div>
                            <h4 style="color: #1f2937; margin-bottom: 1rem; font-size: 1.25rem; font-weight: 600;">No Active Teams</h4>
                            <p style="color: #6b7280; margin-bottom: 1.5rem; max-width: 500px; margin-left: auto; margin-right: auto; line-height: 1.6;">
                                Teams are created automatically when volunteers sign up for events. Once events are posted and volunteers join them, you'll see active teams here.
                            </p>
                            <div style="background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 0.5rem; padding: 1rem; margin: 1.5rem auto; max-width: 600px;">
                                <p style="color: #1e40af; margin: 0; font-size: 0.875rem; font-weight: 500;">
                                    💡 How Teams Work: When an event is created and volunteers sign up, a team is automatically formed. 
                                    Team members can collaborate, share resources, and coordinate their efforts for that specific event. 
                                    When the event ends and all tasks are completed, the team is dissolved.
                                </p>
                            </div>
                        </div>
                    </div>
                `;
                return;
            }
            
            // Show unified teams (when events exist)
            teamsContainer.innerHTML = `
                <div style="padding: 1.5rem; max-width: 1000px; margin: 0 auto;">
                    <div style="text-align: center; margin-bottom: 2rem;">
                        <h3 style="color: #1f2937; margin-bottom: 0.5rem; font-size: 1.5rem; font-weight: 600;">Active Volunteer Teams</h3>
                        <p style="color: #6b7280; font-size: 1rem;">These teams are automatically formed based on current events with volunteers signed up.</p>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 1.5rem;">
                        ${Object.entries(unifiedTeams).map(([teamKey, team]) => `
                            <div style="border: 1px solid #e5e7eb; border-radius: 0.75rem; padding: 1.5rem; background: white; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);">
                                <div style="display: flex; align-items: center; margin-bottom: 1rem;">
                                    <span style="font-size: 2rem; margin-right: 0.75rem;">${team.icon}</span>
                                    <h4 style="margin: 0; color: #1f2937; font-size: 1.25rem; font-weight: 600;">${team.name}</h4>
                                </div>
                                <p style="color: #6b7280; margin-bottom: 1rem; line-height: 1.5; min-height: 3rem;">${team.description}</p>
                                
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <span style="background: #dbeafe; color: #1e40af; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.875rem; font-weight: 500;">${team.memberCount} members</span>
                                    <button onclick="CLAWSApp.viewTeamDetails('${teamKey}')" style="background: #3b82f6; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.375rem; font-size: 0.875rem; cursor: pointer;">View Details</button>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        },

        /**
         * Join a team
         */
        joinTeam: function(teamKey) {
            console.log('Joining team:', teamKey);
            // TODO: Implement team joining functionality
            this.showAlert('Team joining functionality coming soon!', 'info');
        },

        /**
         * Load Stats & Goals content
         */
        loadVolunteerStatsGoals: function() {
            console.log('Loading Stats & Goals...');
            this.displayStatsGoalsInterface();
        },

        /**
         * Display Stats & Goals interface
         */
        displayStatsGoalsInterface: function() {
            const statsContainer = document.getElementById('claws-volunteers-stats-goals');
            if (!statsContainer) return;
            
            // Check user role (mock for now - in real implementation would check actual user role)
            const isCoordinatorOrAdmin = true; // This would be determined by actual user role
            
            if (isCoordinatorOrAdmin) {
                // Coordinator/Admin view with sidebar
                statsContainer.innerHTML = `
                    <div style="padding: 1.5rem; max-width: 1200px; margin: 0 auto;">
                        <div style="text-align: center; margin-bottom: 2rem;">
                            <h3 style="color: #1f2937; margin-bottom: 0.5rem; font-size: 1.5rem; font-weight: 600;">Stats & Goals</h3>
                            <p style="color: #6b7280; font-size: 1rem;">Analyze volunteer performance and organizational achievements.</p>
                        </div>
                        
                        <!-- Time Period Filter -->
                        <div style="margin-bottom: 2rem; display: flex; align-items: center; justify-content: center; gap: 1rem;">
                            <label style="font-weight: 500; color: #374151;">Show data for:</label>
                            <select id="stats-time-period" onchange="CLAWSApp.updateStatsTimeframe(this.value)" style="padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                                <option value="3months">Last 3 months</option>
                                <option value="6months">Last 6 months</option>
                                <option value="1year">Last 1 year</option>
                                <option value="lifetime">Lifetime</option>
                            </select>
                        </div>
                        
                        <div style="display: grid; grid-template-columns: 300px 1fr; gap: 2rem;">
                            <!-- Sidebar -->
                            <div style="background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb; overflow: hidden; height: fit-content;">
                                <div style="padding: 1rem; border-bottom: 1px solid #e5e7eb; background: #f9fafb;">
                                    <h4 style="margin: 0; color: #1f2937; font-size: 1.125rem; font-weight: 600;">View Options</h4>
                                </div>
                                
                                <div id="stats-sidebar" style="overflow-y: auto;">
                                    <!-- Everyone option -->
                                    <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('everyone', 'Everyone')" style="padding: 0.75rem 1rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='white'">
                                        <div style="display: flex; align-items: center;">
                                            <span style="font-size: 1.25rem; margin-right: 0.5rem;">🌍</span>
                                            <span style="font-weight: 500; color: #1f2937;">Everyone</span>
                                        </div>
                                    </div>
                                    
                                    <!-- Teams section -->
                                    <div class="stats-section">
                                        <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('teams', 'All Teams')" style="padding: 0.75rem 1rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='white'">
                                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                                <div style="display: flex; align-items: center;">
                                                    <span style="font-size: 1.25rem; margin-right: 0.5rem;">👥</span>
                                                    <span style="font-weight: 500; color: #1f2937;">Teams</span>
                                                </div>
                                                <button onclick="event.stopPropagation(); CLAWSApp.toggleStatsSection('teams')" class="expand-btn" style="background: none; border: none; font-size: 1.25rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;" onmouseover="this.style.background='#e5e7eb'" onmouseout="this.style.background='none'">+</button>
                                            </div>
                                        </div>
                                        <div id="teams-list" class="stats-subsection" style="display: none; background: #f9fafb;">
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('team-feeding', 'Feeding Team')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">🍽️ Feeding Team</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('team-shelter', 'Shelter Builds Team')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">🏠 Shelter Builds</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('team-education', 'Education Team')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">📚 Education</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('team-admin', 'Administration Team')" style="padding: 0.5rem 1rem 0.5rem 3rem; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">📋 Administration</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Volunteers section -->
                                    <div class="stats-section">
                                        <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('volunteers', 'All Volunteers')" style="padding: 0.75rem 1rem; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='white'">
                                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                                <div style="display: flex; align-items: center;">
                                                    <span style="font-size: 1.25rem; margin-right: 0.5rem;">👤</span>
                                                    <span style="font-weight: 500; color: #1f2937;">Volunteers</span>
                                                </div>
                                                <button onclick="event.stopPropagation(); CLAWSApp.toggleStatsSection('volunteers')" class="expand-btn" style="background: none; border: none; font-size: 1.25rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;" onmouseover="this.style.background='#e5e7eb'" onmouseout="this.style.background='none'">+</button>
                                            </div>
                                        </div>
                                        <div id="volunteers-list" class="stats-subsection" style="display: none; background: #f9fafb;">
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('volunteer-sarah', 'Sarah Johnson')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">Sarah Johnson</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('volunteer-mike', 'Mike Chen')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">Mike Chen</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('volunteer-lisa', 'Lisa Garcia')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">Lisa Garcia</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('volunteer-david', 'David Wilson')" style="padding: 0.5rem 1rem 0.5rem 3rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">David Wilson</span>
                                            </div>
                                            <div class="stats-option" onclick="CLAWSApp.selectStatsTarget('volunteer-emma', 'Emma Davis')" style="padding: 0.5rem 1rem 0.5rem 3rem; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f3f4f6'" onmouseout="this.style.background='#f9fafb'">
                                                <span style="color: #374151;">Emma Davis</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Main Content Area -->
                            <div id="stats-content" style="background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb; min-height: 500px; padding: 1.5rem;">
                                <div style="text-align: center; padding: 3rem; color: #6b7280;">
                                    <span style="font-size: 3rem; display: block; margin-bottom: 1rem;">📊</span>
                                    <h4 style="margin: 0 0 0.5rem; color: #1f2937;">Select a View Option</h4>
                                    <p>Choose from Everyone, Teams, or individual Volunteers to view detailed analytics.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            } else {
                // Regular volunteer view
                this.displayVolunteerPersonalStats();
            }
            
            // Initialize stats state
            this.currentStatsTarget = null;
            this.currentStatsTimeframe = '3months';
        },

        /**
         * Display personal volunteer stats (for regular volunteers)
         */
        displayVolunteerPersonalStats: function() {
            const statsContainer = document.getElementById('claws-volunteers-stats-goals');
            if (!statsContainer) return;
            
            statsContainer.innerHTML = `
                <div style="padding: 1.5rem; max-width: 900px; margin: 0 auto;">
                    <div style="text-align: center; margin-bottom: 2rem;">
                        <h3 style="color: #1f2937; margin-bottom: 0.5rem; font-size: 1.5rem; font-weight: 600;">Your Stats & Goals</h3>
                        <p style="color: #6b7280; font-size: 1rem;">Track your volunteer contributions and achievements.</p>
                    </div>
                    
                    <!-- Time Period Filter -->
                    <div style="margin-bottom: 2rem; display: flex; align-items: center; justify-content: center; gap: 1rem;">
                        <label style="font-weight: 500; color: #374151;">Show data for:</label>
                        <select id="personal-stats-time-period" onchange="CLAWSApp.updatePersonalStatsTimeframe(this.value)" style="padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                            <option value="3months">Last 3 months</option>
                            <option value="6months">Last 6 months</option>
                            <option value="1year">Last 1 year</option>
                            <option value="lifetime">Lifetime</option>
                        </select>
                    </div>
                    
                    <!-- Stats Content -->
                    <div id="personal-stats-content">
                        ${this.generatePersonalStatsContent('3months')}
                    </div>
                </div>
            `;
        },

        /**
         * Toggle stats section (Teams or Volunteers)
         */
        toggleStatsSection: function(sectionKey) {
            const sectionDiv = document.getElementById(sectionKey + '-list');
            const expandBtn = event.target;
            
            if (sectionDiv.style.display === 'none') {
                // Show section
                sectionDiv.style.display = 'block';
                expandBtn.textContent = '−';
                expandBtn.title = 'Hide ' + sectionKey;
            } else {
                // Hide section
                sectionDiv.style.display = 'none';
                expandBtn.textContent = '+';
                expandBtn.title = 'Show ' + sectionKey;
            }
        },

        /**
         * Select stats target
         */
        selectStatsTarget: function(targetId, targetName) {
            console.log('Selecting stats target:', targetId, targetName);
            
            // Clear previous selections
            document.querySelectorAll('.stats-option').forEach(item => {
                item.style.background = item.closest('.stats-subsection') ? '#f9fafb' : 'white';
            });
            
            // Highlight selected item
            event.target.closest('.stats-option').style.background = '#dbeafe';
            
            // Update current target
            this.currentStatsTarget = targetId;
            this.currentStatsTargetName = targetName;
            
            // Load stats for this target
            this.loadStatsForTarget(targetId, targetName);
        },

        /**
         * Load stats for selected target
         */
        loadStatsForTarget: function(targetId, targetName) {
            const statsContent = document.getElementById('stats-content');
            if (!statsContent) return;
            
            // Generate content based on target type
            let content = '';
            
            if (targetId === 'everyone') {
                content = this.generateEveryoneStats();
            } else if (targetId === 'teams' || targetId.startsWith('team-')) {
                content = this.generateTeamStats(targetId, targetName);
            } else if (targetId === 'volunteers' || targetId.startsWith('volunteer-')) {
                content = this.generateVolunteerStats(targetId, targetName);
            }
            
            statsContent.innerHTML = content;
        },

        /**
         * Generate everyone stats
         */
        generateEveryoneStats: function() {
            const timeframe = this.currentStatsTimeframe || '3months';
            const timeLabel = this.getTimeframeLabel(timeframe);
            
            return `
                <div>
                    <h4 style="margin: 0 0 1.5rem; color: #1f2937; font-size: 1.25rem; font-weight: 600;">🌍 Organization-wide Analytics (${timeLabel})</h4>
                    
                    <!-- Summary Cards -->
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
                        <div style="background: linear-gradient(135deg, #3b82f6, #1d4ed8); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">1,247</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Total Hours</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #10b981, #047857); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">23</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Active Volunteers</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #f59e0b, #d97706); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">156</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Tasks Completed</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">89</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Opportunities</div>
                        </div>
                    </div>
                    
                    <!-- Charts Row -->
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem;">
                        <!-- Activity Breakdown Chart -->
                        <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                            <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Activity Breakdown</h5>
                            <div style="display: grid; gap: 0.75rem;">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <div style="width: 12px; height: 12px; background: #3b82f6; border-radius: 2px;"></div>
                                        <span style="font-size: 0.875rem;">Feeding</span>
                                    </div>
                                    <span style="font-weight: 600;">412 hrs (33%)</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <div style="width: 12px; height: 12px; background: #10b981; border-radius: 2px;"></div>
                                        <span style="font-size: 0.875rem;">Shelter Builds</span>
                                    </div>
                                    <span style="font-weight: 600;">356 hrs (29%)</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <div style="width: 12px; height: 12px; background: #f59e0b; border-radius: 2px;"></div>
                                        <span style="font-size: 0.875rem;">Education</span>
                                    </div>
                                    <span style="font-weight: 600;">279 hrs (22%)</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <div style="width: 12px; height: 12px; background: #8b5cf6; border-radius: 2px;"></div>
                                        <span style="font-size: 0.875rem;">Administration</span>
                                    </div>
                                    <span style="font-weight: 600;">200 hrs (16%)</span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Top Performers -->
                        <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                            <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Top Performers</h5>
                            <div style="display: grid; gap: 0.75rem;">
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: white; border-radius: 0.5rem;">
                                    <span style="font-weight: 500;">🥇 Sarah Johnson</span>
                                    <span style="color: #3b82f6; font-weight: 600;">127 hrs</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: white; border-radius: 0.5rem;">
                                    <span style="font-weight: 500;">🥈 Mike Chen</span>
                                    <span style="color: #10b981; font-weight: 600;">98 hrs</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: white; border-radius: 0.5rem;">
                                    <span style="font-weight: 500;">🥉 Lisa Garcia</span>
                                    <span style="color: #f59e0b; font-weight: 600;">89 hrs</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Monthly Trend -->
                    <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                        <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Monthly Activity Trend</h5>
                        <div style="display: flex; align-items: end; gap: 0.5rem; height: 150px; padding: 1rem 0;">
                            ${this.generateTrendBars()}
                        </div>
                    </div>
                </div>
            `;
        },

        /**
         * Generate team stats
         */
        generateTeamStats: function(targetId, targetName) {
            const timeframe = this.currentStatsTimeframe || '3months';
            const timeLabel = this.getTimeframeLabel(timeframe);
            
            // Sample data varies by team
            const teamData = this.getTeamSampleData(targetId);
            
            return `
                <div>
                    <h4 style="margin: 0 0 1.5rem; color: #1f2937; font-size: 1.25rem; font-weight: 600;">${teamData.icon} ${targetName} Analytics (${timeLabel})</h4>
                    
                    <!-- Team Summary Cards -->
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
                        <div style="background: linear-gradient(135deg, ${teamData.colors.primary}, ${teamData.colors.secondary}); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${teamData.totalHours}</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Total Hours</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #10b981, #047857); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${teamData.memberCount}</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Team Members</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #f59e0b, #d97706); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${teamData.tasksCompleted}</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Tasks Completed</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                            <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${Math.round(teamData.totalHours / teamData.memberCount)}</div>
                            <div style="font-size: 0.875rem; opacity: 0.9;">Avg Hours/Member</div>
                        </div>
                    </div>
                    
                    <!-- Team Member Performance -->
                    <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb; margin-bottom: 2rem;">
                        <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Team Member Performance</h5>
                        <div style="display: grid; gap: 0.75rem;">
                            ${teamData.members.map((member, index) => `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; background: white; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                    <div style="display: flex; align-items: center; gap: 0.75rem;">
                                        <div style="width: 8px; height: 8px; background: ${teamData.colors.primary}; border-radius: 50%;"></div>
                                        <span style="font-weight: 500;">${member.name}</span>
                                    </div>
                                    <div style="text-align: right;">
                                        <div style="font-weight: 600; color: #1f2937;">${member.hours} hrs</div>
                                        <div style="font-size: 0.75rem; color: #6b7280;">${member.tasks} tasks</div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    
                    <!-- Team Activity Focus -->
                    <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                        <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Activity Focus Areas</h5>
                        <div style="display: grid; gap: 0.75rem;">
                            ${teamData.activities.map(activity => `
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <div style="width: 12px; height: 12px; background: ${activity.color}; border-radius: 2px;"></div>
                                        <span style="font-size: 0.875rem;">${activity.name}</span>
                                    </div>
                                    <span style="font-weight: 600;">${activity.hours} hrs (${activity.percentage}%)</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            `;
        },

        /**
         * Generate volunteer stats
         */
        generateVolunteerStats: function(targetId, targetName) {
            const timeframe = this.currentStatsTimeframe || '3months';
            const timeLabel = this.getTimeframeLabel(timeframe);
            
            if (targetId === 'volunteers') {
                // All volunteers summary
                return `
                    <div>
                        <h4 style="margin: 0 0 1.5rem; color: #1f2937; font-size: 1.25rem; font-weight: 600;">👤 All Volunteers Summary (${timeLabel})</h4>
                        
                        <!-- Volunteer Directory -->
                        <div style="display: grid; gap: 1rem;">
                            ${this.getAllVolunteersSummary().map(volunteer => `
                                <div style="background: #f9fafb; padding: 1rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                                    <div style="display: flex; justify-content: space-between; align-items: center;">
                                        <div>
                                            <h6 style="margin: 0 0 0.25rem; font-weight: 600; color: #1f2937;">${volunteer.name}</h6>
                                            <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${volunteer.team} • ${volunteer.joinDate}</p>
                                        </div>
                                        <div style="text-align: right;">
                                            <div style="font-weight: 600; color: #1f2937; font-size: 1.125rem;">${volunteer.hours} hrs</div>
                                            <div style="font-size: 0.75rem; color: #6b7280;">${volunteer.tasks} tasks completed</div>
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            } else {
                // Individual volunteer stats
                return this.generateIndividualVolunteerStats(targetId, targetName, timeframe);
            }
        },

        /**
         * Generate individual volunteer stats
         */
        generateIndividualVolunteerStats: function(targetId, targetName, timeframe) {
            const timeLabel = this.getTimeframeLabel(timeframe);
            const volunteerData = this.getVolunteerSampleData(targetId);
            
            return `
                <div>
                    <h4 style="margin: 0 0 1.5rem; color: #1f2937; font-size: 1.25rem; font-weight: 600;">👤 ${targetName} - Personal Analytics (${timeLabel})</h4>
                    
                    ${this.generatePersonalStatsContent(timeframe, volunteerData)}
                </div>
            `;
        },

        /**
         * Generate personal stats content
         */
        generatePersonalStatsContent: function(timeframe, data = null) {
            const volunteerData = data || this.getVolunteerSampleData('current-user');
            
            return `
                <!-- Personal Summary Cards -->
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
                    <div style="background: linear-gradient(135deg, #3b82f6, #1d4ed8); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                        <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${volunteerData.totalHours}</div>
                        <div style="font-size: 0.875rem; opacity: 0.9;">Total Hours</div>
                    </div>
                    <div style="background: linear-gradient(135deg, #10b981, #047857); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                        <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${volunteerData.tasksCompleted}</div>
                        <div style="font-size: 0.875rem; opacity: 0.9;">Tasks Completed</div>
                    </div>
                    <div style="background: linear-gradient(135deg, #f59e0b, #d97706); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                        <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${volunteerData.eventsJoined}</div>
                        <div style="font-size: 0.875rem; opacity: 0.9;">Opportunities</div>
                    </div>
                    <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 1.5rem; border-radius: 0.75rem; color: white; text-align: center;">
                        <div style="font-size: 2rem; font-weight: bold; margin-bottom: 0.5rem;">${volunteerData.avgHoursPerWeek}</div>
                        <div style="font-size: 0.875rem; opacity: 0.9;">Avg Hours/Week</div>
                    </div>
                </div>
                
                <!-- Charts Row -->
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem;">
                    <!-- Your Activity Breakdown -->
                    <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                        <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Your Activity Breakdown</h5>
                        <div style="display: grid; gap: 0.75rem;">
                            ${volunteerData.activities.map(activity => `
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                                        <div style="width: 12px; height: 12px; background: ${activity.color}; border-radius: 2px;"></div>
                                        <span style="font-size: 0.875rem;">${activity.name}</span>
                                    </div>
                                    <span style="font-weight: 600;">${activity.hours} hrs (${activity.percentage}%)</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    
                    <!-- Recent Achievements -->
                    <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                        <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Recent Achievements</h5>
                        <div style="display: grid; gap: 0.75rem;">
                            ${volunteerData.achievements.map(achievement => `
                                <div style="display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem; background: white; border-radius: 0.5rem;">
                                    <span style="font-size: 1.25rem;">${achievement.icon}</span>
                                    <div>
                                        <div style="font-weight: 500; font-size: 0.875rem;">${achievement.title}</div>
                                        <div style="font-size: 0.75rem; color: #6b7280;">${achievement.date}</div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
                
                <!-- Weekly Activity Trend -->
                <div style="background: #f9fafb; padding: 1.5rem; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                    <h5 style="margin: 0 0 1rem; color: #1f2937; font-weight: 600;">Weekly Activity Trend</h5>
                    <div style="display: flex; align-items: end; gap: 0.5rem; height: 120px; padding: 1rem 0;">
                        ${volunteerData.weeklyHours.map((hours, index) => `
                            <div style="flex: 1; background: linear-gradient(to top, #3b82f6, #1d4ed8); border-radius: 2px 2px 0 0; height: ${(hours / Math.max(...volunteerData.weeklyHours)) * 100}%; min-height: 4px; position: relative;" title="Week ${index + 1}: ${hours} hours"></div>
                        `).join('')}
                    </div>
                    <div style="display: flex; justify-content: space-between; margin-top: 0.5rem; font-size: 0.75rem; color: #6b7280;">
                        ${volunteerData.weeklyHours.map((_, index) => `<span>W${index + 1}</span>`).join('')}
                    </div>
                </div>
            `;
        },

        /**
         * Update stats timeframe
         */
        updateStatsTimeframe: function(timeframe) {
            this.currentStatsTimeframe = timeframe;
            console.log('Updating stats timeframe to:', timeframe);
            
            // Reload current target with new timeframe
            if (this.currentStatsTarget) {
                this.loadStatsForTarget(this.currentStatsTarget, this.currentStatsTargetName);
            }
        },

        /**
         * Update personal stats timeframe
         */
        updatePersonalStatsTimeframe: function(timeframe) {
            this.currentStatsTimeframe = timeframe;
            const statsContent = document.getElementById('personal-stats-content');
            if (statsContent) {
                statsContent.innerHTML = this.generatePersonalStatsContent(timeframe);
            }
        },

        /**
         * Clean up duplicate colonies (admin function)
         */
        cleanupDuplicateColonies: async function() {
            if (!confirm('This will remove duplicate colony entries. Are you sure? This action cannot be undone.')) {
                return;
            }
            
            try {
                this.showLoading();
                
                const response = await fetch(this.config.apiUrl + 'colonies/cleanup-duplicates', {
                    method: 'POST',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    this.showAlert(result.message, 'success');
                    
                    // Reload colonies to see the cleaned up list
                    await this.loadColonies();
                    this.updateColonyUI();
                } else {
                    throw new Error('Cleanup failed: ' + response.status);
                }
            } catch (error) {
                console.error('Cleanup error:', error);
                this.showAlert('Failed to clean up duplicates: ' + error.message, 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Load Comms content
         */
        loadVolunteerComms: function() {
            console.log('Loading Comms...');
            this.displayCommunicationsInterface();
        },

        /**
         * Display communications interface
         */
        displayCommunicationsInterface: function() {
            const commsContainer = document.getElementById('claws-volunteers-comms');
            if (!commsContainer) return;
            
            commsContainer.innerHTML = `
                <div style="padding: 1.5rem; max-width: 1200px; margin: 0 auto;">
                    <div style="text-align: center; margin-bottom: 2rem;">
                        <h3 style="color: #1f2937; margin-bottom: 0.5rem; font-size: 1.5rem; font-weight: 600;">Communications</h3>
                        <p style="color: #6b7280; font-size: 1rem;">Send messages to teams or individual volunteers.</p>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 300px; gap: 2rem; height: 600px;">
                        <!-- Messages Area -->
                        <div style="display: flex; flex-direction: column; background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb; overflow: hidden;">
                            <!-- Message Header -->
                            <div id="message-header" style="padding: 1rem; border-bottom: 1px solid #e5e7eb; background: #f9fafb;">
                                <h4 style="margin: 0; color: #1f2937; font-size: 1.125rem; font-weight: 600;">Select a team or member to start messaging</h4>
                            </div>
                            
                            <!-- Messages Display -->
                            <div id="messages-display" style="flex: 1; padding: 1rem; overflow-y: auto; background: white;">
                                <div style="text-align: center; padding: 2rem; color: #6b7280;">
                                    <span style="font-size: 3rem; display: block; margin-bottom: 1rem;">💬</span>
                                    <p>Select a team or individual from the list to view messages</p>
                                </div>
                            </div>
                            
                            <!-- Message Composition -->
                            <div id="message-compose" style="padding: 1rem; border-top: 1px solid #e5e7eb; background: #f9fafb; display: none;">
                                <div style="display: flex; gap: 0.5rem;">
                                    <input type="text" id="message-input" placeholder="Type your message..." onkeypress="if(event.key==='Enter') CLAWSApp.sendMessage()" style="flex: 1; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;" />
                                    <button onclick="CLAWSApp.sendMessage()" style="background: #3b82f6; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.375rem; font-size: 0.875rem; cursor: pointer; font-weight: 500;">Send</button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Teams and Members Sidebar -->
                        <div style="background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb; overflow: hidden;">
                            <div style="padding: 1rem; border-bottom: 1px solid #e5e7eb; background: #f9fafb;">
                                <h4 style="margin: 0; color: #1f2937; font-size: 1.125rem; font-weight: 600;">Teams & Members</h4>
                            </div>
                            
                            <div id="teams-list" style="overflow-y: auto; max-height: 520px;">
                                <!-- Everyone option with expand functionality -->
                                <div class="team-container">
                                    <div class="team-item" onclick="CLAWSApp.selectTarget('everyone', 'Everyone')" style="padding: 0.75rem 1rem; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='white'">
                                        <div style="display: flex; align-items: center; justify-content: space-between;">
                                            <div style="display: flex; align-items: center;">
                                                <span style="font-size: 1.25rem; margin-right: 0.5rem;">📢</span>
                                                <span style="font-weight: 600; color: #1f2937;">Everyone</span>
                                            </div>
                                            <button onclick="event.stopPropagation(); CLAWSApp.toggleEveryoneList()" class="expand-btn" style="background: none; border: none; font-size: 1.25rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;" onmouseover="this.style.background='#e5e7eb'" onmouseout="this.style.background='none'">+</button>
                                        </div>
                                    </div>
                                    <div id="everyone-list" class="everyone-members" style="display: none; background: #f9fafb; max-height: 300px; overflow-y: auto;">
                                        <!-- Volunteer list will be populated here -->
                                        <div style="padding: 1rem; text-align: center; color: #6b7280;">
                                            <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">⏳</div>
                                            <p style="margin: 0; font-size: 0.875rem;">Loading volunteers...</p>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Teams section (will show active event-based teams when they exist) -->
                                <div id="active-teams-section">
                                    <!-- Active teams will be populated here when events exist -->
                                </div>
                                
                                <!-- No teams message -->
                                <div id="no-teams-message" style="padding: 2rem 1rem; text-align: center; color: #6b7280; border-top: 1px solid #f3f4f6;">
                                    <div style="font-size: 2rem; margin-bottom: 0.5rem;">👥</div>
                                    <p style="margin: 0 0 0.5rem; font-weight: 500; color: #374151;">No Active Teams</p>
                                    <p style="margin: 0; font-size: 0.875rem; line-height: 1.4;">
                                        Teams are automatically created when volunteers sign up for events. 
                                        Once events are posted and volunteers join them, teams will appear here.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Initialize communications state
            this.currentMessageTarget = null;
            this.currentMessageTargetName = '';
            this.currentMessageTargetType = ''; // 'team', 'user', or 'everyone'
            this.selectedVolunteers = new Set(); // For group messaging
            
            // Load active teams (event-based)
            this.loadActiveTeams();
            
            // Load volunteers list (but don't show until expanded)
            this.loadVolunteersForComms();
        },

        /**
         * Toggle team members display
         */
        toggleTeamMembers: function(teamKey) {
            const membersDiv = document.getElementById(teamKey + '-members');
            const expandBtn = event.target;
            
            if (membersDiv.style.display === 'none') {
                // Show members
                membersDiv.style.display = 'block';
                expandBtn.textContent = '−';
                expandBtn.title = 'Hide members';
            } else {
                // Hide members
                membersDiv.style.display = 'none';
                expandBtn.textContent = '+';
                expandBtn.title = 'Show members';
            }
        },

        /**
         * Toggle everyone list display with checkboxes
         */
        toggleEveryoneList: function() {
            const everyoneList = document.getElementById('everyone-list');
            const expandBtn = event.target;
            
            if (everyoneList.style.display === 'none') {
                // Show everyone list
                everyoneList.style.display = 'block';
                expandBtn.textContent = '−';
                expandBtn.title = 'Hide volunteer list';
            } else {
                // Hide everyone list
                everyoneList.style.display = 'none';
                expandBtn.textContent = '+';
                expandBtn.title = 'Show volunteer list';
            }
        },

        /**
         * Load active teams (event-based)
         */
        loadActiveTeams: function() {
            // TODO: Replace with actual API call to get active teams based on events
            // For now, hide teams section since no events exist
            const activeTeamsSection = document.getElementById('active-teams-section');
            const noTeamsMessage = document.getElementById('no-teams-message');
            
            if (activeTeamsSection) {
                activeTeamsSection.innerHTML = ''; // No active teams
            }
            
            if (noTeamsMessage) {
                noTeamsMessage.style.display = 'block'; // Show no teams message
            }
        },

        /**
         * Load volunteers list for communications
         */
        loadVolunteersForComms: function() {
            // TODO: Replace with actual API call to get all volunteers
            // For now, create a sample list that would come from the API
            const volunteers = [
                { id: 'current_user', name: 'You', role: 'volunteer', isCurrentUser: true },
                { id: 'admin_1', name: 'Admin User', role: 'administrator' },
                { id: 'coord_1', name: 'Coordinator Jane', role: 'coordinator' },
                { id: 'vol_1', name: 'Sarah Johnson', role: 'volunteer' },
                { id: 'vol_2', name: 'Mike Chen', role: 'volunteer' },
                { id: 'vol_3', name: 'Lisa Garcia', role: 'volunteer' }
            ];
            
            this.populateEveryoneList(volunteers);
        },

        /**
         * Populate everyone list with checkboxes
         */
        populateEveryoneList: function(volunteers) {
            const everyoneList = document.getElementById('everyone-list');
            if (!everyoneList) return;
            
            const getRoleIcon = (role) => {
                switch(role) {
                    case 'administrator': return '🔧';
                    case 'coordinator': return '📋';
                    case 'volunteer': return '👤';
                    default: return '👤';
                }
            };
            
            const getRoleColor = (role) => {
                switch(role) {
                    case 'administrator': return '#dc2626';
                    case 'coordinator': return '#7c3aed';
                    case 'volunteer': return '#059669';
                    default: return '#6b7280';
                }
            };
            
            everyoneList.innerHTML = volunteers.map(volunteer => `
                <div class="volunteer-item" style="padding: 0.5rem 1rem; border-bottom: 1px solid #f3f4f6; display: flex; align-items: center; gap: 0.75rem;">
                    <input type="checkbox" id="volunteer-${volunteer.id}" onchange="CLAWSApp.toggleVolunteerSelection('${volunteer.id}')" style="width: 1rem; height: 1rem; cursor: pointer;" />
                    <label for="volunteer-${volunteer.id}" style="flex: 1; display: flex; align-items: center; gap: 0.5rem; cursor: pointer; color: #374151;">
                        <span style="font-size: 1rem;">${getRoleIcon(volunteer.role)}</span>
                        <span style="font-weight: ${volunteer.isCurrentUser ? '600' : '400'};">
                            ${volunteer.name}${volunteer.isCurrentUser ? ' (You)' : ''}
                        </span>
                        <span style="background: ${getRoleColor(volunteer.role)}; color: white; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.6875rem; font-weight: 500; text-transform: uppercase;">
                            ${volunteer.role}
                        </span>
                    </label>
                </div>
            `).join('') + `
                <div style="padding: 0.75rem 1rem; border-top: 1px solid #e5e7eb; background: white;">
                    <button id="create-group-btn" onclick="CLAWSApp.createGroupChat()" disabled style="width: 100%; background: #d1d5db; color: #6b7280; border: none; padding: 0.5rem; border-radius: 0.375rem; font-size: 0.875rem; cursor: not-allowed;">
                        Create Group Chat (Select 2+ people)
                    </button>
                </div>
            `;
        },

        /**
         * Toggle volunteer selection for group messaging
         */
        toggleVolunteerSelection: function(volunteerId) {
            if (this.selectedVolunteers.has(volunteerId)) {
                this.selectedVolunteers.delete(volunteerId);
            } else {
                this.selectedVolunteers.add(volunteerId);
            }
            
            // Update group chat button state
            const createGroupBtn = document.getElementById('create-group-btn');
            if (createGroupBtn) {
                if (this.selectedVolunteers.size >= 2) {
                    createGroupBtn.disabled = false;
                    createGroupBtn.style.background = '#3b82f6';
                    createGroupBtn.style.color = 'white';
                    createGroupBtn.style.cursor = 'pointer';
                    createGroupBtn.textContent = `Create Group Chat (${this.selectedVolunteers.size} selected)`;
                } else {
                    createGroupBtn.disabled = true;
                    createGroupBtn.style.background = '#d1d5db';
                    createGroupBtn.style.color = '#6b7280';
                    createGroupBtn.style.cursor = 'not-allowed';
                    createGroupBtn.textContent = 'Create Group Chat (Select 2+ people)';
                }
            }
        },

        /**
         * Create group chat with selected volunteers
         */
        createGroupChat: function() {
            if (this.selectedVolunteers.size < 2) {
                this.showAlert('Please select at least 2 people for a group chat.', 'warning');
                return;
            }
            
            console.log('Creating group chat with:', Array.from(this.selectedVolunteers));
            
            // TODO: Implement actual group chat creation
            this.showAlert(`Group chat functionality coming soon! Selected ${this.selectedVolunteers.size} people.`, 'info');
            
            // Clear selections
            this.selectedVolunteers.clear();
            document.querySelectorAll('#everyone-list input[type="checkbox"]').forEach(cb => cb.checked = false);
            this.toggleVolunteerSelection(''); // Update button state
        },

        /**
         * Select message target (team, individual, or everyone)
         */
        selectTarget: function(targetId, targetName, teamKey = null) {
            console.log('Selecting target:', targetId, targetName, teamKey);
            
            // Clear previous selections
            document.querySelectorAll('.team-item, .member-item').forEach(item => {
                item.style.background = item.classList.contains('member-item') ? '#f9fafb' : 'white';
            });
            
            // Highlight selected item
            event.target.closest('.team-item, .member-item').style.background = '#dbeafe';
            
            // Update current target
            this.currentMessageTarget = targetId;
            this.currentMessageTargetName = targetName;
            
            // Determine target type
            if (targetId === 'everyone') {
                this.currentMessageTargetType = 'everyone';
            } else if (targetId.startsWith('user_')) {
                this.currentMessageTargetType = 'user';
            } else {
                this.currentMessageTargetType = 'team';
            }
            
            // Update message header
            const messageHeader = document.getElementById('message-header');
            const messageCompose = document.getElementById('message-compose');
            
            if (messageHeader && messageCompose) {
                let headerText = '';
                if (this.currentMessageTargetType === 'everyone') {
                    headerText = '📢 Messaging: Everyone (System-wide message)';
                } else if (this.currentMessageTargetType === 'user') {
                    headerText = `👤 Messaging: ${targetName} (Direct message)`;
                } else {
                    headerText = `👥 Messaging: ${targetName} (Team message)`;
                }
                
                messageHeader.innerHTML = `<h4 style="margin: 0; color: #1f2937; font-size: 1.125rem; font-weight: 600;">${headerText}</h4>`;
                messageCompose.style.display = 'block';
                
                // Load messages for this target
                this.loadMessagesForTarget(targetId);
            }
        },

        /**
         * Load messages for selected target
         */
        loadMessagesForTarget: function(targetId) {
            const messagesDisplay = document.getElementById('messages-display');
            if (!messagesDisplay) return;
            
            // Sample messages for demo
            const sampleMessages = {
                'everyone': [
                    { sender: 'Admin User', message: 'Welcome to the new messaging system! You can now communicate with teams and individuals.', timestamp: '2024-12-20 10:30 AM', isOwn: false },
                    { sender: 'Sarah Johnson', message: 'This is great! Much easier to coordinate now.', timestamp: '2024-12-20 10:35 AM', isOwn: false }
                ],
                'feeding': [
                    { sender: 'Sarah Johnson', message: 'Reminder: Colony A needs feeding today at 6 PM', timestamp: '2024-12-20 9:15 AM', isOwn: false },
                    { sender: 'Mike Chen', message: 'I can cover Colony B this weekend', timestamp: '2024-12-20 11:20 AM', isOwn: false },
                    { sender: 'You', message: 'Thanks Mike! I\'ll update the schedule.', timestamp: '2024-12-20 11:25 AM', isOwn: true }
                ],
                'user_1': [
                    { sender: 'You', message: 'Hi Sarah, are you available for the colony feeding training this weekend?', timestamp: '2024-12-19 2:30 PM', isOwn: true },
                    { sender: 'Sarah Johnson', message: 'Yes, I\'ll be there! What time should I arrive?', timestamp: '2024-12-19 3:15 PM', isOwn: false }
                ]
            };
            
            const messages = sampleMessages[targetId] || [];
            
            if (messages.length === 0) {
                messagesDisplay.innerHTML = `
                    <div style="text-align: center; padding: 2rem; color: #6b7280;">
                        <span style="font-size: 2rem; display: block; margin-bottom: 1rem;">💬</span>
                        <p>No messages yet. Start the conversation!</p>
                    </div>
                `;
                return;
            }
            
            messagesDisplay.innerHTML = messages.map(msg => `
                <div style="margin-bottom: 1rem; padding: 0.75rem; border-radius: 0.5rem; ${msg.isOwn ? 'background: #dbeafe; margin-left: 2rem;' : 'background: #f3f4f6; margin-right: 2rem;'}">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                        <span style="font-weight: 600; color: #1f2937; font-size: 0.875rem;">${msg.sender}</span>
                        <span style="color: #6b7280; font-size: 0.75rem;">${msg.timestamp}</span>
                    </div>
                    <p style="margin: 0; color: #374151; line-height: 1.4;">${msg.message}</p>
                </div>
            `).join('');
            
            // Scroll to bottom
            messagesDisplay.scrollTop = messagesDisplay.scrollHeight;
        },

        /**
         * Send a message
         */
        sendMessage: function() {
            const messageInput = document.getElementById('message-input');
            if (!messageInput || !messageInput.value.trim()) return;
            
            const message = messageInput.value.trim();
            const timestamp = new Date().toLocaleString('en-US', {
                month: 'numeric',
                day: 'numeric',
                year: 'numeric',
                hour: 'numeric',
                minute: '2-digit',
                hour12: true
            });
            
            // Add message to display
            const messagesDisplay = document.getElementById('messages-display');
            if (messagesDisplay) {
                // Create new message element
                const messageEl = document.createElement('div');
                messageEl.style.cssText = 'margin-bottom: 1rem; padding: 0.75rem; border-radius: 0.5rem; background: #dbeafe; margin-left: 2rem;';
                messageEl.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                        <span style="font-weight: 600; color: #1f2937; font-size: 0.875rem;">You</span>
                        <span style="color: #6b7280; font-size: 0.75rem;">${timestamp}</span>
                    </div>
                    <p style="margin: 0; color: #374151; line-height: 1.4;">${message}</p>
                `;
                
                // Check if there's a "no messages" placeholder and remove it
                const placeholder = messagesDisplay.querySelector('div[style*="text-align: center"]');
                if (placeholder && placeholder.textContent.includes('No messages yet')) {
                    messagesDisplay.innerHTML = '';
                }
                
                messagesDisplay.appendChild(messageEl);
                messagesDisplay.scrollTop = messagesDisplay.scrollHeight;
            }
            
            // Clear input
            messageInput.value = '';
            
            // Show success message
            let targetText = this.currentMessageTargetName;
            if (this.currentMessageTargetType === 'everyone') {
                targetText = 'all users';
            }
            
            this.showAlert(`Message sent to ${targetText}!`, 'success');
            
            // TODO: Send actual message via API
            console.log('Sending message:', {
                target: this.currentMessageTarget,
                targetType: this.currentMessageTargetType,
                message: message,
                timestamp: timestamp
            });
        },

        /**
         * Load Admin content
         */
        loadVolunteerAdmin: function() {
            console.log('Loading Admin...');
            // Load pending tasks for this coordinator/admin
            this.loadPendingTasks();
            this.loadApprovedTasks();
        },

        /**
         * Load pending tasks for approval
         */
        loadPendingTasks: function() {
            console.log('Loading pending tasks...');
            
            const pendingTasksList = document.getElementById('pending-tasks-list');
            if (!pendingTasksList) return;
            
            if (this.config.demoMode) {
                // Show sample pending tasks
                pendingTasksList.innerHTML = `
                    <div style="space-y: 1rem;">
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: white;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                <div style="flex: 1;">
                                    <h5 style="margin: 0; font-weight: 600; color: #1f2937;">Colony Feeding</h5>
                                    <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">Submitted by: Jane Volunteer | Date: Dec 15, 2024 | 2.5 hours</p>
                                </div>
                                <div style="display: flex; gap: 0.5rem;">
                                    <button onclick="CLAWSApp.approveTask(1)" style="padding: 0.5rem 1rem; background: #10b981; color: white; border: none; border-radius: 0.25rem; font-size: 0.875rem; cursor: pointer;">Approve</button>
                                    <button onclick="CLAWSApp.rejectTask(1)" style="padding: 0.5rem 1rem; background: #ef4444; color: white; border: none; border-radius: 0.25rem; font-size: 0.875rem; cursor: pointer;">Reject</button>
                                </div>
                            </div>
                            <p style="margin: 0; color: #374151; font-size: 0.875rem;">Fed cats at downtown colony, refilled water stations</p>
                        </div>
                        
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: white;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                <div style="flex: 1;">
                                    <h5 style="margin: 0; font-weight: 600; color: #1f2937;">TNR Transport</h5>
                                    <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">Submitted by: Bob Helper | Date: Dec 14, 2024 | 3 hours</p>
                                </div>
                                <div style="display: flex; gap: 0.5rem;">
                                    <button onclick="CLAWSApp.approveTask(2)" style="padding: 0.5rem 1rem; background: #10b981; color: white; border: none; border-radius: 0.25rem; font-size: 0.875rem; cursor: pointer;">Approve</button>
                                    <button onclick="CLAWSApp.rejectTask(2)" style="padding: 0.5rem 1rem; background: #ef4444; color: white; border: none; border-radius: 0.25rem; font-size: 0.875rem; cursor: pointer;">Reject</button>
                                </div>
                            </div>
                            <p style="margin: 0; color: #374151; font-size: 0.875rem;">Drove 2 cats to the clinic for spay/neuter surgery</p>
                        </div>
                    </div>
                `;
                return;
            }
            
            // TODO: Implement API call to load pending tasks for this coordinator
            pendingTasksList.innerHTML = '<p style="color: #6b7280; text-align: center; padding: 2rem;">Loading pending tasks...</p>';
        },

        /**
         * Load approved tasks
         */
        loadApprovedTasks: function() {
            console.log('Loading approved tasks...');
            
            const approvedTasksList = document.getElementById('approved-tasks-list');
            if (!approvedTasksList) return;
            
            if (this.config.demoMode) {
                // Show sample approved tasks
                approvedTasksList.innerHTML = `
                    <div style="space-y: 1rem;">
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: white;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                <div style="flex: 1;">
                                    <h5 style="margin: 0; font-weight: 600; color: #1f2937;">Colony Maintenance</h5>
                                    <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">Approved: Dec 12, 2024 | Volunteer: Alice Helper | 1.5 hours</p>
                                </div>
                                <div style="padding: 0.25rem 0.5rem; background: #dcfce7; color: #166534; border-radius: 0.25rem; font-size: 0.75rem;">
                                    ✅ Approved
                                </div>
                            </div>
                            <p style="margin: 0; color: #374151; font-size: 0.875rem;">Cleaned and restocked feeding stations, checked shelters</p>
                        </div>
                        
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: white;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                <div style="flex: 1;">
                                    <h5 style="margin: 0; font-weight: 600; color: #1f2937;">Educational Outreach</h5>
                                    <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">Approved: Dec 10, 2024 | Volunteer: Mike Educator | 3 hours</p>
                                </div>
                                <div style="padding: 0.25rem 0.5rem; background: #dcfce7; color: #166534; border-radius: 0.25rem; font-size: 0.75rem;">
                                    ✅ Approved
                                </div>
                            </div>
                            <p style="margin: 0; color: #374151; font-size: 0.875rem;">Presented at community center about TNR programs</p>
                        </div>
                    </div>
                `;
                return;
            }
            
            // TODO: Implement API call to load approved tasks for this coordinator
            approvedTasksList.innerHTML = '<p style="color: #6b7280; text-align: center; padding: 2rem;">Loading approved tasks...</p>';
        },

        /**
         * Approve a completed task
         */
        approveTask: function(taskId) {
            console.log('Approving task:', taskId);
            if (confirm('Approve this completed task?')) {
                // TODO: Implement task approval API call
                this.showAlert('Task approved successfully!', 'success');
                // Refresh the admin view
                this.loadPendingTasks();
                this.loadApprovedTasks();
            }
        },

        /**
         * Reject a completed task
         */
        rejectTask: function(taskId) {
            console.log('Rejecting task:', taskId);
            const reason = prompt('Please provide a reason for rejecting this task:');
            if (reason !== null && reason.trim() !== '') {
                // TODO: Implement task rejection API call
                this.showAlert('Task rejected successfully!', 'success');
                // Refresh the admin view
                this.loadPendingTasks();
            }
        },

        /**
         * Load coordinators (editors and administrators) for dropdown
         */
        loadCoordinators: function() {
            console.log('Loading coordinators...');
            
            // TODO: Replace with actual API call to get users with editor and administrator roles
            const coordinatorDropdown = document.getElementById('claws-task-coordinator');
            if (coordinatorDropdown) {
                coordinatorDropdown.innerHTML = '<option value="">Select coordinator...</option>';
                // Coordinators will be populated when backend is implemented
            }
        },

        /**
         * Load task types for dropdown
         */
        /**
         * Get unified task/event types
         */
        getUnifiedTaskEventTypes: function() {
            return {
                // Colony Care types (require colony selection)
                'colony-feeding': 'Colony Care - Feeding',
                'colony-shelter': 'Colony Care - Winter Shelter Building', 
                'colony-safety': 'Colony Care - Safety/Maintenance',
                'colony-monitoring': 'Colony Care - Population Monitoring',
                'colony-setup': 'Colony Care - New Colony Setup',
                
                // TNR Related
                'tnr-party': 'TNR Party',
                'tnr-transport': 'TNR Transport',
                'tnr-recovery': 'TNR Recovery Care',
                
                // Education & Outreach
                'education': 'Education & Training',
                'community-outreach': 'Community Outreach',
                'public-speaking': 'Public Speaking/Presentations',
                
                // Administrative & Support
                'administrative': 'Administrative Work',
                'fundraising': 'Fundraising',
                'event-support': 'Event Support/Coordination',
                'social-media': 'Social Media Management',
                
                // Direct Animal Care
                'foster-care': 'Foster Care',
                'animal-transport': 'Animal Transport',
                'medical-support': 'Medical Support/Vet Assistance',
                
                // Facilities & Equipment
                'maintenance': 'Equipment/Facility Maintenance',
                'supply-management': 'Supply Management',
                
                // Other
                'other': 'Other'
            };
        },

        /**
         * Check if task type requires colony selection
         */
        requiresColonySelection: function(taskType) {
            return taskType && taskType.startsWith('colony-');
        },

        loadTaskTypes: function() {
            console.log('Loading unified task types...');
            
            const taskTypeDropdown = document.getElementById('claws-task-type');
            if (!taskTypeDropdown) return;
            
            const unifiedTypes = this.getUnifiedTaskEventTypes();
            
            let optionsHtml = '<option value="">Select task/event type...</option>';
            
            // Group by category for better organization
            const categories = {
                'Colony Care': ['colony-feeding', 'colony-shelter', 'colony-safety', 'colony-monitoring', 'colony-setup'],
                'TNR Activities': ['tnr-party', 'tnr-transport', 'tnr-recovery'],
                'Education & Outreach': ['education', 'community-outreach', 'public-speaking'],
                'Administrative': ['administrative', 'fundraising', 'event-support', 'social-media'],
                'Animal Care': ['foster-care', 'animal-transport', 'medical-support'],
                'Facilities': ['maintenance', 'supply-management'],
                'Other': ['other']
            };
            
            Object.entries(categories).forEach(([categoryName, typeKeys]) => {
                optionsHtml += `<optgroup label="${categoryName}">`;
                typeKeys.forEach(key => {
                    if (unifiedTypes[key]) {
                        optionsHtml += `<option value="${key}">${unifiedTypes[key]}</option>`;
                    }
                });
                optionsHtml += '</optgroup>';
            });
            
            taskTypeDropdown.innerHTML = optionsHtml;
            
            // Set up change handler for colony selection
            this.setupTaskTypeChangeHandler();
        },

        /**
         * Setup task type change handler for colony selection
         */
        setupTaskTypeChangeHandler: function() {
            const taskTypeDropdown = document.getElementById('claws-task-type');
            const colonySection = document.getElementById('claws-task-colony-section');
            
            if (taskTypeDropdown) {
                taskTypeDropdown.addEventListener('change', (e) => {
                    const selectedType = e.target.value;
                    
                    if (this.requiresColonySelection(selectedType)) {
                        if (colonySection) {
                            colonySection.style.display = 'block';
                            this.populateTaskColonyDropdown();
                        }
                    } else {
                        if (colonySection) {
                            colonySection.style.display = 'none';
                        }
                    }
                });
            }
        },

        /**
         * Populate colony dropdown for task form
         */
        populateTaskColonyDropdown: function() {
            const colonyDropdown = document.getElementById('claws-task-colony');
            if (!colonyDropdown) return;
            
            // Use existing colonies data
            if (this.colonies && this.colonies.length > 0) {
                let optionsHtml = '<option value="">Select colony...</option>';
                this.colonies.forEach(colony => {
                    optionsHtml += `<option value="${colony.id}">${colony.name}</option>`;
                });
                colonyDropdown.innerHTML = optionsHtml;
            } else {
                colonyDropdown.innerHTML = '<option value="">Loading colonies...</option>';
                // Load colonies if not already loaded
                this.loadColonies().then(() => {
                    this.populateTaskColonyDropdown();
                });
            }
        },

        /**
         * Load pending items (tasks and events) for the current user
         */
        /**
         * Load needs attention items
         */
        loadNeedsAttentionItems: function() {
            console.log('Loading needs attention items...');
            
            const needsAttentionContainer = document.getElementById('claws-needs-attention-items');
            const needsAttentionSection = document.getElementById('claws-needs-attention-section');
            if (!needsAttentionContainer || !needsAttentionSection) return;
            
            // TODO: Replace with actual API call when backend is implemented
            // For now, show empty state
            needsAttentionContainer.innerHTML = `
                <div style="text-align: center; padding: 2rem; color: #92400e;">
                    <div style="font-size: 2rem; margin-bottom: 1rem;">👍</div>
                    <p style="margin: 0; font-size: 0.875rem; font-style: italic;">No tasks need attention right now</p>
                </div>
            `;
            
            // Show the section but with empty state
            needsAttentionSection.style.display = 'block';
        },

        loadPendingItems: function() {
            console.log('Loading pending items...');
            
            const pendingItemsContainer = document.getElementById('claws-pending-items');
            if (!pendingItemsContainer) return;
            
            if (this.config.demoMode) {
                // Show sample pending items in demo mode
                pendingItemsContainer.innerHTML = `
                    <div style="space-y: 1rem;">
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: #f9fafb;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                <div>
                                    <h5 style="margin: 0; font-weight: 600; color: #1f2937;">Colony Feeding <span style="background: #dbeafe; color: #1e40af; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">TASK</span></h5>
                                    <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">Date: Dec 15, 2024 | 2.5 hours</p>
                                </div>
                                <div style="display: flex; gap: 0.5rem;">
                                    <button onclick="CLAWSApp.editTask(1)" style="padding: 0.25rem 0.5rem; background: #3b82f6; color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">Edit</button>
                                    <button onclick="CLAWSApp.deleteTask(1)" style="padding: 0.25rem 0.5rem; background: #ef4444; color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">Delete</button>
                                </div>
                            </div>
                            <p style="margin: 0; color: #374151; font-size: 0.875rem;">Fed cats at downtown colony, refilled water stations</p>
                            <div style="margin-top: 0.5rem; padding: 0.25rem 0.5rem; background: #fef3c7; border-radius: 0.25rem; font-size: 0.75rem; color: #92400e;">
                                ⏳ Pending approval by Sarah Johnson
                            </div>
                        </div>
                        
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: #f9fafb;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                <div>
                                    <h5 style="margin: 0; font-weight: 600; color: #1f2937;">Winter Shelter Build <span style="background: #fef3c7; color: #92400e; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">OPPORTUNITY</span></h5>
                                    <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">Completed: Dec 14, 2024 | 3 hours</p>
                                </div>
                                <div style="display: flex; gap: 0.5rem;">
                                    <button onclick="CLAWSApp.editEvent(2)" style="padding: 0.25rem 0.5rem; background: #3b82f6; color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">Edit</button>
                                    <button onclick="CLAWSApp.deleteEvent(2)" style="padding: 0.25rem 0.5rem; background: #ef4444; color: white; border: none; border-radius: 0.25rem; font-size: 0.75rem; cursor: pointer;">Delete</button>
                                </div>
                            </div>
                            <p style="margin: 0; color: #374151; font-size: 0.875rem;">Built insulated shelters for colony cats</p>
                            <div style="margin-top: 0.5rem; padding: 0.25rem 0.5rem; background: #fef3c7; border-radius: 0.25rem; font-size: 0.75rem; color: #92400e;">
                                ⏳ Pending approval by Mike Chen
                            </div>
                        </div>
                    </div>
                `;
                return;
            }
            
            // TODO: Replace with actual API call to load user's pending items
            pendingItemsContainer.innerHTML = '<p style="color: #6b7280; text-align: center; padding: 2rem;">Loading your pending items...</p>';
        },

        /**
         * Load approved items based on selected time period
         */
        loadApprovedItems: function() {
            console.log('Loading approved items...');
            
            const approvedItemsContainer = document.getElementById('claws-approved-items');
            if (!approvedItemsContainer) return;
            
            // Get selected time period
            const timePeriodFilter = document.getElementById('claws-time-period-filter');
            const selectedPeriod = timePeriodFilter ? timePeriodFilter.value : '3months';
            
            if (this.config.demoMode) {
                // Show sample approved items based on time period
                let items = this.getSampleApprovedItems(selectedPeriod);
                
                if (items.length === 0) {
                    approvedItemsContainer.innerHTML = '<p style="color: #6b7280; text-align: center; padding: 2rem;">No approved items for the selected time period.</p>';
                    return;
                }
                
                approvedItemsContainer.innerHTML = `
                    <div style="space-y: 1rem;">
                        ${items.map(item => `
                            <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem; background: white;">
                                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                    <div>
                                        <h5 style="margin: 0; font-weight: 600; color: #1f2937;">
                                            ${item.title} 
                                            <span style="background: ${item.type === 'task' ? '#dbeafe; color: #1e40af' : '#fef3c7; color: #92400e'}; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">
                                                ${item.type.toUpperCase()}
                                            </span>
                                        </h5>
                                        <p style="margin: 0.25rem 0 0 0; color: #6b7280; font-size: 0.875rem;">${item.date} | ${item.hours} hours</p>
                                    </div>
                                    <div style="padding: 0.25rem 0.5rem; background: #dcfce7; color: #166534; border-radius: 0.25rem; font-size: 0.75rem;">
                                        ✅ Approved
                                    </div>
                                </div>
                                <p style="margin: 0; color: #374151; font-size: 0.875rem;">${item.description}</p>
                            </div>
                        `).join('')}
                    </div>
                `;
                return;
            }
            
            // TODO: Replace with actual API call to load user's approved items
            approvedItemsContainer.innerHTML = '<p style="color: #6b7280; text-align: center; padding: 2rem;">Loading your approved items...</p>';
        },

        /**
         * Get sample approved items based on time period
         */
        getSampleApprovedItems: function(period) {
            const allItems = [
                { title: 'TNR Transport', type: 'task', date: 'Dec 12, 2024', hours: '4', description: 'Transported 3 cats to spay/neuter clinic', monthsAgo: 0 },
                { title: 'Educational Outreach', type: 'event', date: 'Dec 8, 2024', hours: '2', description: 'Presented at community center about TNR programs', monthsAgo: 0 },
                { title: 'Colony Maintenance', type: 'task', date: 'Nov 25, 2024', hours: '1.5', description: 'Cleaned and restocked feeding stations', monthsAgo: 1 },
                { title: 'TNR Party', type: 'event', date: 'Nov 15, 2024', hours: '6', description: 'Helped trap 8 cats for spay/neuter', monthsAgo: 1 },
                { title: 'Food Drive', type: 'event', date: 'Oct 30, 2024', hours: '3', description: 'Collected donations at pet store', monthsAgo: 2 },
                { title: 'Colony Census', type: 'task', date: 'Sep 20, 2024', hours: '2', description: 'Counted and photographed colony cats', monthsAgo: 3 },
                { title: 'Kitten Transport', type: 'task', date: 'Aug 15, 2024', hours: '2.5', description: 'Transported kittens to foster homes', monthsAgo: 4 },
                { title: 'Trap Repair', type: 'task', date: 'Jul 10, 2024', hours: '1', description: 'Fixed damaged traps', monthsAgo: 5 },
                { title: 'Adoption Event', type: 'event', date: 'Jun 1, 2024', hours: '4', description: 'Helped at weekend adoption event', monthsAgo: 6 },
                { title: 'Shelter Build', type: 'event', date: 'Jan 15, 2024', hours: '5', description: 'Built winter shelters for colonies', monthsAgo: 11 }
            ];
            
            let maxMonths;
            switch(period) {
                case '3months': maxMonths = 3; break;
                case '6months': maxMonths = 6; break;
                case '1year': maxMonths = 12; break;
                case 'alltime': maxMonths = Infinity; break;
                default: maxMonths = 3;
            }
            
            return allItems.filter(item => item.monthsAgo < maxMonths);
        },

        /**
         * Filter approved items when time period changes
         */
        filterApprovedItems: function() {
            console.log('Filtering approved items...');
            this.loadApprovedItems();
        },

        /**
         * Filter admin approved items by time period
         */
        filterAdminApprovedItems: function(timePeriod) {
            console.log('Filtering admin approved items for:', timePeriod);
            
            // TODO: Replace with actual API call to filter approved items by time period
            const approvedTasksList = document.getElementById('approved-tasks-list');
            if (!approvedTasksList) return;
            
            // Show loading state
            approvedTasksList.innerHTML = `
                <div style="text-align: center; padding: 2rem; color: #6b7280;">
                    <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">⏳</div>
                    <p style="margin: 0; font-size: 0.875rem;">Loading ${timePeriod === 'all' ? 'all' : timePeriod} data...</p>
                </div>
            `;
            
            // Simulate API call with timeout
            setTimeout(() => {
                approvedTasksList.innerHTML = `
                    <div style="text-align: center; padding: 2rem; color: #6b7280;">
                        <div style="font-size: 2rem; margin-bottom: 0.5rem;">📋</div>
                        <p style="margin: 0; font-weight: 500; color: #374151;">No approved items found</p>
                        <p style="margin: 0.5rem 0 0; font-size: 0.875rem;">
                            ${timePeriod === 'all' ? 'No tasks or events have been approved yet.' : 
                              `No tasks or events approved in the last ${timePeriod.replace('months', ' months').replace('year', ' year')}.`}
                        </p>
                    </div>
                `;
            }, 1000);
        },

        /**
         * Edit a completed task (only if not approved)
         */
        editTask: function(taskId) {
            console.log('Editing task:', taskId);
            // TODO: Implement task editing functionality
            this.showAlert('Task editing functionality coming soon!', 'info');
        },

        /**
         * Delete a completed task (only if not approved)
         */
        deleteTask: function(taskId) {
            console.log('Deleting task:', taskId);
            if (confirm('Are you sure you want to delete this task? This action cannot be undone.')) {
                // TODO: Implement task deletion functionality
                this.showAlert('Task deletion functionality coming soon!', 'info');
                // Refresh the pending items view
                this.loadPendingItems();
            }
        },

        /**
         * Edit a completed event (only if not approved)
         */
        editEvent: function(eventId) {
            console.log('Editing event:', eventId);
            // TODO: Implement event editing functionality
            this.showAlert('Event editing functionality coming soon!', 'info');
        },

        /**
         * Delete a completed event (only if not approved)
         */
        deleteEvent: function(eventId) {
            console.log('Deleting event:', eventId);
            if (confirm('Are you sure you want to delete this event completion? This action cannot be undone.')) {
                // TODO: Implement event deletion functionality
                this.showAlert('Event deletion functionality coming soon!', 'info');
                // Refresh the pending items view
                this.loadPendingItems();
            }
        },

        /**
         * Get gradient style based on color scheme type - now uses master colors
         */
        getGradientStyle: function() {
            const masterColors = this.getMasterColors();
            if (clawsData.colorSchemeType === 'solid') {
                return masterColors.primary;
            } else {
                return `linear-gradient(to right, ${masterColors.primary}, ${masterColors.secondary})`;
            }
        },

        /**
         * Apply color scheme - simplified for master header inheritance system
         */
        applyColorScheme: function() {
            return;
        },


        /**
         * Update chart colors to complement color scheme
         */
        updateChartColors: function() {
            // COMPLETELY DISABLED - do nothing to prevent infinite loops
            return;
        },

        /**
         * Generate Roy G. Biv color palette for charts with cycling shades
         * Returns colors independent of user's chosen header colors
         * SAFE VERSION - no function calls, static return only
         */
        generateChartColorPalette: function() {
            // COMPLETELY DISABLED - return empty array to prevent infinite loops
            return [];
        },

        /**
         * Convert hex color to RGB
         */
        hexToRgb: function(hex) {
            const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
            return result ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16)
            } : null;
        },


        /**
         * Lighten a color by percentage
         */
        lightenColor: function(hex, percent) {
            const rgb = this.hexToRgb(hex);
            if (!rgb) return hex;
            
            const r = Math.min(255, Math.round(rgb.r + (255 - rgb.r) * percent / 100));
            const g = Math.min(255, Math.round(rgb.g + (255 - rgb.g) * percent / 100));
            const b = Math.min(255, Math.round(rgb.b + (255 - rgb.b) * percent / 100));
            
            return `rgb(${r}, ${g}, ${b})`;
        },

        // REMOVED: forceColorUpdate function - was unnecessary and causing external dependency issues

        /**
         * Helper functions for stats and goals
         */
        
        /**
         * Get timeframe label
         */
        getTimeframeLabel: function(timeframe) {
            const labels = {
                '3months': 'Last 3 months',
                '6months': 'Last 6 months',
                '1year': 'Last 1 year',
                'lifetime': 'Lifetime'
            };
            return labels[timeframe] || 'Last 3 months';
        },

        /**
         * Generate trend bars for charts
         */
        generateTrendBars: function() {
            const monthlyData = [320, 285, 412, 356, 445, 398]; // Sample data
            const maxValue = Math.max(...monthlyData);
            
            return monthlyData.map((value, index) => {
                const height = (value / maxValue) * 100;
                const months = ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'];
                return `
                    <div style="flex: 1; text-align: center;">
                        <div style="background: linear-gradient(to top, #3b82f6, #1d4ed8); height: ${height}%; min-height: 8px; border-radius: 2px 2px 0 0; margin-bottom: 0.5rem;" title="${months[index]}: ${value} hours"></div>
                        <span style="font-size: 0.75rem; color: #6b7280;">${months[index]}</span>
                    </div>
                `;
            }).join('');
        },

        /**
         * Get unified teams based on task/event types
         */
        getUnifiedTeams: function() {
            // Teams are event-based and only exist when there are active events with volunteers
            // TODO: Replace with actual API call to get teams based on current events
            // For now, return empty object since no events exist yet
            return {};
        },

        /**
         * Get team sample data
         */
        getTeamSampleData: function(teamId) {
            const teamData = {
                'teams': {
                    icon: '👥',
                    totalHours: 847,
                    memberCount: 23,
                    tasksCompleted: 156,
                    colors: { primary: '#3b82f6', secondary: '#1d4ed8' },
                    members: [
                        { name: 'Sarah Johnson', hours: 127, tasks: 23 },
                        { name: 'Mike Chen', hours: 98, tasks: 18 },
                        { name: 'Lisa Garcia', hours: 89, tasks: 16 },
                        { name: 'David Wilson', hours: 76, tasks: 14 },
                        { name: 'Emma Davis', hours: 67, tasks: 12 }
                    ],
                    activities: [
                        { name: 'Team Coordination', hours: 285, percentage: 34, color: '#3b82f6' },
                        { name: 'Training', hours: 203, percentage: 24, color: '#10b981' },
                        { name: 'Project Management', hours: 169, percentage: 20, color: '#f59e0b' },
                        { name: 'Cross-team Support', hours: 190, percentage: 22, color: '#8b5cf6' }
                    ]
                },
                'team-colony-care': {
                    icon: '🍽️',
                    totalHours: 512,
                    memberCount: 18,
                    tasksCompleted: 124,
                    colors: { primary: '#10b981', secondary: '#047857' },
                    members: [
                        { name: 'Sarah Johnson', hours: 89, tasks: 16 },
                        { name: 'Mike Chen', hours: 76, tasks: 14 },
                        { name: 'Lisa Garcia', hours: 67, tasks: 12 },
                        { name: 'John Smith', hours: 58, tasks: 11 },
                        { name: 'Amy Brown', hours: 45, tasks: 9 }
                    ],
                    activities: [
                        { name: 'Colony Feeding', hours: 245, percentage: 48, color: '#10b981' },
                        { name: 'Shelter Building', hours: 156, percentage: 30, color: '#f59e0b' },
                        { name: 'Safety Improvements', hours: 67, percentage: 13, color: '#8b5cf6' },
                        { name: 'Monitoring & Setup', hours: 44, percentage: 9, color: '#3b82f6' }
                    ]
                },
                'team-tnr': {
                    icon: '🐱',
                    totalHours: 298,
                    memberCount: 12,
                    tasksCompleted: 67,
                    colors: { primary: '#8b5cf6', secondary: '#7c3aed' },
                    members: [
                        { name: 'Jennifer Lee', hours: 78, tasks: 18 },
                        { name: 'Robert Brown', hours: 65, tasks: 15 },
                        { name: 'Amanda Miller', hours: 56, tasks: 12 },
                        { name: 'Steven Davis', hours: 45, tasks: 11 },
                        { name: 'Maria Garcia', hours: 54, tasks: 11 }
                    ],
                    activities: [
                        { name: 'TNR Parties', hours: 178, percentage: 60, color: '#8b5cf6' },
                        { name: 'Animal Transport', hours: 74, percentage: 25, color: '#3b82f6' },
                        { name: 'Recovery Care', hours: 46, percentage: 15, color: '#10b981' }
                    ]
                },
                'team-education': {
                    icon: '📚',
                    totalHours: 356,
                    memberCount: 15,
                    tasksCompleted: 89,
                    colors: { primary: '#f59e0b', secondary: '#d97706' },
                    members: [
                        { name: 'David Wilson', hours: 89, tasks: 19 },
                        { name: 'Emma Davis', hours: 76, tasks: 16 },
                        { name: 'Mark Johnson', hours: 67, tasks: 14 },
                        { name: 'Rachel Lee', hours: 59, tasks: 12 },
                        { name: 'Tom Brown', hours: 65, tasks: 28 }
                    ],
                    activities: [
                        { name: 'Education & Training', hours: 156, percentage: 44, color: '#f59e0b' },
                        { name: 'Community Outreach', hours: 123, percentage: 35, color: '#3b82f6' },
                        { name: 'Public Speaking', hours: 77, percentage: 21, color: '#10b981' }
                    ]
                },
                'team-administrative': {
                    icon: '📋',
                    totalHours: 234,
                    memberCount: 8,
                    tasksCompleted: 156,
                    colors: { primary: '#ef4444', secondary: '#dc2626' },
                    members: [
                        { name: 'Admin User', hours: 89, tasks: 45 },
                        { name: 'Coordinator A', hours: 67, tasks: 38 },
                        { name: 'Coordinator B', hours: 44, tasks: 29 },
                        { name: 'Sarah Admin', hours: 34, tasks: 44 }
                    ],
                    activities: [
                        { name: 'Administrative Work', hours: 98, percentage: 42, color: '#ef4444' },
                        { name: 'Fundraising', hours: 67, percentage: 29, color: '#f59e0b' },
                        { name: 'Event Support', hours: 45, percentage: 19, color: '#8b5cf6' },
                        { name: 'Social Media', hours: 24, percentage: 10, color: '#3b82f6' }
                    ]
                },
                'team-animal-care': {
                    icon: '❤️',
                    totalHours: 289,
                    memberCount: 10,
                    tasksCompleted: 67,
                    colors: { primary: '#ec4899', secondary: '#db2777' },
                    members: [
                        { name: 'Foster Mom 1', hours: 89, tasks: 12 },
                        { name: 'Transport Vol 1', hours: 76, tasks: 15 },
                        { name: 'Medical Helper', hours: 67, tasks: 14 },
                        { name: 'Foster Dad 1', hours: 57, tasks: 26 }
                    ],
                    activities: [
                        { name: 'Foster Care', hours: 167, percentage: 58, color: '#ec4899' },
                        { name: 'Animal Transport', hours: 78, percentage: 27, color: '#3b82f6' },
                        { name: 'Medical Support', hours: 44, percentage: 15, color: '#10b981' }
                    ]
                },
                'team-facilities': {
                    icon: '🔧',
                    totalHours: 156,
                    memberCount: 6,
                    tasksCompleted: 34,
                    colors: { primary: '#6b7280', secondary: '#4b5563' },
                    members: [
                        { name: 'Handyman 1', hours: 67, tasks: 12 },
                        { name: 'Supply Manager', hours: 45, tasks: 8 },
                        { name: 'Maintenance Vol', hours: 44, tasks: 14 }
                    ],
                    activities: [
                        { name: 'Equipment Maintenance', hours: 89, percentage: 57, color: '#6b7280' },
                        { name: 'Supply Management', hours: 67, percentage: 43, color: '#8b5cf6' }
                    ]
                }
            };
            
            return teamData[teamId] || teamData['teams'];
        },

        /**
         * Get volunteer sample data
         */
        getVolunteerSampleData: function(volunteerId) {
            const volunteerData = {
                'current-user': {
                    totalHours: 127,
                    tasksCompleted: 23,
                    eventsJoined: 12,
                    avgHoursPerWeek: 8.2,
                    activities: [
                        { name: 'Feeding', hours: 67, percentage: 53, color: '#10b981' },
                        { name: 'Shelter Builds', hours: 32, percentage: 25, color: '#f59e0b' },
                        { name: 'Education', hours: 19, percentage: 15, color: '#8b5cf6' },
                        { name: 'Administration', hours: 9, percentage: 7, color: '#ef4444' }
                    ],
                    achievements: [
                        { icon: '🏆', title: '100 Hours Milestone', date: 'Dec 15, 2024' },
                        { icon: '⭐', title: 'Team Leader', date: 'Nov 28, 2024' },
                        { icon: '🎯', title: 'Perfect Attendance', date: 'Nov 15, 2024' },
                        { icon: '👥', title: 'Mentor Badge', date: 'Oct 30, 2024' }
                    ],
                    weeklyHours: [12, 8, 15, 6, 11, 9, 14, 8, 10, 13, 7, 12]
                },
                'volunteer-sarah': {
                    totalHours: 127,
                    tasksCompleted: 23,
                    eventsJoined: 15,
                    avgHoursPerWeek: 9.8,
                    activities: [
                        { name: 'Feeding', hours: 89, percentage: 70, color: '#10b981' },
                        { name: 'Training', hours: 25, percentage: 20, color: '#3b82f6' },
                        { name: 'Administration', hours: 13, percentage: 10, color: '#ef4444' }
                    ],
                    achievements: [
                        { icon: '🥇', title: 'Top Performer', date: 'Dec 20, 2024' },
                        { icon: '🏆', title: '125 Hours Milestone', date: 'Dec 10, 2024' },
                        { icon: '👑', title: 'Team Captain', date: 'Nov 20, 2024' },
                        { icon: '⭐', title: 'Excellence Award', date: 'Nov 5, 2024' }
                    ],
                    weeklyHours: [15, 12, 18, 8, 14, 11, 16, 10, 13, 15, 9, 14]
                },
                'volunteer-mike': {
                    totalHours: 98,
                    tasksCompleted: 18,
                    eventsJoined: 10,
                    avgHoursPerWeek: 7.5,
                    activities: [
                        { name: 'Feeding', hours: 76, percentage: 78, color: '#10b981' },
                        { name: 'Shelter Builds', hours: 15, percentage: 15, color: '#f59e0b' },
                        { name: 'Education', hours: 7, percentage: 7, color: '#8b5cf6' }
                    ],
                    achievements: [
                        { icon: '🎯', title: 'Reliability Award', date: 'Dec 1, 2024' },
                        { icon: '🏆', title: '75 Hours Milestone', date: 'Nov 18, 2024' },
                        { icon: '⭐', title: 'Dedication Badge', date: 'Oct 25, 2024' }
                    ],
                    weeklyHours: [10, 7, 12, 5, 9, 8, 11, 6, 8, 10, 6, 9]
                },
                'volunteer-lisa': {
                    totalHours: 89,
                    tasksCompleted: 16,
                    eventsJoined: 8,
                    avgHoursPerWeek: 6.8,
                    activities: [
                        { name: 'Feeding', hours: 67, percentage: 75, color: '#10b981' },
                        { name: 'Administration', hours: 13, percentage: 15, color: '#ef4444' },
                        { name: 'Education', hours: 9, percentage: 10, color: '#8b5cf6' }
                    ],
                    achievements: [
                        { icon: '🏆', title: 'Team Player', date: 'Nov 30, 2024' },
                        { icon: '⭐', title: 'Consistent Volunteer', date: 'Nov 10, 2024' },
                        { icon: '👥', title: 'Helper Badge', date: 'Oct 15, 2024' }
                    ],
                    weeklyHours: [8, 6, 10, 4, 7, 6, 9, 5, 7, 8, 5, 7]
                },
                'volunteer-david': {
                    totalHours: 112,
                    tasksCompleted: 15,
                    eventsJoined: 7,
                    avgHoursPerWeek: 8.6,
                    activities: [
                        { name: 'Shelter Builds', hours: 89, percentage: 79, color: '#f59e0b' },
                        { name: 'Training', hours: 15, percentage: 13, color: '#3b82f6' },
                        { name: 'Administration', hours: 8, percentage: 8, color: '#ef4444' }
                    ],
                    achievements: [
                        { icon: '🔨', title: 'Master Builder', date: 'Dec 5, 2024' },
                        { icon: '🏆', title: '100 Hours Milestone', date: 'Nov 25, 2024' },
                        { icon: '⭐', title: 'Construction Expert', date: 'Oct 20, 2024' }
                    ],
                    weeklyHours: [14, 9, 16, 6, 12, 8, 13, 7, 10, 12, 8, 11]
                },
                'volunteer-emma': {
                    totalHours: 98,
                    tasksCompleted: 13,
                    eventsJoined: 6,
                    avgHoursPerWeek: 7.5,
                    activities: [
                        { name: 'Shelter Builds', hours: 78, percentage: 80, color: '#f59e0b' },
                        { name: 'Education', hours: 12, percentage: 12, color: '#8b5cf6' },
                        { name: 'Feeding', hours: 8, percentage: 8, color: '#10b981' }
                    ],
                    achievements: [
                        { icon: '🏗️', title: 'Construction Helper', date: 'Nov 20, 2024' },
                        { icon: '⭐', title: 'Support Award', date: 'Nov 1, 2024' },
                        { icon: '👷', title: 'Safety First', date: 'Oct 10, 2024' }
                    ],
                    weeklyHours: [11, 7, 13, 5, 9, 7, 12, 6, 8, 10, 6, 9]
                }
            };
            
            return volunteerData[volunteerId] || volunteerData['current-user'];
        },

        /**
         * Get all volunteers summary
         */
        getAllVolunteersSummary: function() {
            return [
                { name: 'Sarah Johnson', team: 'Feeding Team', joinDate: 'March 2024', hours: 127, tasks: 23 },
                { name: 'Mike Chen', team: 'Feeding Team', joinDate: 'April 2024', hours: 98, tasks: 18 },
                { name: 'Lisa Garcia', team: 'Feeding Team', joinDate: 'May 2024', hours: 89, tasks: 16 },
                { name: 'David Wilson', team: 'Shelter Builds', joinDate: 'February 2024', hours: 112, tasks: 15 },
                { name: 'Emma Davis', team: 'Shelter Builds', joinDate: 'June 2024', hours: 98, tasks: 13 },
                { name: 'Jennifer Lee', team: 'Education', joinDate: 'January 2024', hours: 78, tasks: 8 },
                { name: 'Robert Brown', team: 'Education', joinDate: 'April 2024', hours: 65, tasks: 7 },
                { name: 'Amanda Miller', team: 'Education', joinDate: 'May 2024', hours: 56, tasks: 6 },
                { name: 'Admin User', team: 'Administration', joinDate: 'January 2024', hours: 89, tasks: 28 }
            ];
        },
        
        /**
         * Load admin aggregate intake analytics
         */
        loadAdminIntakeAnalytics: async function() {
            try {
                console.log('Loading admin intake analytics from:', this.config.apiUrl + 'admin/intakes/aggregate');
                const response = await fetch(this.config.apiUrl + 'admin/intakes/aggregate', {
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                console.log('Admin intake analytics response status:', response.status);
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('Admin intake analytics data received:', data);
                    this.updateAdminIntakeStatistics(data);
                    this.updateAdminIntakeCharts(data);
                } else {
                    console.error('Failed to load admin intake analytics:', response.status, response.statusText);
                    const errorText = await response.text();
                    console.error('Error response:', errorText);
                }
            } catch (error) {
                console.error('Error loading admin intake analytics:', error);
            }
        },
        
        /**
         * Load admin aggregate discharge analytics
         */
        loadAdminDischargeAnalytics: async function() {
            try {
                const response = await fetch(this.config.apiUrl + 'admin/discharges/aggregate', {
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    this.updateAdminDischargeStatistics(data);
                    this.updateAdminDischargeCharts(data);
                } else {
                    console.error('Failed to load admin discharge analytics:', response.status);
                }
            } catch (error) {
                console.error('Error loading admin discharge analytics:', error);
            }
        },
        
        /**
         * Update admin intake statistics
         */
        updateAdminIntakeStatistics: function(data) {
            const totalElement = document.getElementById('claws-admin-total-intakes');
            const weekElement = document.getElementById('claws-admin-week-intakes');
            const monthElement = document.getElementById('claws-admin-month-intakes');
            
            if (totalElement) totalElement.textContent = data.total || 0;
            if (weekElement) weekElement.textContent = data.this_week || 0;
            if (monthElement) monthElement.textContent = data.this_month || 0;
        },
        
        /**
         * Update admin discharge statistics
         */
        updateAdminDischargeStatistics: function(data) {
            const totalElement = document.getElementById('claws-admin-total-discharges');
            const weekElement = document.getElementById('claws-admin-week-discharges');
            const monthElement = document.getElementById('claws-admin-month-discharges');
            const adoptionsElement = document.getElementById('claws-admin-adoptions');
            
            if (totalElement) totalElement.textContent = data.total || 0;
            if (weekElement) weekElement.textContent = data.this_week || 0;
            if (monthElement) monthElement.textContent = data.this_month || 0;
            if (adoptionsElement) adoptionsElement.textContent = data.adoptions || 0;
        },
        
        /**
         * Update admin intake charts
         */
        updateAdminIntakeCharts: function(data) {
            this.updateAdminIntakeTypeChart(data);
            this.updateAdminIntakeVolunteerChart(data);
        },
        
        /**
         * Update admin discharge charts
         */
        updateAdminDischargeCharts: function(data) {
            this.updateAdminDischargeOutcomeChart(data);
            this.updateAdminDischargeVolunteerChart(data);
        },
        
        /**
         * Update admin intake type chart
         */
        updateAdminIntakeTypeChart: function(data) {
            console.log('Updating admin intake type chart with data:', data);
            const canvas = document.getElementById('claws-admin-intake-type-chart');
            if (!canvas) {
                console.error('Canvas element claws-admin-intake-type-chart not found');
                return;
            }
            
            const ctx = canvas.getContext('2d');
            
            if (this.adminIntakeTypeChart) {
                this.adminIntakeTypeChart.destroy();
            }
            
            const labels = Object.keys(data.type_counts || {});
            const values = Object.values(data.type_counts || {});
            
            console.log('Chart labels:', labels);
            console.log('Chart values:', values);
            
            // Handle empty data
            if (labels.length === 0 || values.every(v => v === 0)) {
                console.log('No data to display, showing empty message');
                // Show "No data" message
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '16px Arial';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No intake data available yet', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            console.log('Creating chart with data');
            
            try {
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js is not loaded!');
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.font = '16px Arial';
                    ctx.fillStyle = '#ef4444';
                    ctx.textAlign = 'center';
                    ctx.fillText('Chart.js library not loaded', canvas.width / 2, canvas.height / 2);
                    return;
                }
                
                this.adminIntakeTypeChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: values,
                            backgroundColor: this.chartColorPalette.slice(0, labels.length)
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
                console.log('Chart created successfully');
            } catch (error) {
                console.error('Error creating chart:', error);
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '16px Arial';
                ctx.fillStyle = '#ef4444';
                ctx.textAlign = 'center';
                ctx.fillText('Error creating chart', canvas.width / 2, canvas.height / 2);
            }
        },
        
        /**
         * Update admin intake volunteer chart
         */
        updateAdminIntakeVolunteerChart: function(data) {
            const canvas = document.getElementById('claws-admin-intake-volunteer-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            if (this.adminIntakeVolunteerChart) {
                this.adminIntakeVolunteerChart.destroy();
            }
            
            const labels = Object.keys(data.volunteer_counts || {});
            const values = Object.values(data.volunteer_counts || {});
            
            // Handle empty data
            if (labels.length === 0 || values.every(v => v === 0)) {
                // Show "No data" message
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '16px Arial';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No intake data available yet', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.adminIntakeVolunteerChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Intakes',
                        data: values,
                        backgroundColor: this.chartColorPalette.slice(0, labels.length)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        },
        
        /**
         * Update admin discharge outcome chart
         */
        updateAdminDischargeOutcomeChart: function(data) {
            const canvas = document.getElementById('claws-admin-discharge-outcome-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            if (this.adminDischargeOutcomeChart) {
                this.adminDischargeOutcomeChart.destroy();
            }
            
            const labels = Object.keys(data.outcome_counts || {});
            const values = Object.values(data.outcome_counts || {});
            
            this.adminDischargeOutcomeChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: this.chartColorPalette.slice(0, labels.length)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        },
        
        /**
         * Update admin discharge volunteer chart
         */
        updateAdminDischargeVolunteerChart: function(data) {
            const canvas = document.getElementById('claws-admin-discharge-volunteer-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            if (this.adminDischargeVolunteerChart) {
                this.adminDischargeVolunteerChart.destroy();
            }
            
            const labels = Object.keys(data.volunteer_counts || {});
            const values = Object.values(data.volunteer_counts || {});
            
            this.adminDischargeVolunteerChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Discharges',
                        data: values,
                        backgroundColor: this.chartColorPalette.slice(0, labels.length)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        },
        
        /**
         * Get sample needs attention items for demo mode
         */
        getSampleNeedsAttentionItems: function() {
            return [
                {
                    id: 1001,
                    type: 'Colony Feeding',
                    category: 'TASK',
                    date: 'Dec 10, 2024',
                    hours: '2.5',
                    colony: 'Downtown Colony',
                    description: 'Fed the colony cats and refilled water stations. Also noticed one cat seemed lethargic.',
                    coordinatorNotes: 'Please provide more details about the lethargic cat. What time of day was this? Did you take any photos? We may need to schedule a vet check.'
                },
                {
                    id: 1002,
                    type: 'Winter Shelter Building',
                    category: 'TASK',
                    date: 'Dec 8, 2024',
                    hours: '4.0',
                    description: 'Built and installed 3 winter shelters behind the warehouse.',
                    coordinatorNotes: 'Great work! However, we need the exact address where these were installed for our records. Please provide the street address in an updated submission.'
                }
            ];
        }
    };

    // Make CLAWSApp globally accessible for debugging
    window.CLAWSApp = CLAWSApp;

    // TEST: Verify updated JavaScript is loading
    console.log('CLAWS JavaScript file updated - Version: 2.0.2 - Colony-Quick-Actions-Fixed');
    console.log('Current clawsData at load:', typeof clawsData !== 'undefined' ? clawsData : 'undefined');

    // Initialize when DOM is loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, initializing CLAWSApp...');
            CLAWSApp.initialize();
        });
    } else {
        console.log('DOM already ready, initializing CLAWSApp...');
        CLAWSApp.initialize();
    }

})(jQuery || window.jQuery || function() {
    // Fallback if jQuery is not available
    console.warn('jQuery not available, some features may not work properly');
    return {
        ready: function(fn) { 
            if (document.readyState !== 'loading') fn(); 
            else document.addEventListener('DOMContentLoaded', fn); 
        }
    };
});