/**
 * CLAWS UI Module
 * Handles tab switching, alerts, modal management, and general UI interactions
 */

(function() {
    'use strict';

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

        /**
         * Switch between app tabs
         */
        switchTab: function(tabName) {
            // Check if trying to access volunteers without proper plan
            if (tabName === 'volunteers') {
                const volunteerTab = document.getElementById('claws-tab-volunteers');
                const volunteerSection = document.getElementById('claws-volunteers-section');
                
                // If volunteer tab doesn't exist or section doesn't exist, user doesn't have access
                if (!volunteerTab || !volunteerSection) {
                    // Show upgrade prompt instead
                    const upgradePrompt = document.getElementById('claws-volunteers-upgrade-prompt');
                    if (upgradePrompt) {
                        // Hide all sections
                        document.querySelectorAll('.claws-content-section').forEach(section => {
                            section.classList.add('claws-section-hidden');
                        });
                        // Show upgrade prompt
                        upgradePrompt.classList.remove('claws-section-hidden');
                    } else {
                        // Fallback: show alert and redirect
                        alert('Volunteer features are available in the Deluxe plan. Upgrade to unlock this feature!');
                    }
                    return; // Don't proceed with tab switch
                }
            }
            
            // 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 the selected section
            const targetSection = document.getElementById(`claws-${tabName}-section`);
            if (targetSection) {
                targetSection.classList.remove('claws-section-hidden');
            }
            
            // Update current tab
            this.currentTab = tabName;
            
            // Track feature usage
            this.trackFeatureUsage(`tab_${tabName}`, 'viewed');
            
            // Load tab-specific content
            this.loadTabContent(tabName);
        },

        /**
         * Load content for specific tab
         */
        loadTabContent: function(tabName) {
            switch(tabName) {
                case 'colony':
                    this.initColonyTracker();
                    break;
                case 'intake':
                    this.initIntakeTab();
                    break;
                case 'discharge':
                    this.loadDischargeRecords();
                    break;
                case 'neonate':
                    if (clawsData.userRoles && !clawsData.userRoles.includes('subscriber')) {
                        this.initNeonateTracker();
                    }
                    break;
                case 'volunteer':
                    if (clawsData.userRoles && 
                        (clawsData.userRoles.includes('contributor') || 
                         clawsData.userRoles.includes('author') || 
                         clawsData.userRoles.includes('administrator'))) {
                        this.loadVolunteerContent();
                    }
                    break;
            }
        },

        /**
         * 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: 20px;
                right: 20px;
                background: white;
                color: ${colors[type] || CLAWS_CONSTANTS.COLORS.INFO};
                padding: 1rem 1.5rem;
                border-radius: 0.5rem;
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
                border-left: 4px solid ${colors[type] || CLAWS_CONSTANTS.COLORS.INFO};
                z-index: 10000;
                max-width: 400px;
                font-size: 0.875rem;
                line-height: 1.5;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.3s ease-in-out;
            `;
            
            alertDiv.innerHTML = `
                <div style="display: flex; align-items: flex-start; gap: 0.75rem;">
                    <div style="flex: 1;">${message}</div>
                    <button onclick="this.parentElement.parentElement.remove()" style="background: none; border: none; font-size: 1.25rem; cursor: pointer; color: ${CLAWS_CONSTANTS.COLORS.GRAY_600}; padding: 0; line-height: 1;">×</button>
                </div>
            `;
            
            document.body.appendChild(alertDiv);
            
            // Trigger animation
            setTimeout(() => {
                alertDiv.style.opacity = '1';
                alertDiv.style.transform = 'translateX(0)';
            }, 10);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentElement) {
                    alertDiv.style.opacity = '0';
                    alertDiv.style.transform = 'translateX(100%)';
                    setTimeout(() => {
                        if (alertDiv.parentElement) {
                            alertDiv.remove();
                        }
                    }, 300);
                }
            }, 5000);
        },

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

        /**
         * Switch volunteer sub-tabs (restored from backup)
         */
        switchVolunteerSubTab: function(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 volunteer sub-tab 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 (restored from backup)
         */
        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 (restored from backup)
         */
        loadVolunteerMyTime: function() {
            this.loadNeedsAttentionItems();
            this.loadPendingItems();
            this.loadApprovedItems();
        },

        /**
         * Show completed task form (restored from backup - uses existing modal)
         */
        showCompletedTaskForm: function() {
            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();
            
            // Load user's events and projects for linkage
            this.loadUserEventsProjects();
            
            // Set default date to today
            const dateField = document.getElementById('claws-task-date');
            if (dateField) {
                dateField.value = new Date().toISOString().split('T')[0];
            }
            
            // Setup time calculation
            this.setupTimeCalculation();
            
            // Setup task type change handler for colony selection
            this.setupTaskTypeChangeHandler();
            
            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';
            }
            
            // Clear editing mode
            this.editingTaskId = null;
            
            // Reset form
            const form = document.getElementById('claws-completed-task-form');
            if (form) {
                form.reset();
            }
            
            // Reset button text
            const submitBtn = document.querySelector('#claws-completed-task-form button[onclick*="saveCompletedTask"]');
            if (submitBtn) {
                submitBtn.textContent = '💾 Submit for Approval';
            }
        },

        /**
         * Save completed task (restored from backup)
         */
        saveCompletedTask: function() {
            console.log('=== SAVE COMPLETED TASK STARTED ===');
            
            const isEditing = !!(this.editingTaskId || window.CLAWSApp.editingTaskId);
            const taskId = this.editingTaskId || window.CLAWSApp.editingTaskId;
            console.log('Mode:', isEditing ? 'EDITING task ' + taskId : 'CREATING new task');
            console.log('this.editingTaskId:', this.editingTaskId);
            console.log('window.CLAWSApp.editingTaskId:', window.CLAWSApp.editingTaskId);
            
            // 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,
                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,
                // Event/Project linkage
                eventId: document.getElementById('claws-task-tied-to-event')?.checked ? 
                    document.getElementById('claws-task-event-id')?.value : null,
                projectId: document.getElementById('claws-task-tied-to-project')?.checked ? 
                    document.getElementById('claws-task-project-id')?.value : null
            };
            
            console.log('Task data collected:', taskData);
            
            // Validate required fields
            if (!taskData.date || !taskData.type || !taskData.description || !taskData.totalHours || !taskData.coordinator) {
                console.error('❌ Validation failed - missing required fields');
                this.showAlert('Please fill in all required fields', 'error');
                return;
            }
            
            console.log('✅ Validation passed');
            
            // Validate colony selection for colony care tasks
            if (this.requiresColonySelection(taskData.type) && !taskData.colony) {
                console.error('❌ Validation failed - colony required for task type:', taskData.type);
                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;
            
            // Close the form
            this.hideCompletedTaskForm();
            
            // Show success message with task details
            let successMessage = isEditing 
                ? `Task "${typeLabel}" updated and re-submitted for approval!`
                : `Task "${typeLabel}" submitted for approval!`;
            
            if (taskData.colony) {
                // Find colony name
                const colony = this.colonies?.find(c => c.id === taskData.colony);
                if (colony) {
                    successMessage = isEditing
                        ? `Task "${typeLabel}" for ${colony.name} updated and re-submitted!`
                        : `Task "${typeLabel}" for ${colony.name} submitted for approval!`;
                }
            }
            
            this.showAlert(successMessage, 'success');
            
            const payload = {
                date: taskData.date,
                task_type: taskData.type,
                colony_id: taskData.colony || null,
                description: taskData.description,
                start_time: taskData.startTime,
                end_time: taskData.endTime,
                hours: parseFloat(taskData.totalHours),
                coordinator_id: parseInt(taskData.coordinator),
                event_id: taskData.eventId ? parseInt(taskData.eventId) : null,
                project_id: taskData.projectId ? parseInt(taskData.projectId) : null,
                approval_status: 'pending' // Always set to pending, even if was rejected
            };
            
            // Determine URL and method based on edit mode
            const url = isEditing 
                ? window.wpApiSettings.root + `claws/v1/volunteer-time/${taskId}`
                : window.wpApiSettings.root + 'claws/v1/volunteer-time';
            const method = isEditing ? 'PUT' : 'POST';
            
            console.log('📤 Sending payload to API:', payload);
            console.log('API endpoint:', url);
            console.log('Method:', method);
            console.log('Current user ID:', window.wpApiSettings.userId);
            
            // Save to backend
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(payload)
            })
            .then(response => {
                console.log('📥 API response received, status:', response.status, response.statusText);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('📥 Task save response data:', data);
                if (data.id || data.success) {
                    // Task saved successfully
                    console.log('✅ Task ' + (isEditing ? 'updated' : 'saved') + ' successfully!');
                    console.log('  - Task ID:', data.id || taskId);
                    console.log('  - Volunteer ID (me):', window.wpApiSettings.userId);
                    console.log('  - Coordinator ID:', taskData.coordinator);
                    console.log('🔄 Calling loadPendingItems to refresh view...');
                    
                    // Clear editing mode
                    this.editingTaskId = null;
                    window.CLAWSApp.editingTaskId = null;
                    
                    // Refresh pending items
                    this.loadPendingItems();
                    console.log('=== SAVE COMPLETED TASK FINISHED ===');
                } else {
                    console.error('❌ Failed to save task - no ID returned:', data);
                    this.showAlert('Task may not have saved properly. Please refresh and check.', 'warning');
                }
            })
            .catch(error => {
                console.error('❌ ERROR saving task:', error);
                console.error('Error stack:', error.stack);
                this.showAlert('Error saving task: ' + error.message, 'error');
            });
        },

        /**
         * Toggle event/project dropdown visibility based on checkboxes
         */
        toggleEventProjectDropdowns: function() {
            const eventCheckbox = document.getElementById('claws-task-tied-to-event');
            const eventSection = document.getElementById('claws-task-event-dropdown-section');
            const projectCheckbox = document.getElementById('claws-task-tied-to-project');
            const projectSection = document.getElementById('claws-task-project-dropdown-section');
            
            if (eventCheckbox && eventSection) {
                eventSection.style.display = eventCheckbox.checked ? 'block' : 'none';
            }
            
            if (projectCheckbox && projectSection) {
                projectSection.style.display = projectCheckbox.checked ? 'block' : 'none';
            }
        },

        /**
         * Load user's events and projects (as lead or volunteer) for task linkage
         */
        loadUserEventsProjects: function() {
            const currentUserId = parseInt(window.wpApiSettings.userId);
            
            // Fetch user's events
            fetch(window.wpApiSettings.root + 'claws/v1/events/available', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(events => {
                // Filter to only events where user is lead or has claimed a spot
                const userEvents = events.filter(event => {
                    // User is lead
                    if (event.lead_id === currentUserId) return true;
                    // User has claimed a spot
                    const spots = event.volunteer_spots || [];
                    return spots.some(spot => spot.volunteer_id === currentUserId);
                });
                
                const eventDropdown = document.getElementById('claws-task-event-id');
                const eventCheckbox = document.getElementById('claws-task-tied-to-event');
                
                if (eventDropdown && eventCheckbox) {
                    // Clear and populate
                    eventDropdown.innerHTML = '<option value="">Select event...</option>';
                    userEvents.forEach(event => {
                        const option = document.createElement('option');
                        option.value = event.id;
                        option.textContent = event.name + ' - ' + event.date;
                        eventDropdown.appendChild(option);
                    });
                    
                    // Enable/disable checkbox
                    if (userEvents.length === 0) {
                        eventCheckbox.disabled = true;
                        eventCheckbox.style.cursor = 'not-allowed';
                        eventCheckbox.style.opacity = '0.5';
                    } else {
                        eventCheckbox.disabled = false;
                        eventCheckbox.style.cursor = 'pointer';
                        eventCheckbox.style.opacity = '1';
                    }
                }
            })
            .catch(error => console.error('Error loading user events:', error));
            
            // Fetch user's projects
            fetch(window.wpApiSettings.root + 'claws/v1/projects/available', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(projects => {
                // Filter to only projects where user is lead or has claimed a spot
                const userProjects = projects.filter(project => {
                    // User is lead
                    if (project.lead_id === currentUserId) return true;
                    // User has claimed a spot
                    const spots = project.volunteer_spots || [];
                    return spots.some(spot => spot.volunteer_id === currentUserId);
                });
                
                const projectDropdown = document.getElementById('claws-task-project-id');
                const projectCheckbox = document.getElementById('claws-task-tied-to-project');
                
                if (projectDropdown && projectCheckbox) {
                    // Clear and populate
                    projectDropdown.innerHTML = '<option value="">Select project...</option>';
                    userProjects.forEach(project => {
                        const option = document.createElement('option');
                        option.value = project.id;
                        option.textContent = project.name;
                        projectDropdown.appendChild(option);
                    });
                    
                    // Enable/disable checkbox
                    if (userProjects.length === 0) {
                        projectCheckbox.disabled = true;
                        projectCheckbox.style.cursor = 'not-allowed';
                        projectCheckbox.style.opacity = '0.5';
                    } else {
                        projectCheckbox.disabled = false;
                        projectCheckbox.style.cursor = 'pointer';
                        projectCheckbox.style.opacity = '1';
                    }
                }
            })
            .catch(error => console.error('Error loading user projects:', error));
        },

        /**
         * Setup time calculation between start/end times
         */
        setupTimeCalculation: function() {
            const startTimeField = document.getElementById('claws-task-start-time');
            const endTimeField = document.getElementById('claws-task-end-time');
            const totalHoursField = document.getElementById('claws-task-total-hours');
            
            if (startTimeField && endTimeField && totalHoursField) {
                const calculateHours = () => {
                    const startTime = startTimeField.value;
                    const endTime = endTimeField.value;
                    
                    if (startTime && endTime) {
                        const start = new Date(`2000-01-01 ${startTime}`);
                        const end = new Date(`2000-01-01 ${endTime}`);
                        
                        if (end > start) {
                            const diff = (end - start) / (1000 * 60 * 60); // Convert to hours
                            // Round to nearest 0.25 (15 minutes)
                            const rounded = Math.round(diff * 4) / 4;
                            totalHoursField.value = rounded.toFixed(2);
                        } else {
                            totalHoursField.value = '';
                        }
                    }
                };
                
                // Add listeners - simple approach
                startTimeField.addEventListener('change', calculateHours);
                startTimeField.addEventListener('input', calculateHours);
                endTimeField.addEventListener('change', calculateHours);
                endTimeField.addEventListener('input', calculateHours);
            }
        },

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

        /**
         * Load coordinators (editors and administrators) for dropdown
         */
        loadCoordinators: function() {
            const coordinatorDropdown = document.getElementById('claws-task-coordinator');
            if (!coordinatorDropdown) return;
            
            // Show loading state
            coordinatorDropdown.innerHTML = '<option value="">Loading coordinators...</option>';
            
            // Fetch coordinators from API
            fetch(window.wpApiSettings.root + 'claws/v1/coordinators', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(coordinators => {
                let optionsHtml = '<option value="">Select coordinator...</option>';
                
                if (coordinators && coordinators.length > 0) {
                    coordinators.forEach(coordinator => {
                        optionsHtml += `<option value="${coordinator.id}">${coordinator.name} (${coordinator.role})</option>`;
                    });
                } else {
                    optionsHtml = '<option value="">No coordinators available</option>';
                }
                
                coordinatorDropdown.innerHTML = optionsHtml;
            })
            .catch(error => {
                console.error('Error loading coordinators:', error);
                coordinatorDropdown.innerHTML = '<option value="">Error loading coordinators</option>';
                this.showAlert('Failed to load coordinators. Please refresh the page.', 'error');
            });
        },

        /**
         * Load task types for dropdown
         */
        loadTaskTypes: function() {
            const taskTypeDropdown = document.getElementById('claws-task-type');
            if (taskTypeDropdown) {
                const unifiedTypes = this.getUnifiedTaskEventTypes();
                
                let optionsHtml = '<option value="">Select task type...</option>';
                
                // Group by category for better organization
                Object.entries(unifiedTypes).forEach(([key, label]) => {
                    optionsHtml += `<option value="${key}">${label}</option>`;
                });
                
                taskTypeDropdown.innerHTML = optionsHtml;
            }
        },

        /**
         * Populate colony dropdown for task form
         */
        populateTaskColonyDropdown: function() {
            const colonySelect = document.getElementById('claws-task-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);
                });
            }
        },

        /**
         * Check if task type requires colony selection
         */
        requiresColonySelection: function(taskType) {
            const colonyRequiredTypes = [
                'colony_care_feeding',
                'colony_care_shelter',
                'colony_care_medical',
                'colony_care_maintenance',
                'tnr_trap',
                'tnr_transport',
                'tnr_return'
            ];
            return colonyRequiredTypes.includes(taskType);
        },

        /**
         * Get unified task/event types
         */
        getUnifiedTaskEventTypes: function() {
            return {
                // Colony Care types (require colony selection)
                'colony_care_feeding': '🍽️ Colony Care - Feeding',
                'colony_care_shelter': '🏠 Colony Care - Shelter Building/Maintenance',
                'colony_care_medical': '🏥 Colony Care - Medical Care',
                'colony_care_maintenance': '🔧 Colony Care - General Maintenance',
                
                // TNR types (require colony selection)
                'tnr_trap': '🪤 TNR - Trapping',
                'tnr_transport': '🚗 TNR - Transport to/from Vet',
                'tnr_return': '🔄 TNR - Return to Colony',
                
                // Administrative types
                'admin_paperwork': '📋 Administrative - Paperwork',
                'admin_coordination': '📞 Administrative - Coordination',
                'admin_fundraising': '💰 Administrative - Fundraising',
                'admin_grants': '📄 Administrative - Grant Writing',
                
                // Education types
                'education_community': '📚 Education - Community Outreach',
                'education_volunteers': '🎓 Education - Volunteer Training',
                'education_materials': '📖 Education - Material Development',
                
                // Support types
                'support_transport': '🚐 Support - General Transport',
                'support_supplies': '📦 Support - Supply Management',
                'support_events': '🎪 Support - Event Organization'
            };
        },

        /**
         * Approve task (coordinator function)
         */
        approveTask: function() {
            // 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;
            }
            
            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
        },

        /**
         * Mark task as needs attention (coordinator function)
         */
        needsAttentionTask: function() {
            // 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;
            }
            
            this.hideCompletedTaskForm();
            
            // Show success message
            this.showAlert('Task marked as needs attention. The volunteer will be notified.', 'warning');
            
            // TODO: Send to backend 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 volunteer events content
         */
        loadVolunteerEvents: function() {
            // Load volunteers first, then load events and projects
            console.log('Loading volunteers before events/projects...');
            
            // Fetch all volunteers first
            fetch(window.wpApiSettings.root + 'claws/v1/volunteers', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(volunteers => {
                this.allVolunteers = volunteers || [];
                console.log('✅ Volunteers loaded:', this.allVolunteers.length);
                
                // Now load events and projects
                this.loadAvailableEvents();
                this.loadAvailableProjects();
            })
            .catch(error => {
                console.error('Error loading volunteers:', error);
                this.allVolunteers = [];
                // Still try to load events/projects even if volunteers fail
                this.loadAvailableEvents();
                this.loadAvailableProjects();
            });
        },

        /**
         * Show add event form (restored from backup)
         */
        showAddEventForm: function() {
            
            // Reset the form
            this.resetEventForm();
            
            // Auto-populate coordinator information
            this.populateCoordinatorInfo();
            
            // Initialize volunteer spots (default 1)
            this.updateVolunteerSpots();
            
            // Load all volunteers for reservation dropdowns
            this.loadAllVolunteers();
            
            // 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';
            }
            
            // Clear editing mode
            this.editingEventId = null;
            
            // Reset button text
            const submitBtn = document.querySelector('#claws-add-event-modal button[onclick*="saveEvent"]');
            if (submitBtn) {
                submitBtn.textContent = '📅 Create Event';
            }
        },

        /**
         * Show add project form
         */
        showAddProjectForm: function() {
            // Reset the form
            this.resetProjectForm();
            
            // Auto-populate coordinator information
            this.populateProjectCoordinatorInfo();
            
            // Populate project categories with unified types
            this.populateProjectCategoryDropdown();
            
            // Set up category change handler for colony selection
            this.setupProjectCategoryChangeHandler();
            
            // Initialize volunteer spots (default 1)
            this.updateProjectVolunteerSpots();
            
            // Load all volunteers for reservation dropdowns
            this.loadAllVolunteers();
            
            // Show the modal
            const modal = document.getElementById('claws-add-project-modal');
            if (modal) {
                modal.style.display = 'flex';
                // Focus on the first field
                setTimeout(() => {
                    const firstField = document.getElementById('claws-project-name');
                    if (firstField) firstField.focus();
                }, 100);
            }
        },

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

        /**
         * Reset project form
         */
        resetProjectForm: function() {
            const fields = [
                'claws-project-name',
                'claws-project-category', 
                'claws-project-colony',
                'claws-project-coordinator',
                'claws-project-email',
                'claws-project-phone',
                'claws-project-notes',
                'claws-project-num-volunteers',
                // Address fields
                'claws-project-street',
                'claws-project-city',
                'claws-project-state',
                'claws-project-zip'
            ];
            
            fields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.value = '';
                }
            });
            
            // Reset checkbox
            const tnrCheckbox = document.getElementById('claws-project-tnr-not-colony');
            if (tnrCheckbox) tnrCheckbox.checked = false;
            
            // Reset num volunteers to 1
            const numVolunteers = document.getElementById('claws-project-num-volunteers');
            if (numVolunteers) numVolunteers.value = '1';
        },

        /**
         * Populate project coordinator information
         */
        populateProjectCoordinatorInfo: function() {
            const coordinatorField = document.getElementById('claws-project-coordinator');
            const emailField = document.getElementById('claws-project-email');
            const phoneField = document.getElementById('claws-project-phone');
            
            if (coordinatorField && typeof clawsData !== 'undefined') {
                coordinatorField.value = clawsData.currentUser || '';
                emailField.value = clawsData.currentUserEmail || '';
                // Phone would need to be added to clawsData if available
            }
        },

        /**
         * Update project volunteer spots
         */
        updateProjectVolunteerSpots: function() {
            const numVolunteers = parseInt(document.getElementById('claws-project-num-volunteers')?.value || 1);
            const container = document.getElementById('claws-project-volunteer-spots-container');
            
            if (!container) return;
            
            container.innerHTML = '';
            
            for (let i = 1; i <= numVolunteers; i++) {
                const spotDiv = document.createElement('div');
                spotDiv.className = 'volunteer-spot';
                spotDiv.style.cssText = 'margin-bottom: 1rem; padding: 1rem; background: white; border: 1px solid #e5e7eb; border-radius: 0.5rem;';
                
                spotDiv.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                        <h4 style="margin: 0; font-weight: 500; color: #374151; font-size: 0.875rem;">Spot ${i}</h4>
                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; cursor: pointer;">
                            <input type="checkbox" id="reserve-project-spot-${i}" onchange="CLAWSApp.toggleProjectSpotReservation(${i})" style="accent-color: var(--claws-master-bg-primary);" />
                            <span style="font-weight: 500; color: #374151;">Reserve Spot</span>
                        </label>
                    </div>
                    <div id="project-reservation-${i}" style="display: none; margin-top: 0.5rem;">
                        <select id="volunteer-project-spot-${i}" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                            <option value="">Select volunteer...</option>
                        </select>
                    </div>
                `;
                
                container.appendChild(spotDiv);
            }
            
            // Populate volunteer dropdowns
            this.populateProjectVolunteerDropdowns();
        },

        /**
         * Toggle project spot reservation
         */
        toggleProjectSpotReservation: function(spotNumber) {
            const checkbox = document.getElementById(`reserve-project-spot-${spotNumber}`);
            const reservationDiv = document.getElementById(`project-reservation-${spotNumber}`);
            
            if (checkbox && reservationDiv) {
                reservationDiv.style.display = checkbox.checked ? 'block' : 'none';
            }
        },

        /**
         * Populate project volunteer dropdowns
         */
        populateProjectVolunteerDropdowns: function() {
            if (!this.allVolunteers || this.allVolunteers.length === 0) {
                return;
            }
            
            const numVolunteers = parseInt(document.getElementById('claws-project-num-volunteers')?.value || 1);
            
            for (let i = 1; i <= numVolunteers; i++) {
                const dropdown = document.getElementById(`volunteer-project-spot-${i}`);
                if (dropdown) {
                    let optionsHtml = '<option value="">Select volunteer...</option>';
                    
                    this.allVolunteers.forEach(volunteer => {
                        optionsHtml += `<option value="${volunteer.id}">${volunteer.name}</option>`;
                    });
                    
                    dropdown.innerHTML = optionsHtml;
                }
            }
        },

        /**
         * Save project
         */
        saveProject: function() {
            // Get form values
            const projectName = document.getElementById('claws-project-name').value.trim();
            const category = document.getElementById('claws-project-category').value;
            const colony = document.getElementById('claws-project-colony').value;
            
            // Basic validation
            if (!projectName) {
                this.showAlert('Please enter a project name.', 'error');
                return;
            }
            
            if (!category) {
                this.showAlert('Please select a category.', 'error');
                return;
            }
            
            // Validate number of volunteers
            const numVolunteers = parseInt(document.getElementById('claws-project-num-volunteers')?.value || 0);
            if (numVolunteers < 1) {
                this.showAlert('Please specify at least 1 volunteer spot.', 'error');
                return;
            }
            
            // Validate project lead selection
            const leadId = document.getElementById('claws-project-lead')?.value;
            if (!leadId) {
                this.showAlert('Please assign a project lead.', 'error');
                return;
            }
            
            // Collect volunteer spot reservations
            const volunteerSpots = [];
            for (let i = 1; i <= numVolunteers; i++) {
                const reserveCheckbox = document.getElementById(`reserve-project-spot-${i}`);
                const volunteerSelect = document.getElementById(`volunteer-project-spot-${i}`);
                
                if (reserveCheckbox && reserveCheckbox.checked) {
                    const volunteerId = volunteerSelect?.value;
                    if (volunteerId) {
                        volunteerSpots.push({
                            spotNumber: i,
                            volunteerId: volunteerId,
                            reserved: true
                        });
                    }
                } else {
                    volunteerSpots.push({
                        spotNumber: i,
                        volunteerId: null,
                        reserved: false
                    });
                }
            }
            
            // Collect all form data
            const projectData = {
                name: projectName,
                category: category,
                colony: colony,
                type: 'project', // Mark as project (not event)
                date: new Date().toISOString().split('T')[0], // Use current date for projects
                coordinator: document.getElementById('claws-project-coordinator').value.trim(),
                email: document.getElementById('claws-project-email').value.trim(),
                phone: document.getElementById('claws-project-phone').value.trim(),
                notes: document.getElementById('claws-project-notes').value.trim(),
                leadId: parseInt(leadId), // Project lead ID
                
                // Volunteer spots
                numVolunteers: numVolunteers,
                volunteerSpots: volunteerSpots,
                
                // Address fields
                address: {
                    street: document.getElementById('claws-project-street') ? 
                        document.getElementById('claws-project-street').value.trim() : '',
                    city: document.getElementById('claws-project-city') ? 
                        document.getElementById('claws-project-city').value.trim() : '',
                    state: document.getElementById('claws-project-state') ? 
                        document.getElementById('claws-project-state').value.trim() : '',
                    zip: document.getElementById('claws-project-zip') ? 
                        document.getElementById('claws-project-zip').value.trim() : ''
                }
            };
            
            // Save project data to backend (use same events endpoint)
            fetch(window.wpApiSettings.root + 'claws/v1/events', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(projectData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Close the modal
                    this.hideAddProjectForm();
                    
                    // Show success message
                    this.showAlert(`Project "${projectName}" created successfully! Notifications have been sent to volunteers.`, 'success');
                    
                    // Reload projects list
                    this.loadAvailableProjects();
                } else {
                    this.showAlert('Failed to create project. Please try again.', 'error');
                }
            })
            .catch(error => {
                console.error('Error creating project:', error);
                this.showAlert('An error occurred while creating the project.', 'error');
            });
        },

        /**
         * 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 = '';
            }
            
            // Populate event categories with unified types
            this.populateEventCategoryDropdown();
            
            // Set up category change handler for colony selection
            this.setupCategoryChangeHandler();
        },

        /**
         * Populate event category dropdown with unified types (same as task form)
         */
        populateEventCategoryDropdown: function() {
            const categorySelect = document.getElementById('claws-event-category');
            if (!categorySelect) return;
            
            const unifiedTypes = this.getUnifiedTaskEventTypes();
            
            // Clear existing options except first
            categorySelect.innerHTML = '<option value="">Select category...</option>';
            
            // Add all unified types as options
            Object.entries(unifiedTypes).forEach(([key, label]) => {
                const option = document.createElement('option');
                option.value = key;
                option.textContent = label;
                categorySelect.appendChild(option);
            });
        },

        /**
         * 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');
            
            if (categorySelect) {
                categorySelect.addEventListener('change', (e) => {
                    const selectedCategory = e.target.value;
                    
                    // Reset all sections first
                    this.hideAllLocationSections();
                    
                    // Show colony selection for Colony Care and TNR categories
                    if (this.requiresEventColonySelection(selectedCategory)) {
                        colonySection.style.display = 'block';
                        this.populateEventColonyDropdown();
                        this.setupEventColonyChangeHandler();
                        
                        // Show TNR checkbox for TNR categories only
                        if (selectedCategory.startsWith('tnr_')) {
                            tnrNotColonySection.style.display = 'block';
                            this.setupTNRCheckboxHandler();
                        }
                    }
                });
            }
        },

        /**
         * Populate project category dropdown with unified types (same as events)
         */
        populateProjectCategoryDropdown: function() {
            const categorySelect = document.getElementById('claws-project-category');
            if (!categorySelect) return;
            
            const unifiedTypes = this.getUnifiedTaskEventTypes();
            
            // Clear existing options except first
            categorySelect.innerHTML = '<option value="">Select category...</option>';
            
            // Add all unified types as options
            Object.entries(unifiedTypes).forEach(([key, label]) => {
                const option = document.createElement('option');
                option.value = key;
                option.textContent = label;
                categorySelect.appendChild(option);
            });
        },

        /**
         * Set up category change handler for projects to show/hide colony selection
         */
        setupProjectCategoryChangeHandler: function() {
            const categorySelect = document.getElementById('claws-project-category');
            const colonySection = document.getElementById('claws-project-colony-section');
            
            if (categorySelect) {
                categorySelect.addEventListener('change', (e) => {
                    const selectedCategory = e.target.value;
                    
                    // Show colony selection for Colony Care and TNR categories
                    if (this.requiresEventColonySelection(selectedCategory)) {
                        colonySection.style.display = 'block';
                        this.populateProjectColonyDropdown();
                    } else {
                        colonySection.style.display = 'none';
                    }
                });
            }
        },

        /**
         * Populate colony dropdown for projects
         */
        populateProjectColonyDropdown: function() {
            const colonySelect = document.getElementById('claws-project-colony');
            if (!colonySelect || !this.colonies) return;
            
            colonySelect.innerHTML = '<option value="">Select colony...</option>';
            
            this.colonies.forEach(colony => {
                const option = document.createElement('option');
                option.value = colony.id;
                option.textContent = colony.name;
                colonySelect.appendChild(option);
            });
        },

        /**
         * Check if event category requires colony selection
         */
        requiresEventColonySelection: function(category) {
            // Colony Care and TNR types require colony selection
            const colonyRequiredTypes = [
                'colony_care_feeding',
                'colony_care_shelter',
                'colony_care_medical',
                'colony_care_maintenance',
                'tnr_trap',
                'tnr_transport',
                'tnr_return'
            ];
            return colonyRequiredTypes.includes(category);
        },

        /**
         * Populate colony dropdown for events
         */
        populateEventColonyDropdown: 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);
            }
        },

        /**
         * Setup colony change handler for events
         */
        setupEventColonyChangeHandler: function() {
            const colonySelect = document.getElementById('claws-event-colony');
            const addressSection = document.getElementById('claws-event-address-section');
            
            if (colonySelect && addressSection) {
                colonySelect.addEventListener('change', (e) => {
                    const selectedColony = e.target.value;
                    if (selectedColony) {
                        // Show address section when a colony is selected
                        addressSection.style.display = 'block';
                        // Pre-populate with colony address if available
                        const colony = this.colonies?.find(c => c.id === selectedColony);
                        if (colony && colony.address) {
                            document.getElementById('claws-event-street').value = colony.address;
                        }
                    }
                });
            }
        },

        /**
         * Setup TNR checkbox 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 && colonySelect && addressSection) {
                tnrCheckbox.addEventListener('change', (e) => {
                    if (e.target.checked) {
                        // TNR not at colony - clear colony selection and show address
                        colonySelect.value = '';
                        addressSection.style.display = 'block';
                        this.clearAddressFields();
                    } else {
                        // TNR at colony - hide address section
                        addressSection.style.display = 'none';
                        this.clearAddressFields();
                    }
                });
            }
        },

        /**
         * Hide all location 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();
        },

        /**
         * 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 = '';
            });
        },

        /**
         * Update volunteer spots based on number selected
         */
        updateVolunteerSpots: function() {
            const numVolunteers = parseInt(document.getElementById('claws-event-num-volunteers')?.value || 1);
            const container = document.getElementById('claws-volunteer-spots-container');
            
            if (!container) return;
            
            container.innerHTML = '';
            
            for (let i = 1; i <= numVolunteers; i++) {
                const spotDiv = document.createElement('div');
                spotDiv.className = 'volunteer-spot';
                spotDiv.style.cssText = 'margin-bottom: 1rem; padding: 1rem; background: white; border: 1px solid #e5e7eb; border-radius: 0.5rem;';
                
                spotDiv.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                        <h4 style="margin: 0; font-weight: 500; color: #374151; font-size: 0.875rem;">Spot ${i}</h4>
                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; cursor: pointer;">
                            <input type="checkbox" id="reserve-spot-${i}" onchange="CLAWSApp.toggleSpotReservation(${i})" style="accent-color: var(--claws-master-bg-primary);" />
                            <span style="font-weight: 500; color: #374151;">Reserve Spot</span>
                        </label>
                    </div>
                    <div id="reservation-${i}" style="display: none; margin-top: 0.5rem;">
                        <select id="volunteer-spot-${i}" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                            <option value="">Select volunteer...</option>
                        </select>
                    </div>
                `;
                
                container.appendChild(spotDiv);
            }
            
            // Populate volunteer dropdowns
            this.populateVolunteerDropdowns();
        },

        /**
         * Toggle spot reservation dropdown
         */
        toggleSpotReservation: function(spotNumber) {
            const checkbox = document.getElementById(`reserve-spot-${spotNumber}`);
            const reservationDiv = document.getElementById(`reservation-${spotNumber}`);
            
            if (checkbox && reservationDiv) {
                reservationDiv.style.display = checkbox.checked ? 'block' : 'none';
            }
        },

        /**
         * Load all volunteers for reservation dropdowns
         */
        loadAllVolunteers: function() {
            // Fetch all users (not just editors/admins - ALL volunteers)
            fetch(window.wpApiSettings.root + 'claws/v1/volunteers', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(volunteers => {
                this.allVolunteers = volunteers || [];
                this.populateVolunteerDropdowns();
            })
            .catch(error => {
                console.error('Error loading volunteers:', error);
                this.allVolunteers = [];
            });
        },

        /**
         * Populate all volunteer dropdown menus (including lead dropdowns)
         */
        populateVolunteerDropdowns: function() {
            if (!this.allVolunteers || this.allVolunteers.length === 0) {
                return;
            }
            
            // SAVE current selections before rebuilding
            const eventLeadDropdown = document.getElementById('claws-event-lead');
            const projectLeadDropdown = document.getElementById('claws-project-lead');
            const savedEventLead = eventLeadDropdown?.value;
            const savedProjectLead = projectLeadDropdown?.value;
            
            // Populate event lead dropdown
            if (eventLeadDropdown) {
                eventLeadDropdown.innerHTML = '<option value="">Select event lead...</option>';
                this.allVolunteers.forEach(vol => {
                    const option = document.createElement('option');
                    option.value = vol.id;
                    option.textContent = vol.name;
                    eventLeadDropdown.appendChild(option);
                });
                // RESTORE saved selection
                if (savedEventLead) {
                    eventLeadDropdown.value = savedEventLead;
                }
            }
            
            // Populate project lead dropdown
            if (projectLeadDropdown) {
                projectLeadDropdown.innerHTML = '<option value="">Select project lead...</option>';
                this.allVolunteers.forEach(vol => {
                    const option = document.createElement('option');
                    option.value = vol.id;
                    option.textContent = vol.name;
                    projectLeadDropdown.appendChild(option);
                });
                // RESTORE saved selection
                if (savedProjectLead) {
                    projectLeadDropdown.value = savedProjectLead;
                }
            }
            
            // Populate volunteer spot reservation dropdowns
            const numVolunteers = parseInt(document.getElementById('claws-event-num-volunteers')?.value || 1);
            
            for (let i = 1; i <= numVolunteers; i++) {
                const dropdown = document.getElementById(`volunteer-spot-${i}`);
                if (dropdown) {
                    let optionsHtml = '<option value="">Select volunteer...</option>';
                    
                    this.allVolunteers.forEach(volunteer => {
                        optionsHtml += `<option value="${volunteer.id}">${volunteer.name}</option>`;
                    });
                    
                    dropdown.innerHTML = optionsHtml;
                }
            }
        },

        /**
         * Save event (restored from backup)
         */
        saveEvent: function() {
            
            // 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 and TNR categories)
            if (this.requiresEventColonySelection(category) && !colony) {
                // For TNR types, check if "Not At Colony" is selected
                const tnrNotColony = document.getElementById('claws-event-tnr-not-colony');
                if (category.startsWith('tnr_') && 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 at colony
                    const errorMsg = category.startsWith('tnr_') ? 
                        '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;
            }
            
            // Get start time to determine if this is an event or project
            const startTime = document.getElementById('claws-event-start-time').value;
            
            // If date is provided but no start time, this is trying to be an EVENT
            // Events REQUIRE start time, projects do not
            if (date && !startTime) {
                this.showAlert('Please enter a start time for this event.', 'error');
                return;
            }
            
            // Validate number of volunteers
            const numVolunteers = parseInt(document.getElementById('claws-event-num-volunteers')?.value || 0);
            if (numVolunteers < 1) {
                this.showAlert('Please specify at least 1 volunteer spot.', 'error');
                return;
            }
            
            // Validate event lead selection
            const leadId = document.getElementById('claws-event-lead')?.value;
            if (!leadId) {
                this.showAlert('Please assign an event lead.', 'error');
                return;
            }
            
            // Collect volunteer spot reservations
            const volunteerSpots = [];
            for (let i = 1; i <= numVolunteers; i++) {
                const reserveCheckbox = document.getElementById(`reserve-spot-${i}`);
                const volunteerSelect = document.getElementById(`volunteer-spot-${i}`);
                
                if (reserveCheckbox && reserveCheckbox.checked) {
                    const volunteerId = volunteerSelect?.value;
                    if (volunteerId) {
                        volunteerSpots.push({
                            spotNumber: i,
                            volunteerId: volunteerId,
                            reserved: true
                        });
                    }
                } else {
                    volunteerSpots.push({
                        spotNumber: i,
                        volunteerId: null,
                        reserved: false
                    });
                }
            }
            
            // Collect all form data
            const isProject = !date; // Projects don't have dates
            const eventData = {
                name: eventName,
                type: isProject ? 'project' : 'event', // Add type field
                category: category,
                colony: colony,
                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(),
                leadId: parseInt(leadId), // Event lead ID
                
                // Volunteer spots
                numVolunteers: numVolunteers,
                volunteerSpots: volunteerSpots,
                
                // 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() : ''
                }
            };
            
            const isEditing = !!this.editingEventId;
            const url = isEditing
                ? window.wpApiSettings.root + `claws/v1/events/${this.editingEventId}`
                : window.wpApiSettings.root + 'claws/v1/events';
            const method = isEditing ? 'PUT' : 'POST';
            
            // Save event data to backend
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(eventData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Close the modal
                    this.hideAddEventForm();
                    
                    // Clear editing mode
                    this.editingEventId = null;
                    
                    // Show success message
                    const action = isEditing ? 'updated' : 'created';
                    this.showAlert(`Event "${eventName}" ${action} successfully!`, 'success');
                    
                    // Reload events and projects lists
                    this.loadAvailableEvents();
                    this.loadAvailableProjects();
                } else {
                    this.showAlert('Failed to save event. Please try again.', 'error');
                }
            })
            .catch(error => {
                console.error('Error saving event:', error);
                this.showAlert('An error occurred while saving the event.', 'error');
            });
        },

        loadVolunteerTeams: function() {
            // Load both event teams and project teams
            this.loadEventTeams();
            this.loadProjectTeams();
        },
        
        /**
         * Load event teams
         */
        loadEventTeams: function() {
            console.log('=== LOAD EVENT TEAMS STARTED ===');
            const container = document.getElementById('claws-event-teams-list');
            if (!container) {
                console.log('❌ Event teams container not found');
                return;
            }
            
            console.log('✅ Event teams container found, fetching data...');
            // Fetch active events that user is part of
            fetch(window.wpApiSettings.root + 'claws/v1/teams/events', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => {
                console.log('📥 Event teams API response status:', response.status);
                return response.json();
            })
            .then(teams => {
                console.log('📥 Event teams data received:', teams);
                console.log('   Number of event teams:', teams ? teams.length : 0);
                
                if (!teams || teams.length === 0) {
                    console.log('⚠️ No event teams found, showing empty message');
                    container.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                            <div style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;">📅</div>
                            <p style="font-size: 1rem; color: #6b7280; margin: 0;">No active event teams</p>
                            <p style="font-size: 0.875rem; color: #9ca3af; margin: 0.5rem 0 0;">Sign up for an event to join a team!</p>
                        </div>
                    `;
                    return;
                }
                
                console.log('✅ Rendering', teams.length, 'event teams');
                // Display teams
                let html = '';
                teams.forEach(team => {
                    html += this.renderTeamCard(team, 'event');
                });
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading event teams:', error);
                container.innerHTML = `
                    <div style="text-align: center; padding: 2rem; background: #fef2f2; border-radius: 0.75rem; border: 1px solid #fca5a5;">
                        <p style="color: #991b1b; margin: 0;">Failed to load event teams</p>
                    </div>
                `;
            });
        },
        
        /**
         * Load project teams
         */
        loadProjectTeams: function() {
            console.log('=== LOAD PROJECT TEAMS STARTED ===');
            const container = document.getElementById('claws-project-teams-list');
            if (!container) {
                console.log('❌ Project teams container not found');
                return;
            }
            
            console.log('✅ Project teams container found, fetching data...');
            // Fetch active projects that user is part of
            fetch(window.wpApiSettings.root + 'claws/v1/teams/projects', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => {
                console.log('📥 Project teams API response status:', response.status);
                return response.json();
            })
            .then(teams => {
                console.log('📥 Project teams data received:', teams);
                console.log('   Number of project teams:', teams ? teams.length : 0);
                
                if (!teams || teams.length === 0) {
                    console.log('⚠️ No project teams found, showing empty message');
                    container.innerHTML = `
                        <div style="text-align: center; padding: 3rem; background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                            <div style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;">🔄</div>
                            <p style="font-size: 1rem; color: #6b7280; margin: 0;">No active project teams</p>
                            <p style="font-size: 0.875rem; color: #9ca3af; margin: 0.5rem 0 0;">Join a project to become part of a team!</p>
                        </div>
                    `;
                    return;
                }
                
                console.log('✅ Rendering', teams.length, 'project teams');
                // Display teams
                let html = '';
                teams.forEach(team => {
                    html += this.renderTeamCard(team, 'project');
                });
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading project teams:', error);
                container.innerHTML = `
                    <div style="text-align: center; padding: 2rem; background: #fef2f2; border-radius: 0.75rem; border: 1px solid #fca5a5;">
                        <p style="color: #991b1b; margin: 0;">Failed to load project teams</p>
                    </div>
                `;
            });
        },
        
        /**
         * Render a team card
         */
        renderTeamCard: function(team, type) {
            const icon = type === 'event' ? '📅' : '🔄';
            const typeLabel = type === 'event' ? 'Event Team' : 'Project Team';
            const typeColor = type === 'event' ? '#3b82f6' : '#8b5cf6';
            
            // Build member list
            let membersHtml = '';
            
            // FIRST: Always show the team lead at the top
            if (team.lead_name) {
                membersHtml += `
                    <div style="display: flex; align-items: center; justify-content: space-between; padding: 0.75rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 0.5rem; margin-bottom: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                        <span style="font-size: 0.9375rem; color: white; font-weight: 600; display: flex; align-items: center; gap: 0.5rem;">
                            <span style="font-size: 1.25rem;">👑</span>
                            ${team.lead_name}
                            <span style="background: rgba(255,255,255,0.3); color: white; padding: 0.125rem 0.5rem; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">Team Lead</span>
                        </span>
                    </div>
                `;
            }
            
            // SECOND: Show volunteer spots
            const totalSpots = team.total_spots || 0;
            const filledSpots = (team.members && team.members.length) || 0;
            
            if (team.members && team.members.length > 0) {
                team.members.forEach(member => {
                    const statusBadge = member.status === 'confirmed' ? 
                        '<span style="background: #10b981; color: white; padding: 0.125rem 0.5rem; border-radius: 0.25rem; font-size: 0.75rem; margin-left: 0.5rem;">Confirmed</span>' :
                        member.status === 'reserved' ?
                        '<span style="background: #f59e0b; color: white; padding: 0.125rem 0.5rem; border-radius: 0.25rem; font-size: 0.75rem; margin-left: 0.5rem;">Reserved</span>' :
                        '';
                    
                    membersHtml += `
                        <div style="display: flex; align-items: center; justify-content: space-between; padding: 0.5rem 0.5rem 0.5rem 1.5rem; background: #f9fafb; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #d1d5db;">
                            <span style="font-size: 0.875rem; color: #374151;">
                                ${member.name}
                                ${statusBadge}
                            </span>
                        </div>
                    `;
                });
            }
            
            // Add "Volunteer Needed" placeholders for empty spots
            const emptySpots = totalSpots - filledSpots;
            for (let i = 0; i < emptySpots; i++) {
                membersHtml += `
                    <div style="display: flex; align-items: center; padding: 0.5rem 0.5rem 0.5rem 1.5rem; background: #fef3c7; border-radius: 0.375rem; margin-bottom: 0.5rem; border: 1px dashed #f59e0b; border-left: 3px solid #f59e0b;">
                        <span style="font-size: 0.875rem; color: #92400e; font-style: italic;">
                            📢 Volunteer Needed
                        </span>
                    </div>
                `;
            }
            
            if (totalSpots === 0) {
                membersHtml = '<p style="color: #9ca3af; font-size: 0.875rem; font-style: italic; margin-left: 1.5rem;">No volunteer spots defined</p>';
            }
            
            // Date info for events
            let dateInfo = '';
            if (type === 'event' && team.event_date) {
                dateInfo = `
                    <div style="display: flex; align-items: center; gap: 0.5rem; color: #6b7280; font-size: 0.875rem; margin-bottom: 0.5rem;">
                        <span>📅</span>
                        <span>${team.event_date}</span>
                        ${team.event_time ? `<span>⏰ ${team.event_time}</span>` : ''}
                    </div>
                `;
            }
            
            return `
                <div style="background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb; padding: 1.5rem; margin-bottom: 1rem;">
                    <div style="display: flex; justify-content: between; align-items: start; margin-bottom: 1rem;">
                        <div style="flex: 1;">
                            <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem;">
                                <span style="font-size: 1.5rem;">${icon}</span>
                                <h5 style="margin: 0; font-size: 1.125rem; font-weight: 600; color: #1f2937;">${team.name}</h5>
                            </div>
                            <span style="display: inline-block; background: ${typeColor}; color: white; padding: 0.25rem 0.75rem; border-radius: 0.375rem; font-size: 0.75rem; font-weight: 500; margin-bottom: 0.75rem;">
                                ${typeLabel}
                            </span>
                        </div>
                    </div>
                    
                    ${dateInfo}
                    
                    ${team.notes ? `
                        <div style="background: #f9fafb; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem;">
                            <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${team.notes}</p>
                        </div>
                    ` : ''}
                    
                    <div style="margin-top: 1rem;">
                        <h6 style="font-weight: 600; font-size: 0.875rem; color: #374151; margin-bottom: 0.75rem;">
                            Team Roster (${filledSpots} of ${totalSpots} volunteer spots filled)
                        </h6>
                        ${membersHtml}
                    </div>
                </div>
            `;
        },

        loadAvailableEvents: function() {
            console.log('=== LOAD AVAILABLE EVENTS STARTED ===');
            const container = document.querySelector('#claws-events-list');
            if (!container) {
                console.log('❌ Events container not found');
                return;
            }
            
            console.log('✅ Events container found, fetching data...');
            container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #9ca3af;">🔍 Loading available events...</p>';
            
            fetch(window.wpApiSettings.root + 'claws/v1/events/available', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => {
                console.log('📥 Events API response status:', response.status);
                return response.json();
            })
            .then(events => {
                console.log('📥 Events data received:', events);
                console.log('   Number of events:', events ? events.length : 0);
                
                if (!events || events.length === 0) {
                    console.log('⚠️ No events found, showing empty message');
                    container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #9ca3af;">No events available at this time.</p>';
                    return;
                }
                
                console.log('✅ Rendering', events.length, 'events');
                const currentUserId = parseInt(window.wpApiSettings.userId);
                
                let html = '<div style="display: grid; gap: 1.5rem; margin-top: 1.5rem;">';
                events.forEach(event => {
                    const eventDate = new Date(event.date).toLocaleDateString('en-US', { 
                        weekday: 'long', 
                        year: 'numeric', 
                        month: 'long', 
                        day: 'numeric' 
                    });
                    
                    // Get team lead info
                    const leadName = this.getVolunteerNameById(event.lead_id) || 'Unknown';
                    
                    // Get volunteer spots
                    const spots = event.volunteer_spots || [];
                    
                    // Build team lead section
                    let teamLeadHtml = `
                        <div style="display: flex; align-items: center; justify-content: space-between; padding: 0.75rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 0.5rem; margin-bottom: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                            <span style="font-size: 0.9375rem; color: white; font-weight: 600; display: flex; align-items: center; gap: 0.5rem;">
                                <span style="font-size: 1.25rem;">👑</span>
                                ${leadName}
                                <span style="background: rgba(255,255,255,0.3); color: white; padding: 0.125rem 0.5rem; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">Event Lead</span>
                            </span>
                        </div>
                    `;
                    
                    // Restructure volunteer spots to be indented
                    let restructuredSpotsHtml = '';
                    spots.forEach((spot, index) => {
                        const spotNum = index + 1;
                        
                        if (spot.volunteer_id && spot.volunteer_id === currentUserId) {
                            // Current user claimed this spot
                            const volunteerName = this.getVolunteerNameById(spot.volunteer_id);
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #dbeafe; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #3b82f6;">
                                    <span style="font-size: 0.875rem; color: #1e40af; font-weight: 600;">
                                        ${volunteerName} (You)
                                    </span>
                                    <button onclick="CLAWSApp.unclaimEventSpot(${event.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#fee2e2'; this.style.borderColor='#fca5a5'" onmouseout="this.style.background='#fef2f2'; this.style.borderColor='#fecaca'">
                                        ❌ Changed My Mind
                                    </button>
                                </div>
                            `;
                        } else if (spot.reserved && spot.volunteer_id && spot.volunteer_id !== currentUserId) {
                            // Reserved for someone else
                            const volunteerName = this.getVolunteerNameById(spot.volunteer_id);
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #f3f4f6; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #9ca3af;">
                                    <span style="font-size: 0.875rem; color: #374151;">
                                        Reserved for ${volunteerName}
                                    </span>
                                    <span style="padding: 0.25rem 0.75rem; background: #f59e0b; color: white; border-radius: 0.25rem; font-size: 0.75rem;">RESERVED</span>
                                </div>
                            `;
                        } else if (spot.reserved && spot.volunteer_id === currentUserId) {
                            // Reserved specifically for current user
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #fef3c7; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #f59e0b;">
                                    <span style="font-size: 0.875rem; color: #92400e; font-weight: 600;">
                                        Reserved for YOU
                                    </span>
                                    <div style="display: flex; gap: 0.5rem;">
                                        <button onclick="CLAWSApp.claimReservedSpot(${event.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 500; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#bbf7d0'" onmouseout="this.style.background='#dcfce7'">
                                            ✓ Claim
                                        </button>
                                        <button onclick="CLAWSApp.declineReservedSpot(${event.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #f3f4f6; color: #6b7280; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 500; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#e5e7eb'" onmouseout="this.style.background='#f3f4f6'">
                                            ✗ Decline
                                        </button>
                                    </div>
                                </div>
                            `;
                        } else {
                            // Open spot
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #f0fdf4; border-radius: 0.375rem; margin-bottom: 0.5rem; border: 1px dashed #10b981; border-left: 3px solid #10b981;">
                                    <span style="font-size: 0.875rem; color: #166534; font-weight: 500;">
                                        Spot Available
                                    </span>
                                    <button onclick="CLAWSApp.claimEventSpot(${event.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 500; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#bbf7d0'" onmouseout="this.style.background='#dcfce7'">
                                        🎯 Claim This Spot!
                                    </button>
                                </div>
                            `;
                        }
                    });
                    
                    // Check if current user can edit (admins and editors can edit all events)
                    const canEdit = window.wpApiSettings.userCan?.manage_options || window.wpApiSettings.userCan?.edit_others_posts;
                    let editDeleteButtons = '';
                    if (canEdit) {
                        editDeleteButtons = `
                            <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; display: flex; gap: 0.5rem;">
                                <button onclick="CLAWSApp.editEvent(${event.id})" style="padding: 0.375rem 0.75rem; background: #eff6ff; color: #2563eb; border: 1px solid #bfdbfe; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#dbeafe'; this.style.borderColor='#93c5fd'" onmouseout="this.style.background='#eff6ff'; this.style.borderColor='#bfdbfe'">
                                    ✏️ Edit Event
                                </button>
                                <button onclick="CLAWSApp.deleteEvent(${event.id})" style="padding: 0.375rem 0.75rem; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#fee2e2'; this.style.borderColor='#fca5a5'" onmouseout="this.style.background='#fef2f2'; this.style.borderColor='#fecaca'">
                                    🗑️ Delete Event
                                </button>
                            </div>
                        `;
                    }
                    
                    html += `
                        <div style="background: white; border: 1px solid #e5e7eb; border-radius: 0.75rem; padding: 1.5rem;">
                            <div style="margin-bottom: 1rem;">
                                <h3 style="margin: 0 0 0.5rem; color: #1f2937; font-size: 1.125rem; font-weight: 600;">${event.name}</h3>
                                <div style="display: flex; align-items: center; gap: 0.75rem; color: #6b7280; font-size: 0.875rem;">
                                    <span>📅 ${eventDate}</span>
                                    <span>⏰ ${event.start_time} - ${event.end_time}</span>
                                </div>
                            </div>
                            
                            ${event.notes ? `
                                <div style="background: #f9fafb; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem;">
                                    <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${event.notes}</p>
                                </div>
                            ` : ''}
                            
                            <div style="margin-top: 1rem;">
                                <h6 style="font-weight: 600; font-size: 0.875rem; color: #374151; margin-bottom: 0.75rem;">
                                    Team Roster
                                </h6>
                                ${teamLeadHtml}
                                ${restructuredSpotsHtml}
                            </div>
                            ${editDeleteButtons}
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading events:', error);
                container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #ef4444;">Failed to load events</p>';
            });
        },
        
        loadAvailableProjects: function() {
            console.log('=== LOAD AVAILABLE PROJECTS STARTED ===');
            const container = document.querySelector('#claws-projects-list');
            if (!container) {
                console.log('❌ Projects container not found');
                return;
            }
            
            console.log('✅ Projects container found, fetching data...');
            container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #9ca3af;">🔍 Loading available projects...</p>';
            
            fetch(window.wpApiSettings.root + 'claws/v1/projects/available', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => {
                console.log('📥 Projects API response status:', response.status);
                return response.json();
            })
            .then(projects => {
                console.log('📥 Projects data received:', projects);
                console.log('   Number of projects:', projects ? projects.length : 0);
                
                if (!projects || projects.length === 0) {
                    console.log('⚠️ No projects found, showing empty message');
                    container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #9ca3af;">No ongoing projects available.</p>';
                    return;
                }
                
                console.log('✅ Rendering', projects.length, 'projects');
                const currentUserId = parseInt(window.wpApiSettings.userId);
                
                let html = '<div style="display: grid; gap: 1.5rem; margin-top: 1.5rem;">';
                projects.forEach(project => {
                    // Get volunteer spots
                    const spots = project.volunteer_spots || [];
                    
                    // Get team lead info
                    const leadName = this.getVolunteerNameById(project.lead_id) || 'Unknown';
                    
                    // Build team lead section
                    let teamLeadHtml = `
                        <div style="display: flex; align-items: center; justify-content: space-between; padding: 0.75rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 0.5rem; margin-bottom: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                            <span style="font-size: 0.9375rem; color: white; font-weight: 600; display: flex; align-items: center; gap: 0.5rem;">
                                <span style="font-size: 1.25rem;">👑</span>
                                ${leadName}
                                <span style="background: rgba(255,255,255,0.3); color: white; padding: 0.125rem 0.5rem; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">Project Lead</span>
                            </span>
                        </div>
                    `;
                    
                    // Restructure volunteer spots to be indented
                    let restructuredSpotsHtml = '';
                    spots.forEach((spot, index) => {
                        const spotNum = index + 1;
                        
                        if (spot.volunteer_id && spot.volunteer_id === currentUserId) {
                            const volunteerName = this.getVolunteerNameById(spot.volunteer_id);
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #dbeafe; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #3b82f6;">
                                    <span style="font-size: 0.875rem; color: #1e40af; font-weight: 600;">
                                        ${volunteerName} (You)
                                    </span>
                                    <button onclick="CLAWSApp.unclaimProjectSpot(${project.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#fee2e2'; this.style.borderColor='#fca5a5'" onmouseout="this.style.background='#fef2f2'; this.style.borderColor='#fecaca'">
                                        ❌ Changed My Mind
                                    </button>
                                </div>
                            `;
                        } else if (spot.reserved && spot.volunteer_id && spot.volunteer_id !== currentUserId) {
                            const volunteerName = this.getVolunteerNameById(spot.volunteer_id);
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #f3f4f6; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #9ca3af;">
                                    <span style="font-size: 0.875rem; color: #374151;">
                                        Reserved for ${volunteerName}
                                    </span>
                                    <span style="padding: 0.25rem 0.75rem; background: #f59e0b; color: white; border-radius: 0.25rem; font-size: 0.75rem;">RESERVED</span>
                                </div>
                            `;
                        } else if (spot.reserved && spot.volunteer_id === currentUserId) {
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #fef3c7; border-radius: 0.375rem; margin-bottom: 0.5rem; border-left: 3px solid #f59e0b;">
                                    <span style="font-size: 0.875rem; color: #92400e; font-weight: 600;">
                                        Reserved for YOU
                                    </span>
                                    <div style="display: flex; gap: 0.5rem;">
                                        <button onclick="CLAWSApp.claimReservedProjectSpot(${project.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 500; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#bbf7d0'" onmouseout="this.style.background='#dcfce7'">
                                            ✓ Claim
                                        </button>
                                        <button onclick="CLAWSApp.declineReservedProjectSpot(${project.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #f3f4f6; color: #6b7280; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 500; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#e5e7eb'" onmouseout="this.style.background='#f3f4f6'">
                                            ✗ Decline
                                        </button>
                                    </div>
                                </div>
                            `;
                        } else {
                            restructuredSpotsHtml += `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0.75rem 0.75rem 1.5rem; background: #f0fdf4; border-radius: 0.375rem; margin-bottom: 0.5rem; border: 1px dashed #10b981; border-left: 3px solid #10b981;">
                                    <span style="font-size: 0.875rem; color: #166534; font-weight: 500;">
                                        Spot Available
                                    </span>
                                    <button onclick="CLAWSApp.claimProjectSpot(${project.id}, ${spotNum})" style="padding: 0.375rem 0.75rem; background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 500; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#bbf7d0'" onmouseout="this.style.background='#dcfce7'">
                                        🎯 Claim This Spot!
                                    </button>
                                </div>
                            `;
                        }
                    });
                    
                    // Check if current user can edit (admins and editors can edit all projects)
                    const canEdit = window.wpApiSettings.userCan?.manage_options || window.wpApiSettings.userCan?.edit_others_posts;
                    let editDeleteButtons = '';
                    if (canEdit) {
                        editDeleteButtons = `
                            <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; display: flex; gap: 0.5rem;">
                                <button onclick="CLAWSApp.editProject(${project.id})" style="padding: 0.375rem 0.75rem; background: #eff6ff; color: #2563eb; border: 1px solid #bfdbfe; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#dbeafe'; this.style.borderColor='#93c5fd'" onmouseout="this.style.background='#eff6ff'; this.style.borderColor='#bfdbfe'">
                                    ✏️ Edit Project
                                </button>
                                <button onclick="CLAWSApp.retireProject(${project.id})" style="padding: 0.375rem 0.75rem; background: #fef3c7; color: #d97706; border: 1px solid #fde68a; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#fde68a'; this.style.borderColor='#fcd34d'" onmouseout="this.style.background='#fef3c7'; this.style.borderColor='#fde68a'">
                                    🏁 Retire Project
                                </button>
                            </div>
                        `;
                    }
                    
                    html += `
                        <div style="background: white; border: 1px solid #e5e7eb; border-radius: 0.75rem; padding: 1.5rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 1rem;">
                                <div>
                                    <h3 style="margin: 0 0 0.5rem; color: #1f2937; font-size: 1.125rem; font-weight: 600;">${project.name}</h3>
                                    <div style="display: flex; align-items: center; gap: 0.75rem; color: #6b7280; font-size: 0.875rem;">
                                        <span>🔄 Ongoing project</span>
                                        ${project.min_commitment ? `<span>⏱️ ${project.min_commitment}</span>` : ''}
                                    </div>
                                </div>
                                <span style="padding: 0.25rem 0.75rem; background: #dbeafe; color: #1e40af; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">ONGOING</span>
                            </div>
                            
                            ${project.notes ? `
                                <div style="background: #f9fafb; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem;">
                                    <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${project.notes}</p>
                                </div>
                            ` : ''}
                            
                            <div style="margin-top: 1rem;">
                                <h6 style="font-weight: 600; font-size: 0.875rem; color: #374151; margin-bottom: 0.75rem;">
                                    Team Roster
                                </h6>
                                ${teamLeadHtml}
                                ${restructuredSpotsHtml}
                            </div>
                            ${editDeleteButtons}
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading projects:', error);
                container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #ef4444;">Failed to load projects</p>';
            });
        },

        /**
         * Get volunteer name by ID from cached list
         */
        getVolunteerNameById: function(volunteerId) {
            console.log('getVolunteerNameById called with:', volunteerId);
            console.log('  - allVolunteers exists:', !!this.allVolunteers);
            console.log('  - allVolunteers length:', this.allVolunteers?.length);
            
            if (!this.allVolunteers) {
                console.log('  - Returning "Unknown" - allVolunteers not loaded');
                return 'Unknown';
            }
            
            const volunteer = this.allVolunteers.find(v => v.id === parseInt(volunteerId));
            console.log('  - Found volunteer:', volunteer);
            console.log('  - Returning:', volunteer ? volunteer.name : 'Unknown');
            
            return volunteer ? volunteer.name : 'Unknown';
        },

        /**
         * Claim an event spot for the current user
         */
        claimEventSpot: function(eventId, spotNumber) {
            if (!confirm('Claim this volunteer spot?')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}/claim-spot`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ spotNumber: spotNumber })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Spot claimed successfully!', 'success');
                    this.loadAvailableEvents(); // Refresh the list
                } else {
                    this.showAlert(data.message || 'Failed to claim spot', 'error');
                }
            })
            .catch(error => {
                console.error('Error claiming spot:', error);
                this.showAlert('Failed to claim spot', 'error');
            });
        },

        /**
         * Unclaim an event spot (Changed My Mind)
         */
        unclaimEventSpot: function(eventId, spotNumber) {
            if (!confirm('Are you sure you want to unclaim this spot?')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}/unclaim-spot`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ spotNumber: spotNumber })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Spot unclaimed successfully', 'success');
                    this.loadAvailableEvents();
                } else {
                    this.showAlert(data.message || 'Failed to unclaim spot', 'error');
                }
            })
            .catch(error => {
                console.error('Error unclaiming spot:', error);
                this.showAlert('Failed to unclaim spot', 'error');
            });
        },

        /**
         * Claim a reserved spot
         */
        claimReservedSpot: function(eventId, spotNumber) {
            // Same as regular claim
            this.claimEventSpot(eventId, spotNumber);
        },

        /**
         * Decline a reserved spot (turns it into regular available spot)
         */
        declineReservedSpot: function(eventId, spotNumber) {
            if (!confirm('Decline this reserved spot? It will become available to everyone.')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}/decline-spot`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ spotNumber: spotNumber })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Reservation declined. Spot is now available to all volunteers.', 'success');
                    this.loadAvailableEvents();
                } else {
                    this.showAlert(data.message || 'Failed to decline spot', 'error');
                }
            })
            .catch(error => {
                console.error('Error declining spot:', error);
                this.showAlert('Failed to decline spot', 'error');
            });
        },

        /**
         * Edit an event
         */
        editEvent: function(eventId) {
            // Fetch event data and pre-fill form
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(event => {
                if (!event || !event.id) {
                    this.showAlert('Failed to load event data', 'error');
                    return;
                }
                
                console.log('Event data received for editing:', event);
                
                // Store editing ID
                this.editingEventId = eventId;
                
                // Show the event form
                this.showAddEventForm();
                
                // Wait for form to be visible, then pre-fill fields
                setTimeout(() => {
                    // Change modal title
                    const modalTitle = document.querySelector('#claws-add-event-modal h2');
                    if (modalTitle) {
                        modalTitle.textContent = event.type === 'project' ? '✏️ Edit Project' : '✏️ Edit Event';
                    }
                    
                    // Pre-fill fields
                    const nameField = document.getElementById('claws-event-name');
                    if (nameField) nameField.value = event.name || '';
                    
                    const typeField = document.getElementById('claws-event-type');
                    if (typeField) typeField.value = event.type || 'event';
                    
                    const dateField = document.getElementById('claws-event-date');
                    if (dateField) dateField.value = event.date || '';
                    
                    const startField = document.getElementById('claws-event-start-time');
                    if (startField) startField.value = event.start_time || '';
                    
                    const endField = document.getElementById('claws-event-end-time');
                    if (endField) endField.value = event.end_time || '';
                    
                    const volunteersField = document.getElementById('claws-event-volunteers');
                    if (volunteersField) {
                        volunteersField.value = event.num_volunteers || 1;
                        // Rebuild volunteer spots UI to match the number
                        this.updateVolunteerSpots();
                    }
                    
                    // Now populate any existing reservations
                    if (event.volunteer_spots && Array.isArray(event.volunteer_spots)) {
                        event.volunteer_spots.forEach((spot, index) => {
                            const spotNumber = index + 1;
                            if (spot.reserved && spot.volunteer_id) {
                                const checkbox = document.getElementById(`reserve-spot-${spotNumber}`);
                                if (checkbox) {
                                    checkbox.checked = true;
                                    this.toggleSpotReservation(spotNumber);
                                    
                                    const dropdown = document.getElementById(`volunteer-spot-${spotNumber}`);
                                    if (dropdown) {
                                        dropdown.value = spot.volunteer_id;
                                    }
                                }
                            }
                        });
                    }
                    
                    const leadField = document.getElementById('claws-event-lead');
                    if (leadField) leadField.value = event.lead_id || '';
                    
                    const categoryField = document.getElementById('claws-event-category');
                    if (categoryField) categoryField.value = event.category || '';
                    
                    const notesField = document.getElementById('claws-event-notes');
                    if (notesField) notesField.value = event.notes || '';
                    
                    // Change button text
                    const submitBtn = document.querySelector('#claws-add-event-modal button[onclick*="saveEvent"]');
                    console.log('Submit button found:', submitBtn);
                    console.log('Button current text:', submitBtn?.textContent);
                    if (submitBtn) {
                        submitBtn.textContent = event.type === 'project' ? '💾 Update Project' : '💾 Update Event';
                        console.log('Button text changed to:', submitBtn.textContent);
                    } else {
                        console.error('❌ Submit button not found with selector: #claws-add-event-modal button[onclick*="saveEvent"]');
                    }
                    
                    console.log('✅ Form populated with event data');
                }, 200);
                
            })
            .catch(error => {
                console.error('Error loading event:', error);
                this.showAlert('Failed to load event data', 'error');
            });
        },

        /**
         * Delete an event
         */
        deleteEvent: function(eventId) {
            if (!confirm('Are you sure you want to delete this event/project? This cannot be undone.')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}`, {
                method: 'DELETE',
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Event/Project deleted successfully', 'success');
                    this.loadAvailableEvents();
                    this.loadAvailableProjects();
                } else {
                    this.showAlert(data.message || 'Failed to delete', 'error');
                }
            })
            .catch(error => {
                console.error('Error deleting event:', error);
                this.showAlert('Failed to delete event/project', 'error');
            });
        },

        /**
         * Claim a project spot for the current user
         */
        claimProjectSpot: function(projectId, spotNumber) {
            if (!confirm('Claim this volunteer spot?')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/projects/${projectId}/claim-spot`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ spotNumber: spotNumber })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Spot claimed successfully!', 'success');
                    this.loadAvailableProjects(); // Refresh the list
                } else {
                    this.showAlert(data.message || 'Failed to claim spot', 'error');
                }
            })
            .catch(error => {
                console.error('Error claiming spot:', error);
                this.showAlert('Failed to claim spot', 'error');
            });
        },

        /**
         * Unclaim a project spot (Changed My Mind)
         */
        unclaimProjectSpot: function(projectId, spotNumber) {
            if (!confirm('Are you sure you want to unclaim this spot?')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/projects/${projectId}/unclaim-spot`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ spotNumber: spotNumber })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Spot unclaimed successfully', 'success');
                    this.loadAvailableProjects();
                } else {
                    this.showAlert(data.message || 'Failed to unclaim spot', 'error');
                }
            })
            .catch(error => {
                console.error('Error unclaiming spot:', error);
                this.showAlert('Failed to unclaim spot', 'error');
            });
        },

        /**
         * Claim a reserved project spot
         */
        claimReservedProjectSpot: function(projectId, spotNumber) {
            this.claimProjectSpot(projectId, spotNumber);
        },

        /**
         * Decline a reserved project spot
         */
        declineReservedProjectSpot: function(projectId, spotNumber) {
            if (!confirm('Decline this reserved spot? It will become available to everyone.')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/projects/${projectId}/decline-spot`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ spotNumber: spotNumber })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Reservation declined. Spot is now available to all volunteers.', 'success');
                    this.loadAvailableProjects();
                } else {
                    this.showAlert(data.message || 'Failed to decline spot', 'error');
                }
            })
            .catch(error => {
                console.error('Error declining spot:', error);
                this.showAlert('Failed to decline spot', 'error');
            });
        },

        /**
         * Edit a project
         */
        editProject: function(projectId) {
            // Fetch project data and pre-fill form
            fetch(window.wpApiSettings.root + `claws/v1/projects/${projectId}`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(project => {
                if (!project || !project.id) {
                    this.showAlert('Failed to load project data', 'error');
                    return;
                }
                
                console.log('Project data received for editing:', project);
                
                // Store editing ID
                this.editingEventId = projectId;
                
                // Show the event form (same form for events and projects)
                this.showAddEventForm();
                
                // Wait for form to be visible, then pre-fill fields
                setTimeout(() => {
                    // Change modal title
                    const modalTitle = document.querySelector('#claws-add-event-modal h2');
                    if (modalTitle) {
                        modalTitle.textContent = '✏️ Edit Project';
                    }
                    
                    // Pre-fill fields
                    const nameField = document.getElementById('claws-event-name');
                    if (nameField) nameField.value = project.name || '';
                    
                    const typeField = document.getElementById('claws-event-type');
                    if (typeField) typeField.value = 'project';
                    
                    // Projects don't have dates/times
                    const dateField = document.getElementById('claws-event-date');
                    if (dateField) dateField.value = '';
                    
                    const startField = document.getElementById('claws-event-start-time');
                    if (startField) startField.value = '';
                    
                    const endField = document.getElementById('claws-event-end-time');
                    if (endField) endField.value = '';
                    
                    const minCommitField = document.getElementById('claws-event-min-commitment');
                    if (minCommitField) minCommitField.value = project.min_commitment || '';
                    
                    const volunteersField = document.getElementById('claws-event-volunteers');
                    if (volunteersField) {
                        volunteersField.value = project.num_volunteers || 1;
                        // Rebuild volunteer spots UI to match the number
                        this.updateVolunteerSpots();
                    }
                    
                    // Now populate any existing reservations
                    if (project.volunteer_spots && Array.isArray(project.volunteer_spots)) {
                        project.volunteer_spots.forEach((spot, index) => {
                            const spotNumber = index + 1;
                            if (spot.reserved && spot.volunteer_id) {
                                const checkbox = document.getElementById(`reserve-spot-${spotNumber}`);
                                if (checkbox) {
                                    checkbox.checked = true;
                                    this.toggleSpotReservation(spotNumber);
                                    
                                    const dropdown = document.getElementById(`volunteer-spot-${spotNumber}`);
                                    if (dropdown) {
                                        dropdown.value = spot.volunteer_id;
                                    }
                                }
                            }
                        });
                    }
                    
                    const leadField = document.getElementById('claws-event-lead');
                    if (leadField) leadField.value = project.lead_id || '';
                    
                    const categoryField = document.getElementById('claws-event-category');
                    if (categoryField) categoryField.value = project.category || '';
                    
                    const notesField = document.getElementById('claws-event-notes');
                    if (notesField) notesField.value = project.notes || '';
                    
                    // Change button text
                    const submitBtn = document.querySelector('#claws-add-event-modal button[onclick*="saveEvent"]');
                    console.log('Submit button found:', submitBtn);
                    console.log('Button current text:', submitBtn?.textContent);
                    if (submitBtn) {
                        submitBtn.textContent = '💾 Update Project';
                        console.log('Button text changed to:', submitBtn.textContent);
                    } else {
                        console.error('❌ Submit button not found with selector: #claws-add-event-modal button[onclick*="saveEvent"]');
                    }
                    
                    console.log('✅ Form populated with project data');
                }, 200);
                
            })
            .catch(error => {
                console.error('Error loading project:', error);
                this.showAlert('Failed to load project data', 'error');
            });
        },

        /**
         * Retire a project (requires reason)
         */
        retireProject: function(projectId) {
            // Prompt for reason
            let reason = '';
            while (!reason || reason.trim() === '') {
                reason = prompt('⚠️ REQUIRED: Please provide a reason for retiring this project:');
                if (reason === null) return; // User clicked Cancel
                if (!reason.trim()) {
                    alert('A retirement reason is required. Please provide a detailed explanation.');
                }
            }
            
            if (!confirm('Retire this project? It will no longer appear in the available projects list.')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/projects/${projectId}/retire`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ reason: reason })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Project retired successfully', 'success');
                    this.loadAvailableProjects();
                } else {
                    this.showAlert(data.message || 'Failed to retire project', 'error');
                }
            })
            .catch(error => {
                console.error('Error retiring project:', error);
                this.showAlert('Failed to retire project', 'error');
            });
        },

        loadVolunteerStatsGoals: function() {
            console.log('=== LOAD VOLUNTEER STATS & GOALS TAB ===');
            this.loadVolunteerStats();
        },

        loadVolunteerComms: function() {
            this.loadChatConversations();
            this.currentChat = null;
            this.chatPollingInterval = null;
        },
        
        /**
         * Load available conversations (teams and individuals)
         */
        loadChatConversations: function() {
            this.loadChatTeams();
            this.loadChatIndividuals();
        },
        
        /**
         * Load teams for chat
         */
        loadChatTeams: function() {
            const container = document.getElementById('claws-chat-teams-list');
            const countBadge = document.getElementById('claws-chat-teams-count');
            if (!container) return;
            
            container.innerHTML = '<p style="color: #9ca3af; font-size: 0.875rem; padding: 0.5rem;">Loading...</p>';
            
            Promise.all([
                fetch(window.wpApiSettings.root + 'claws/v1/teams/events', {
                    headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
                }).then(r => r.json()),
                fetch(window.wpApiSettings.root + 'claws/v1/teams/projects', {
                    headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
                }).then(r => r.json())
            ])
            .then(([eventTeams, projectTeams]) => {
                const allTeams = [...(eventTeams || []), ...(projectTeams || [])];
                
                if (allTeams.length === 0) {
                    container.innerHTML = '<p style="color: #9ca3af; font-size: 0.75rem; padding: 0.5rem; font-style: italic;">No teams</p>';
                    countBadge.textContent = '0';
                    return;
                }
                
                countBadge.textContent = allTeams.length;
                
                let html = '';
                allTeams.forEach(team => {
                    const icon = team.type === 'event' ? '📅' : '🔄';
                    // Count members + 1 for the lead
                    const memberCount = (team.members ? team.members.length : 0) + 1;
                    
                    html += `
                        <div onclick="CLAWSApp.openChat('team', ${team.id}, '${this.escapeHtml(team.name)}', ${memberCount})" 
                             class="claws-chat-item"
                             style="padding: 0.75rem; margin-bottom: 0.25rem; border-radius: 0.5rem; cursor: pointer; transition: background 0.2s;"
                             onmouseover="this.style.background='#f3f4f6'"
                             onmouseout="this.style.background='transparent'">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">${icon}</span>
                                <div style="flex: 1; min-width: 0;">
                                    <p style="margin: 0; font-weight: 600; font-size: 0.875rem; color: #1f2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${team.name}</p>
                                    <p style="margin: 0; font-size: 0.75rem; color: #9ca3af;">${memberCount} member${memberCount !== 1 ? 's' : ''}</p>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading teams:', error);
                container.innerHTML = '<p style="color: #ef4444; font-size: 0.75rem; padding: 0.5rem;">Failed to load</p>';
            });
        },
        
        /**
         * Load individuals for chat
         */
        loadChatIndividuals: function() {
            const container = document.getElementById('claws-chat-individuals-list');
            const countBadge = document.getElementById('claws-chat-individuals-count');
            if (!container) return;
            
            container.innerHTML = '<p style="color: #9ca3af; font-size: 0.875rem; padding: 0.5rem;">Loading...</p>';
            
            fetch(window.wpApiSettings.root + 'claws/v1/volunteers', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(volunteers => {
                if (!volunteers || volunteers.length === 0) {
                    container.innerHTML = '<p style="color: #9ca3af; font-size: 0.75rem; padding: 0.5rem; font-style: italic;">No users</p>';
                    countBadge.textContent = '0';
                    return;
                }
                
                countBadge.textContent = volunteers.length;
                
                let html = '';
                volunteers.forEach(volunteer => {
                    const initial = volunteer.name.charAt(0).toUpperCase();
                    const colors = ['#667eea', '#764ba2', '#f093fb', '#4facfe', '#43e97b', '#fa709a'];
                    const color = colors[volunteer.id % colors.length];
                    
                    html += `
                        <div onclick="CLAWSApp.openChat('individual', ${volunteer.id}, '${this.escapeHtml(volunteer.name)}', 1)" 
                             class="claws-chat-item"
                             style="padding: 0.75rem; margin-bottom: 0.25rem; border-radius: 0.5rem; cursor: pointer; transition: background 0.2s;"
                             onmouseover="this.style.background='#f3f4f6'"
                             onmouseout="this.style.background='transparent'">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <div style="width: 2.5rem; height: 2.5rem; border-radius: 50%; background: ${color}; display: flex; align-items: center; justify-content: center; color: white; font-weight: 600; font-size: 1rem; flex-shrink: 0;">
                                    ${initial}
                                </div>
                                <div style="flex: 1; min-width: 0;">
                                    <p style="margin: 0; font-weight: 600; font-size: 0.875rem; color: #1f2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${volunteer.name}</p>
                                    <p style="margin: 0; font-size: 0.75rem; color: #10b981;">● Online</p>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading volunteers:', error);
                container.innerHTML = '<p style="color: #ef4444; font-size: 0.75rem; padding: 0.5rem;">Failed to load</p>';
            });
        },
        
        /**
         * Toggle chat section
         */
        toggleChatSection: function(section) {
            const list = document.getElementById(`claws-chat-${section}-list`);
            const toggle = document.getElementById(`claws-chat-${section}-toggle`);
            
            if (!list || !toggle) return;
            
            if (list.style.display === 'none') {
                list.style.display = 'block';
                toggle.textContent = '▼';
            } else {
                list.style.display = 'none';
                toggle.textContent = '▶';
            }
        },
        
        /**
         * Open a chat conversation
         */
        currentChat: null,
        chatPollingInterval: null,
        
        openChat: function(type, id, name, memberCount) {
            // Stop polling previous chat
            if (this.chatPollingInterval) {
                clearInterval(this.chatPollingInterval);
            }
            
            // Store current chat
            this.currentChat = {
                type: type,
                id: id,
                name: name,
                memberCount: memberCount
            };
            
            // Show chat window
            document.getElementById('claws-chat-empty').style.display = 'none';
            document.getElementById('claws-chat-window').style.display = 'flex';
            
            // Update header
            const icon = type === 'team' ? (name.includes('Event') ? '📅' : '🔄') : '👤';
            const subtitle = type === 'team' ? `${memberCount} member${memberCount !== 1 ? 's' : ''}` : 'Direct Message';
            
            document.getElementById('claws-chat-header').innerHTML = `
                <div style="display: flex; align-items: center; gap: 1rem;">
                    <span style="font-size: 2rem;">${icon}</span>
                    <div>
                        <h4 style="margin: 0; font-size: 1.125rem; font-weight: 600; color: #1f2937;">${name}</h4>
                        <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${subtitle}</p>
                    </div>
                </div>
            `;
            
            // Load messages
            this.loadChatMessages();
            
            // Start polling for new messages every 3 seconds
            this.chatPollingInterval = setInterval(() => {
                this.loadChatMessages(true);
            }, 3000);
            
            // Focus input
            document.getElementById('claws-chat-input').focus();
        },
        
        /**
         * Load messages for current chat
         */
        loadChatMessages: function(silent = false) {
            if (!this.currentChat) return;
            
            const container = document.getElementById('claws-chat-messages');
            if (!container) return;
            
            if (!silent) {
                container.innerHTML = '<div style="text-align: center; padding: 2rem; color: #9ca3af;">Loading messages...</div>';
            }
            
            fetch(window.wpApiSettings.root + `claws/v1/messages/${this.currentChat.type}/${this.currentChat.id}`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(messages => {
                if (!messages || messages.length === 0) {
                    container.innerHTML = `
                        <div style="text-align: center; padding: 3rem; color: #9ca3af;">
                            <div style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;">💬</div>
                            <p style="font-size: 1rem; margin: 0;">No messages yet</p>
                            <p style="font-size: 0.875rem; margin: 0.5rem 0 0;">Start the conversation!</p>
                        </div>
                    `;
                    return;
                }
                
                // Render messages
                let html = '';
                const currentUserId = window.wpApiSettings.currentUserId;
                
                messages.forEach((msg, index) => {
                    const isOwn = msg.sender_id == currentUserId;
                    const showSender = index === 0 || messages[index-1].sender_id !== msg.sender_id;
                    
                    html += `
                        <div style="margin-bottom: 1rem; display: flex; ${isOwn ? 'justify-content: flex-end' : 'justify-content: flex-start'};">
                            <div style="max-width: 70%;">
                                ${showSender && !isOwn ? `<p style="margin: 0 0 0.25rem 0.5rem; font-size: 0.75rem; color: #6b7280; font-weight: 600;">${msg.sender_name}</p>` : ''}
                                <div style="padding: 0.75rem 1rem; border-radius: 1rem; ${isOwn ? 'background: #3b82f6; color: white; border-bottom-right-radius: 0.25rem;' : 'background: white; color: #1f2937; border: 1px solid #e5e7eb; border-bottom-left-radius: 0.25rem;'}">
                                    <p style="margin: 0; font-size: 0.875rem; white-space: pre-wrap;">${this.escapeHtml(msg.message)}</p>
                                </div>
                                <p style="margin: 0.25rem 0 0 0.5rem; font-size: 0.65rem; color: #9ca3af;">${msg.time}</p>
                            </div>
                        </div>
                    `;
                });
                
                container.innerHTML = html;
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
            })
            .catch(error => {
                console.error('Error loading messages:', error);
                if (!silent) {
                    container.innerHTML = '<div style="text-align: center; padding: 2rem; color: #ef4444;">Failed to load messages</div>';
                }
            });
        },
        
        /**
         * Send a chat message
         */
        sendChatMessage: function() {
            if (!this.currentChat) return;
            
            const input = document.getElementById('claws-chat-input');
            const message = input.value.trim();
            
            if (!message) return;
            
            // Disable input
            input.disabled = true;
            
            // Send message
            fetch(window.wpApiSettings.root + 'claws/v1/messages/send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({
                    chat_type: this.currentChat.type,
                    chat_id: this.currentChat.id,
                    message: message
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    // Clear input
                    input.value = '';
                    
                    // Reload messages
                    this.loadChatMessages(true);
                } else {
                    alert('Failed to send message');
                }
            })
            .catch(error => {
                console.error('Error sending message:', error);
                alert('Failed to send message');
            })
            .finally(() => {
                input.disabled = false;
                input.focus();
            });
        },
        
        /**
         * Helper to escape HTML
         */
        escapeHtml: function(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        },

        loadVolunteerAdmin: function() {
            console.log('Loading admin view - tasks needing approval');
            this.loadTasksNeedingApproval();
            this.loadApprovedTasksForAdmin();
        },
        
        /**
         * Load tasks that need approval (for Admin tab)
         */
        loadTasksNeedingApproval: function() {
            const container = document.querySelector('#claws-admin-pending');
            console.log('loadTasksNeedingApproval called, container exists:', !!container);
            
            if (!container) {
                console.warn('Admin pending container not found');
                return;
            }
            
            container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">Loading...</p>';
            
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-time/pending?view=approve', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => {
                console.log('Tasks needing approval response status:', response.status);
                return response.json();
            })
            .then(entries => {
                console.log('Tasks needing approval received:', entries);
                
                if (!entries || entries.length === 0) {
                    container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">No pending tasks to review.</p>';
                    return;
                }
                
                let html = '<div style="display: grid; gap: 1rem;">';
                entries.forEach(entry => {
                    const date = new Date(entry.date).toLocaleDateString();
                    
                    html += `
                        <div style="padding: 1rem; background: white; border: 1px solid #e5e7eb; border-radius: 0.5rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start;">
                                <div style="flex: 1;">
                                    <p style="margin: 0; font-weight: 600; color: #1f2937;">${entry.task_type}</p>
                                    <p style="margin: 0.25rem 0; font-size: 0.875rem; color: #6b7280;">${date} • ${entry.hours} hours</p>
                                    <p style="margin: 0.25rem 0 0; font-size: 0.875rem; color: #6b7280;">👤 Volunteer: <strong>${entry.volunteer_name}</strong></p>
                                    <p style="margin: 0.5rem 0 0; font-size: 0.875rem; color: #374151;">${entry.description}</p>
                                    <div style="margin-top: 1rem; display: flex; gap: 0.5rem;">
                                        <button onclick="CLAWSApp.approveTask(${entry.id})" style="padding: 0.5rem 1rem; background: #10b981; color: white; border: none; border-radius: 0.375rem; font-size: 0.875rem; cursor: pointer;">
                                            ✓ Approve
                                        </button>
                                        <button onclick="CLAWSApp.rejectTask(${entry.id})" style="padding: 0.5rem 1rem; background: #ef4444; color: white; border: none; border-radius: 0.375rem; font-size: 0.875rem; cursor: pointer;">
                                            ✗ Reject
                                        </button>
                                    </div>
                                </div>
                                <span style="padding: 0.25rem 0.75rem; background: #fef3c7; color: #92400e; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500; white-space: nowrap;">Pending</span>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading tasks needing approval:', error);
                container.innerHTML = '<p style="color: #ef4444; text-align: center; padding: 2rem;">Failed to load tasks.</p>';
            });
        },
        
        /**
         * Load approved tasks for admin view
         */
        loadApprovedTasksForAdmin: function() {
            const container = document.querySelector('#claws-admin-approved');
            if (!container) return;
            
            container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">Loading...</p>';
            
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-time/approved?view=approve&months=3', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(entries => {
                if (!entries || entries.length === 0) {
                    container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">No approved tasks.</p>';
                    return;
                }
                
                let html = '<div style="display: grid; gap: 1rem;">';
                entries.forEach(entry => {
                    const date = new Date(entry.date).toLocaleDateString();
                    html += `
                        <div style="padding: 1rem; background: white; border: 1px solid #e5e7eb; border-radius: 0.5rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start;">
                                <div>
                                    <p style="margin: 0; font-weight: 600; color: #1f2937;">${entry.task_type}</p>
                                    <p style="margin: 0.25rem 0; font-size: 0.875rem; color: #6b7280;">${date} • ${entry.hours} hours</p>
                                    <p style="margin: 0.25rem 0 0; font-size: 0.875rem; color: #6b7280;">👤 ${entry.volunteer_name || 'Unknown'}</p>
                                    <p style="margin: 0.5rem 0 0; font-size: 0.875rem; color: #374151;">${entry.description}</p>
                                </div>
                                <span style="padding: 0.25rem 0.75rem; background: #d1fae5; color: #065f46; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">Approved</span>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading approved tasks:', error);
                container.innerHTML = '<p style="color: #ef4444; text-align: center; padding: 2rem;">Failed to load tasks.</p>';
            });
        },
        
        /**
         * Show decline reservation modal
         */
        showDeclineModal: function(eventId, coordinatorName) {
            document.getElementById('decline-event-id').value = eventId;
            document.getElementById('decline-coordinator-name').textContent = coordinatorName || 'the event coordinator';
            document.getElementById('decline-note').value = '';
            
            const modal = document.getElementById('claws-decline-modal');
            if (modal) {
                modal.style.display = 'flex';
            }
        },
        
        /**
         * Hide decline reservation modal
         */
        hideDeclineModal: function() {
            const modal = document.getElementById('claws-decline-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        },
        
        /**
         * Submit decline reservation
         */
        submitDecline: function() {
            const eventId = document.getElementById('decline-event-id').value;
            const note = document.getElementById('decline-note').value.trim();
            
            if (!note) {
                this.showAlert('Please provide a reason for declining.', 'error');
                return;
            }
            
            // Call API to decline
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}/decline`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ note: note })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.hideDeclineModal();
                    this.showAlert('Reservation declined. The coordinator has been notified.', 'success');
                    // Reload events
                    this.loadAvailableEvents();
                } else {
                    this.showAlert(data.message || 'Failed to decline reservation.', 'error');
                }
            })
            .catch(error => {
                console.error('Error declining reservation:', error);
                this.showAlert('An error occurred. Please try again.', 'error');
            });
        },
        
        /**
         * Confirm event reservation
         */
        confirmReservation: function(eventId) {
            if (!confirm('Confirm your attendance for this event?')) {
                return;
            }
            
            fetch(window.wpApiSettings.root + `claws/v1/events/${eventId}/confirm`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Reservation confirmed!', 'success');
                    // Reload events
                    this.loadAvailableEvents();
                } else {
                    this.showAlert(data.message || 'Failed to confirm reservation.', 'error');
                }
            })
            .catch(error => {
                console.error('Error confirming reservation:', error);
                this.showAlert('An error occurred. Please try again.', 'error');
            });
        },

        /**
         * Load placeholder content for My Time sections
         */
        loadNeedsAttentionItems: function() {
        },

        loadPendingItems: function() {
            const container = document.querySelector('#claws-my-time-pending');
            console.log('loadPendingItems called, container exists:', !!container);
            
            if (!container) {
                console.warn('Pending items container not found - user may not be on My Time tab');
                return;
            }
            
            container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">Loading...</p>';
            
            const isAdmin = window.wpApiSettings.userCan?.manage_options || window.wpApiSettings.userCan?.edit_others_posts;
            console.log('Loading pending items, isAdmin:', isAdmin);
            
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-time/pending?view=my', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => {
                console.log('Pending items response status:', response.status);
                return response.json();
            })
            .then(entries => {
                console.log('Pending items received:', entries);
                
                if (!entries || entries.length === 0) {
                    container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">No items pending approval.</p>';
                    return;
                }
                
                let html = '<div style="display: grid; gap: 1rem;">';
                entries.forEach(entry => {
                    const date = new Date(entry.date).toLocaleDateString();
                    const isRejected = entry.approval_status === 'rejected';
                    
                    // Determine badge color and text
                    let badgeHtml = '';
                    if (isRejected) {
                        badgeHtml = '<span style="padding: 0.25rem 0.75rem; background: #fee2e2; color: #991b1b; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 600; white-space: nowrap;">❌ REJECTED</span>';
                    } else {
                        badgeHtml = '<span style="padding: 0.25rem 0.75rem; background: #fef3c7; color: #92400e; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500; white-space: nowrap;">⏳ Pending</span>';
                    }
                    
                    // Show rejection reason if rejected
                    let rejectionInfo = '';
                    if (isRejected && entry.rejection_reason) {
                        rejectionInfo = `
                            <div style="margin-top: 0.75rem; padding: 0.75rem; background: #fee2e2; border-left: 3px solid #dc2626; border-radius: 0.375rem;">
                                <p style="margin: 0; font-size: 0.875rem; color: #991b1b; font-weight: 600;">Rejection Reason:</p>
                                <p style="margin: 0.25rem 0 0; font-size: 0.875rem; color: #7f1d1d;">${entry.rejection_reason}</p>
                            </div>
                        `;
                    }
                    
                    // Edit/Delete buttons - always show for user's tasks in pending section
                    const editDeleteButtons = `
                        <div style="margin-top: 0.75rem; display: flex; gap: 0.5rem;">
                            <button onclick="CLAWSApp.editTask(${entry.id})" style="padding: 0.375rem 0.75rem; background: #eff6ff; color: #2563eb; border: 1px solid #bfdbfe; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#dbeafe'; this.style.borderColor='#93c5fd'" onmouseout="this.style.background='#eff6ff'; this.style.borderColor='#bfdbfe'">
                                ✏️ Edit
                            </button>
                            <button onclick="CLAWSApp.deleteTask(${entry.id})" style="padding: 0.375rem 0.75rem; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; border-radius: 0.375rem; font-size: 0.8125rem; cursor: pointer; transition: all 0.2s; font-weight: 500;" onmouseover="this.style.background='#fee2e2'; this.style.borderColor='#fca5a5'" onmouseout="this.style.background='#fef2f2'; this.style.borderColor='#fecaca'">
                                🗑️ Delete
                            </button>
                        </div>
                    `;
                    
                    html += `
                        <div style="padding: 1rem; background: white; border: 1px solid ${isRejected ? '#fecaca' : '#e5e7eb'}; border-radius: 0.5rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start;">
                                <div style="flex: 1;">
                                    <p style="margin: 0; font-weight: 600; color: #1f2937;">${entry.task_type}</p>
                                    <p style="margin: 0.25rem 0; font-size: 0.875rem; color: #6b7280;">${date} • ${entry.hours} hours</p>
                                    <p style="margin: 0.5rem 0 0; font-size: 0.875rem; color: #374151;">${entry.description}</p>
                                    ${rejectionInfo}
                                    ${editDeleteButtons}
                                </div>
                                ${badgeHtml}
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading pending items:', error);
                container.innerHTML = '<p style="color: #ef4444; text-align: center; padding: 2rem;">Failed to load pending items.</p>';
            });
        },

        /**
         * Approve a volunteer task
         */
        approveTask: function(taskId) {
            if (!confirm('Approve this task?')) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/volunteer-time/${taskId}/approve`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Task approved!', 'success');
                    // Refresh both views
                    this.loadPendingItems(); // For My Time tab
                    this.loadTasksNeedingApproval(); // For Admin tab
                } else {
                    this.showAlert(data.message || 'Failed to approve task', 'error');
                }
            })
            .catch(error => {
                console.error('Error approving task:', error);
                this.showAlert('Failed to approve task', 'error');
            });
        },

        /**
         * Reject a volunteer task
         */
        rejectTask: function(taskId) {
            let reason = '';
            while (!reason || reason.trim() === '') {
                reason = prompt('⚠️ REQUIRED: Please provide a reason for rejecting this task.\n\nThis will be sent to the volunteer so they can correct and resubmit.');
                
                if (reason === null) {
                    // User clicked Cancel
                    return;
                }
                
                if (!reason || reason.trim() === '') {
                    alert('A rejection reason is required. Please provide a reason or click Cancel to abort.');
                }
            }
            
            console.log('Rejecting task', taskId, 'with reason:', reason);
            
            fetch(window.wpApiSettings.root + `claws/v1/volunteer-time/${taskId}/reject`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ reason: reason.trim() })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Task rejected and volunteer has been notified', 'success');
                    // Refresh both views
                    this.loadPendingItems(); // For My Time tab
                    this.loadTasksNeedingApproval(); // For Admin tab
                } else {
                    this.showAlert(data.message || 'Failed to reject task', 'error');
                }
            })
            .catch(error => {
                console.error('Error rejecting task:', error);
                this.showAlert('Failed to reject task', 'error');
            });
        },

        /**
         * Edit a task (opens the task form with pre-filled data)
         */
        editTask: function(taskId) {
            console.log('=== EDIT TASK STARTED ===');
            console.log('Task ID to edit:', taskId);
            
            // Fetch the task data
            fetch(window.wpApiSettings.root + `claws/v1/volunteer-time/${taskId}`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(task => {
                console.log('Task data received:', task);
                
                if (!task || !task.id) {
                    this.showAlert('Failed to load task data', 'error');
                    return;
                }
                
                // Store the task ID for updating - CRITICAL
                this.editingTaskId = taskId;
                window.CLAWSApp.editingTaskId = taskId; // Also store on window object as backup
                console.log('✅ editingTaskId SET TO:', this.editingTaskId);
                console.log('✅ window.CLAWSApp.editingTaskId SET TO:', window.CLAWSApp.editingTaskId);
                
                // Show the form
                this.showCompletedTaskForm();
                
                // Pre-fill the form fields
                document.getElementById('claws-task-date').value = task.date;
                document.getElementById('claws-task-type').value = task.task_type;
                document.getElementById('claws-task-description').value = task.description;
                document.getElementById('claws-task-start-time').value = task.start_time || '';
                document.getElementById('claws-task-end-time').value = task.end_time || '';
                document.getElementById('claws-task-total-hours').value = task.hours;
                document.getElementById('claws-task-coordinator').value = task.coordinator_id;
                
                // If task requires colony, show colony dropdown and select it
                if (task.colony_id && this.requiresColonySelection(task.task_type)) {
                    const colonyGroup = document.getElementById('claws-task-colony-group');
                    if (colonyGroup) {
                        colonyGroup.style.display = 'block';
                        document.getElementById('claws-task-colony').value = task.colony_id;
                    }
                }
                
                // Change button text to indicate editing
                const submitBtn = document.querySelector('#claws-completed-task-form button[onclick*="saveCompletedTask"]');
                if (submitBtn) {
                    submitBtn.textContent = '💾 Update Task';
                }
                
                console.log('=== EDIT TASK COMPLETED - Form ready ===');
            })
            .catch(error => {
                console.error('Error loading task:', error);
                this.showAlert('Failed to load task data', 'error');
            });
        },

        /**
         * Delete a task
         */
        deleteTask: function(taskId) {
            if (!confirm('Are you sure you want to delete this task? This cannot be undone.')) {
                return;
            }
            
            console.log('Deleting task', taskId);
            
            fetch(window.wpApiSettings.root + `claws/v1/volunteer-time/${taskId}`, {
                method: 'DELETE',
                headers: {
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showAlert('Task deleted successfully', 'success');
                    // Refresh pending items
                    this.loadPendingItems();
                } else {
                    this.showAlert(data.message || 'Failed to delete task', 'error');
                }
            })
            .catch(error => {
                console.error('Error deleting task:', error);
                this.showAlert('Failed to delete task', 'error');
            });
        },

        loadApprovedItems: function() {
            const container = document.querySelector('#claws-my-time-approved');
            if (!container) return;
            
            const monthsSelect = document.querySelector('select[onchange*="loadApprovedItems"]');
            const months = monthsSelect ? monthsSelect.value : 3;
            
            container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">Loading...</p>';
            
            fetch(window.wpApiSettings.root + `claws/v1/volunteer-time/approved?months=${months}`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(entries => {
                if (!entries || entries.length === 0) {
                    container.innerHTML = '<p style="color: #9ca3af; text-align: center; padding: 2rem;">No approved items for the selected time period.</p>';
                    return;
                }
                
                let html = '<div style="display: grid; gap: 1rem;">';
                entries.forEach(entry => {
                    const date = new Date(entry.date).toLocaleDateString();
                    html += `
                        <div style="padding: 1rem; background: white; border: 1px solid #e5e7eb; border-radius: 0.5rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start;">
                                <div>
                                    <p style="margin: 0; font-weight: 600; color: #1f2937;">${entry.task_type}</p>
                                    <p style="margin: 0.25rem 0; font-size: 0.875rem; color: #6b7280;">${date} • ${entry.hours} hours</p>
                                    <p style="margin: 0.5rem 0 0; font-size: 0.875rem; color: #374151;">${entry.description}</p>
                                </div>
                                <span style="padding: 0.25rem 0.75rem; background: #d1fae5; color: #065f46; border-radius: 0.25rem; font-size: 0.75rem; font-weight: 500;">Approved</span>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading approved items:', error);
                container.innerHTML = '<p style="color: #ef4444; text-align: center; padding: 2rem;">Failed to load approved items.</p>';
            });
        },

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

        /**
         * Load intake records
         */
        loadIntakeRecords: function() {
            // Placeholder - implement intake loading logic
            this.intakeRecords = [];
            this.updateIntakeCharts();
        },

        /**
         * Load discharge records
         */
        loadDischargeRecords: async function() {
            try {
                const timestamp = new Date().getTime();
                const randomParam = Math.random().toString(36).substring(7);
                
                // Check if user is admin to determine which data to fetch
                const isAdmin = clawsData.userRoles && (
                    clawsData.userRoles.includes('administrator') || 
                    clawsData.userRoles.includes('editor')
                );
                
                // FIRST: Load intake records (needed for gender cross-reference in charts)
                const intakeEndpoint = isAdmin ? 
                    this.config.apiUrl + 'admin/intakes' : 
                    this.config.apiUrl + 'intakes';
                
                const intakeResponse = await fetch(intakeEndpoint + '?_=' + timestamp + '&r1=' + randomParam, {
                    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'
                    }
                });
                
                if (intakeResponse.ok) {
                    const intakeData = await intakeResponse.json();
                    this.intakeRecords = Array.isArray(intakeData) ? intakeData : [];
                } else {
                    throw new Error(`Failed to load intakes: HTTP ${intakeResponse.status}`);
                }
                
                // SECOND: Load discharge records
                const dischargeEndpoint = isAdmin ? 
                    this.config.apiUrl + 'admin/discharges' : 
                    this.config.apiUrl + 'discharges';
                
                const response = await fetch(dischargeEndpoint + '?_=' + timestamp + '&r2=' + randomParam, {
                    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'
                    }
                });
                
                if (response.ok) {
                    const dischargeData = await response.json();
                    this.dischargeRecords = Array.isArray(dischargeData) ? dischargeData : [];
                } else {
                    throw new Error(`Failed to load discharges: HTTP ${response.status}`);
                }
                
            } catch (error) {
                this.dischargeRecords = [];
                this.intakeRecords = [];
            }
            
            this.updateDischargeDisplay();
        },

        /**
         * Update discharge display
         */
        updateDischargeDisplay: function() {
            const container = document.getElementById('claws-discharge-content');
            if (!container) {
                return;
            }
            
            if (!this.dischargeRecords || this.dischargeRecords.length === 0) {
                container.innerHTML = `
                    <div style="padding: 1rem; text-align: center;">
                        <p style="color: #6b7280; font-style: italic;">No discharge records found.</p>
                        <button onclick="CLAWSApp.showDischargeForm()" style="margin-top: 1rem; margin-right: 0.5rem; background: #3b82f6; color: white; border: none; border-radius: 0.5rem; padding: 0.75rem 1.5rem; cursor: pointer; font-weight: 500;">Record New Discharge</button>
                        <button onclick="CLAWSApp.exportDischargeData()" style="margin-top: 1rem; background: #059669; color: white; border: none; border-radius: 0.5rem; padding: 0.75rem 1.5rem; cursor: pointer; font-weight: 500;">Export Data</button>
                    </div>
                `;
                return;
            }
            
            // Check if user is admin
            const isAdmin = clawsData.userRoles && (
                clawsData.userRoles.includes('administrator') || 
                clawsData.userRoles.includes('editor')
            );
            
            // Sort by date (newest first)
            const sortedDischarges = this.dischargeRecords
                .sort((a, b) => new Date(b.discharge_date || b.date) - new Date(a.discharge_date || a.date));
            
            let html = `
                <div style="padding: 1rem;">
                    <!-- 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;">Discharge Actions</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; margin-bottom: 0.5rem;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                            Record New Discharge
                        </button>
                        <button onclick="CLAWSApp.exportDischargeData()" style="width: 100%; background: rgba(34, 197, 94, 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(34,197,94,0.3)'" onmouseout="this.style.background='rgba(34,197,94,0.2)'">
                            Export Data
                        </button>
                    </div>

                    <!-- 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: #059669; font-size: 1.25rem;">📋</span>
                            </div>
                            <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.75rem;">${isAdmin ? 'My/Total' : 'Total'} Discharges</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #059669; margin: 0;">${isAdmin ? this.getMyDischargeCount() + '/' + this.dischargeRecords.length : this.dischargeRecords.length}</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: #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;">Adoptions</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #2563eb; margin: 0;">${this.getOutcomeCount('Adoption')}</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;">TNR</h3>
                            <p style="font-size: 1.5rem; font-weight: bold; color: #7c3aed; margin: 0;">${this.getOutcomeCount('TNR')}</p>
                        </div>
                    </div>

                    <!-- My Discharge 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; margin-bottom: 1rem;">
                        <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem;">My Discharge Analytics (${this.getMyDischargeCount()})</h3>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Gender Breakdown</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-my-discharge-gender-chart"></canvas>
                                </div>
                            </div>
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Discharge Outcomes</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-my-discharge-outcome-chart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Age Distribution</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-my-discharge-age-chart"></canvas>
                                </div>
                            </div>
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Type Classification</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-my-discharge-type-chart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    ${isAdmin || (clawsData.userRoles && (clawsData.userRoles.includes('author') || clawsData.userRoles.includes('editor') || clawsData.userRoles.includes('administrator'))) ? `
                    <!-- All Discharge Charts (Authors+ Only) -->
                    <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;">All Discharge Analytics (${this.dischargeRecords.length})</h3>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Gender Breakdown</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-all-discharge-gender-chart"></canvas>
                                </div>
                            </div>
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Discharge Outcomes</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-all-discharge-outcome-chart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Age Distribution</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-all-discharge-age-chart"></canvas>
                                </div>
                            </div>
                            <div>
                                <h4 style="font-weight: 500; color: #374151; margin: 0 0 0.75rem; font-size: 0.875rem; text-align: center;">Type Classification</h4>
                                <div style="height: 200px; position: relative;">
                                    <canvas id="claws-all-discharge-type-chart"></canvas>
                                </div>
                            </div>
                        </div>
                    </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;">
                        <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem;">Recent Discharges</h3>
                        <div style="display: flex; flex-direction: column; gap: 0.75rem;">
            `;
            
            if (isAdmin) {
                // Admin view: Show "My Discharges" and "All Other Discharges"
                const myDischarges = sortedDischarges.filter(record => 
                    record.author_id == clawsData.userId || record.user_id == clawsData.userId
                ).slice(0, 10);
                
                const otherDischarges = sortedDischarges.filter(record => 
                    record.author_id != clawsData.userId && record.user_id != clawsData.userId
                ).slice(0, 10);
                
                // My Discharges section
                if (myDischarges.length > 0) {
                    html += `
                        <div style="margin-bottom: 1.5rem;">
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #3b82f6; padding-bottom: 0.5rem;">My Discharges (${myDischarges.length})</h4>
                            ${this.renderDischargeList(myDischarges)}
                        </div>
                    `;
                } else {
                    html += `
                        <div style="margin-bottom: 1.5rem;">
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #3b82f6; padding-bottom: 0.5rem;">My Discharges (0)</h4>
                            <p style="color: #6b7280; text-align: center; font-style: italic; margin: 1rem 0;">No discharge records found for you.</p>
                        </div>
                    `;
                }
                
                // All Other Discharges section
                if (otherDischarges.length > 0) {
                    html += `
                        <div>
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #6b7280; padding-bottom: 0.5rem;">All Other Discharges (${otherDischarges.length})</h4>
                            ${this.renderDischargeList(otherDischarges)}
                        </div>
                    `;
                } else {
                    html += `
                        <div>
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #6b7280; padding-bottom: 0.5rem;">All Other Discharges (0)</h4>
                            <p style="color: #6b7280; text-align: center; font-style: italic; margin: 1rem 0;">No other discharge records found.</p>
                        </div>
                    `;
                }
            } else {
                // Non-admin view: Show just their discharges
                const recentDischarges = sortedDischarges.slice(0, 20);
                html += this.renderDischargeList(recentDischarges);
            }
            
            html += `
                        </div>
                    </div>
                </div>
            `;
            
            container.innerHTML = html;
            
            // Update discharge charts after rendering
            setTimeout(() => {
                this.updateDischargeCharts();
            }, 100);
        },

        /**
         * Get count of my discharges (for admins)
         */
        getMyDischargeCount: function() {
            if (!this.dischargeRecords) return 0;
            return this.dischargeRecords.filter(record => 
                record.author_id == clawsData.userId || record.user_id == clawsData.userId
            ).length;
        },

        /**
         * Get count by outcome type
         */
        getOutcomeCount: function(outcome) {
            if (!this.dischargeRecords) return 0;
            return this.dischargeRecords.filter(record => 
                record.outcome === outcome
            ).length;
        },

        /**
         * Render a list of discharge records
         */
        renderDischargeList: function(discharges) {
            if (!discharges || discharges.length === 0) {
                return '<p style="color: #6b7280; text-align: center; font-style: italic;">No discharge records found.</p>';
            }
            
            return discharges.map(record => {
                const dischargeDate = new Date(record.discharge_date || record.date);
                const formattedDate = dischargeDate.toLocaleDateString();
                const catName = record.cat_name || record.name || 'Unknown Cat';
                const outcome = record.outcome || 'Unknown';
                
                // Color coding by outcome
                const statusColor = outcome === 'Adoption' ? '#059669' : 
                                   outcome === 'Foster to Adopt' ? '#059669' :
                                   outcome === 'TNR' ? '#7c3aed' : 
                                   outcome === 'Transfer' ? '#ea580c' : 
                                   outcome === 'Died' || outcome === 'Euthanasia' ? '#dc2626' :
                                   '#6b7280';
                const statusBg = outcome === 'Adoption' ? '#dcfce7' : 
                                outcome === 'Foster to Adopt' ? '#dcfce7' :
                                outcome === 'TNR' ? '#f3e8ff' : 
                                outcome === 'Transfer' ? '#fed7aa' : 
                                outcome === 'Died' || outcome === 'Euthanasia' ? '#fecaca' :
                                '#f3f4f6';
                
                return `
                    <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 0.75rem; margin-bottom: 0.5rem;">
                        <div style="display: flex; justify-content: space-between; align-items: start;">
                            <div>
                                <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.875rem;">${catName}</h4>
                                <p style="color: #6b7280; font-size: 0.75rem; margin: 0 0 0.25rem;">Discharged: ${formattedDate}</p>
                                ${record.notes ? `<p style="color: #9ca3af; font-size: 0.625rem; margin: 0;">${record.notes}</p>` : ''}
                            </div>
                            <span style="background: ${statusBg}; color: ${statusColor}; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.625rem; font-weight: 500;">${outcome}</span>
                        </div>
                    </div>
                `;
            }).join('');
        },

        /**
         * Initialize neonate tracker
         */
        initNeonateTracker: function() {
            
            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 -->
                    <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;">
                                        <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;">
                                        <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 3 hrs</td>
                                    </tr>
                                    <tr style="border-bottom: 1px solid #f3f4f6;">
                                        <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 4 hrs</td>
                                    </tr>
                                    <tr>
                                        <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 5 hrs</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Add New Feeding Record -->
                    <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; margin-bottom: 1.5rem;">
                            <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>
                        
                        <!-- 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>
                        
                        <!-- Date and Time -->
                        <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>
                        
                        <!-- Weight inputs -->
                        <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>
                        
                        <!-- Notes -->
                        <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 -->
                        <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;">
                                    <input type="radio" name="chartDisplayMode" value="smooth" checked style="margin-right: 0.5rem; accent-color: #3b82f6;">
                                    <span style="font-weight: 600; color: #374151;">📊 Smooth (Post Weights Only)</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;">
                                    <input type="radio" name="chartDisplayMode" value="sawtooth" style="margin-right: 0.5rem; accent-color: #3b82f6;">
                                    <span style="font-weight: 600; color: #374151;">📈 Sawtooth (Pre & Post Weights)</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 -->
                    <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);">
                                <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);">
                                <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];
            this.chartDisplayMode = 'sawtooth';
            
            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': ['7:00 AM', '12:00 PM', '5:00 PM', '10:00 PM', '3:00 AM']
            };
            
            this.setupNeonateEventListeners();
            this.initializeDateTimeInputs();
            this.updateWeightChart();
        },

        /**
         * 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');
            
            if (dateInput && !dateInput.value) {
                dateInput.value = now.toISOString().split('T')[0];
            }
            
            if (timeInput) {
                const hours = now.getHours().toString().padStart(2, '0');
                const minutes = now.getMinutes().toString().padStart(2, '0');
                timeInput.value = `${hours}:${minutes}`;
            }
        },

        /**
         * Setup event listeners for neonate care
         */
        setupNeonateEventListeners: function() {            
            document.querySelectorAll('input[name="chartDisplayMode"]').forEach(radio => {
                radio.addEventListener('change', (e) => {
                    if (e.target.checked) {
                        this.chartDisplayMode = e.target.value;
                        this.updateWeightChart();
                        this.updateRecentRecords(); // Update feeding records display when mode changes
                    }
                });
            });
        },

        /**
         * Load feeding data
         */
        loadFeedingData: async function() {
            try {
                // Load feeding records
                const feedingResponse = await fetch(`${clawsData.apiUrl}feedings`, {
                    headers: {
                        'X-WP-Nonce': clawsData.nonce,
                        'Content-Type': 'application/json'
                    }
                });

                // Load baby kittens
                const kittensResponse = await fetch(`${clawsData.apiUrl}baby-kittens`, {
                    headers: {
                        'X-WP-Nonce': clawsData.nonce,
                        'Content-Type': 'application/json'
                    }
                });

                if (feedingResponse.ok && kittensResponse.ok) {
                    this.feedingRecords = await feedingResponse.json() || [];
                    this.babyKittens = await kittensResponse.json() || [];
                    
                    this.populateKittenDropdown();
                    this.updateKittenCheckboxes();
                    this.updateRecentRecords();
                    this.updateWeightChart();
                } else {
                    this.feedingRecords = [];
                    this.babyKittens = [];
                }
            } catch (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;
            }

            const feedingData = {
                kitten_name: kittenName,
                feeding_date: feedingDate,
                feeding_time: feedingTime,
                pre_weight: parseInt(preWeight),
                post_weight: parseInt(postWeight),
                notes: notes || ''
            };

            this.showLoading('Saving feeding record...');

            try {
                const response = await fetch(`${clawsData.apiUrl}feeding`, {
                    method: 'POST',
                    headers: {
                        'X-WP-Nonce': clawsData.nonce,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(feedingData)
                });

                if (response.ok) {
                    this.showAlert('Feeding record saved successfully!', 'success');
                    this.clearFeedingForm();
                    this.loadFeedingData();
                } else {
                    const errorText = await response.text();
                    throw new Error(`Failed to save feeding record: ${response.status} - ${errorText}`);
                }
            } catch (error) {
                this.showAlert('An error occurred while saving the record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Clear feeding form
         */
        clearFeedingForm: function() {
            document.getElementById('neonate-pre-weight').value = '';
            document.getElementById('neonate-post-weight').value = '';
            document.getElementById('neonate-notes').value = '';
            this.initializeDateTimeInputs();
        },

        /**
         * Populate kitten dropdown
         */
        populateKittenDropdown: function() {
            const dropdown = document.getElementById('neonate-kitten-name');
            if (!dropdown) return;

            dropdown.innerHTML = '<option value="">Select a kitten...</option>';
            
            if (this.babyKittens && this.babyKittens.length > 0) {
                this.babyKittens.forEach(kitten => {
                    const option = document.createElement('option');
                    option.value = kitten.name;
                    option.textContent = kitten.name;
                    dropdown.appendChild(option);
                });
            }
        },

        /**
         * Update kitten checkboxes
         */
        updateKittenCheckboxes: function() {
            const container = document.getElementById('neonate-kitten-checkboxes');
            if (!container) return;

            container.innerHTML = '';
            
            if (this.babyKittens && this.babyKittens.length > 0) {
                this.babyKittens.forEach(kitten => {
                    const checkboxDiv = document.createElement('div');
                    checkboxDiv.innerHTML = `
                        <label style="display: flex; align-items: center; cursor: pointer; padding: 0.5rem; border: 2px solid #e5e7eb; border-radius: 0.5rem; background: white;">
                            <input type="checkbox" value="${kitten.name}" checked style="margin-right: 0.5rem; accent-color: #3b82f6;">
                            <span style="font-weight: 600; color: #374151;">${kitten.name}</span>
                        </label>
                    `;
                    
                    const checkbox = checkboxDiv.querySelector('input');
                    checkbox.addEventListener('change', () => {
                        this.updateWeightChart();
                    });
                    
                    container.appendChild(checkboxDiv);
                });
            }
        },

        /**
         * Update recent records display
         */
        updateRecentRecords: function() {
            const container = document.getElementById('neonate-recent-records');
            if (!container) return;
            
            if (this.feedingRecords.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #6b7280; padding: 2rem;">No feeding records found.</p>';
                return;
            }

            // Sort all records chronologically for proper gain calculation
            const sortedRecords = this.feedingRecords
                .sort((a, b) => new Date(a.feeding_date + ' ' + a.feeding_time) - new Date(b.feeding_date + ' ' + b.feeding_time));
            
            // Check if we're in sawtooth mode
            const isSawtoothMode = document.querySelector('input[name="chartDisplayMode"][value="sawtooth"]')?.checked || false;
            
            const recordsHtml = sortedRecords
                .slice(-20) // Get last 20 records
                .reverse() // Show newest first
                .map((record, index, displayArray) => {
                    // Calculate weight change between feeds (always shown as "Gain")
                    const allRecordsForKitten = sortedRecords.filter(r => r.kitten_name === record.kitten_name);
                    const currentIndex = allRecordsForKitten.findIndex(r => r.id === record.id);
                    
                    let betweenFeedsChange = 0;
                    let gainColor = '#6b7280';
                    let gainText = '0g';
                    
                    if (currentIndex > 0) {
                        const previousRecord = allRecordsForKitten[currentIndex - 1];
                        betweenFeedsChange = record.pre_weight - previousRecord.post_weight;
                        gainColor = betweenFeedsChange > 0 ? '#10b981' : (betweenFeedsChange < 0 ? '#ef4444' : '#6b7280');
                        gainText = `${betweenFeedsChange > 0 ? '+' : ''}${betweenFeedsChange}g`;
                    } else {
                        gainText = '0g (first)';
                    }
                    
                    // Calculate per-feeding weight change (pre to post) - only shown in sawtooth mode
                    const perFeedGain = record.post_weight - record.pre_weight;
                    const perFeedColor = perFeedGain > 0 ? '#10b981' : '#ef4444';
                    const perFeedText = `${perFeedGain > 0 ? '+' : ''}${perFeedGain}g`;
                    
                    // Determine grid layout based on mode
                    const gridColumns = isSawtoothMode ? 'repeat(4, 1fr)' : 'repeat(3, 1fr)';
                    
                    return `
                        <div style="border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 1rem; margin-bottom: 0.75rem; background: #f9fafb;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                                <span style="font-weight: 600; color: #1f2937;">${record.kitten_name}</span>
                                <div style="display: flex; align-items: center; gap: 0.5rem;">
                                    <span style="font-size: 0.875rem; color: #6b7280;">${record.feeding_date} ${record.feeding_time}</span>
                                    <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;">Edit</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;">Delete</button>
                                </div>
                            </div>
                            <div style="display: grid; grid-template-columns: ${gridColumns}; gap: 1rem; font-size: 0.875rem;">
                                <div>
                                    <span style="color: #6b7280;">Pre: </span>
                                    <span style="font-weight: 600;">${record.pre_weight}g</span>
                                </div>
                                <div>
                                    <span style="color: #6b7280;">Post: </span>
                                    <span style="font-weight: 600;">${record.post_weight}g</span>
                                </div>
                                <div>
                                    <span style="color: #6b7280;">Gain: </span>
                                    <span style="font-weight: 600; color: ${gainColor};">${gainText}</span>
                                </div>
                                ${isSawtoothMode ? `
                                <div>
                                    <span style="color: #6b7280;">Pre/Post: </span>
                                    <span style="font-weight: 600; color: ${perFeedColor};">${perFeedText}</span>
                                </div>
                                ` : ''}
                            </div>
                            ${record.notes ? `<div style="margin-top: 0.5rem; font-size: 0.875rem; color: #6b7280; font-style: italic;">${record.notes}</div>` : ''}
                        </div>
                    `;
                }).join('');

            container.innerHTML = recordsHtml;
        },

        /**
         * Update weight chart
         */
        updateWeightChart: function() {
            const canvas = document.getElementById('neonate-weight-chart');
            if (!canvas) return;

            const ctx = canvas.getContext('2d');
            
            if (this.neonateWeightChart) {
                this.neonateWeightChart.destroy();
                this.neonateWeightChart = null;
            }

            const selectedKittens = this.getSelectedKittens();
            if (selectedKittens.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '16px Arial';
                ctx.fillStyle = '#6b7280';
                ctx.textAlign = 'center';
                ctx.fillText('No kittens selected', canvas.width / 2, canvas.height / 2);
                return;
            }

            const datasets = this.createChartDatasets(selectedKittens);
            
            this.neonateWeightChart = new Chart(ctx, {
                type: 'line',
                data: { datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Kitten Weight Progress Over Time'
                        },
                        legend: {
                            position: 'top'
                        }
                    },
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                unit: 'day',
                                displayFormats: {
                                    day: 'MMM dd'
                                }
                            },
                            title: {
                                display: true,
                                text: 'Date'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Weight (grams)'
                            }
                        }
                    }
                }
            });
        },

        /**
         * Get selected kittens from checkboxes
         */
        getSelectedKittens: function() {
            const checkboxes = document.querySelectorAll('#neonate-kitten-checkboxes input[type="checkbox"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        },

        /**
         * Create chart datasets
         */
        createChartDatasets: function(selectedKittens) {
            const datasets = [];
            const colors = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#06b6d4'];
            
            selectedKittens.forEach((kittenName, index) => {
                const kittenRecords = this.feedingRecords
                    .filter(record => record.kitten_name === kittenName)
                    .sort((a, b) => new Date(a.feeding_date + ' ' + a.feeding_time) - new Date(b.feeding_date + ' ' + b.feeding_time));

                if (kittenRecords.length === 0) return;

                const color = colors[index % colors.length];
                
                if (this.chartDisplayMode === 'sawtooth') {
                    const preWeightData = [];
                    const postWeightData = [];
                    
                    kittenRecords.forEach(record => {
                        const datetime = new Date(record.feeding_date + ' ' + record.feeding_time);
                        preWeightData.push({ x: datetime, y: record.pre_weight });
                        postWeightData.push({ x: datetime, y: record.post_weight });
                    });

                    datasets.push({
                        label: `${kittenName} (Pre)`,
                        data: preWeightData,
                        borderColor: color,
                        backgroundColor: color + '20',
                        fill: false,
                        borderDash: [5, 5]
                    });

                    datasets.push({
                        label: `${kittenName} (Post)`,
                        data: postWeightData,
                        borderColor: color,
                        backgroundColor: color + '20',
                        fill: false
                    });
                } else {
                    const postWeightData = kittenRecords.map(record => ({
                        x: new Date(record.feeding_date + ' ' + record.feeding_time),
                        y: record.post_weight
                    }));

                    datasets.push({
                        label: kittenName,
                        data: postWeightData,
                        borderColor: color,
                        backgroundColor: color + '20',
                        fill: false
                    });
                }
            });

            return datasets;
        },

        /**
         * Export feeding data
         */
        exportFeedingData: function() {
            if (this.feedingRecords.length === 0) {
                this.showAlert('No feeding data to export.', 'warning');
                return;
            }

            const csvHeaders = ['Kitten Name', 'Date', 'Time', 'Pre Weight (g)', 'Post Weight (g)', 'Weight Gain (g)', 'Notes'];
            const csvRows = this.feedingRecords.map(record => [
                record.kitten_name,
                record.feeding_date,
                record.feeding_time,
                record.pre_weight,
                record.post_weight,
                record.post_weight - record.pre_weight,
                record.notes || ''
            ]);

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

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

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

        /**
         * 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!`;
            
            // Create a proper modal instead of using alert() which can truncate content
            const modal = document.createElement('div');
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;">
                    <div style="background: white; border-radius: 8px; padding: 2rem; max-width: 600px; 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: 1rem;">
                            <h2 style="margin: 0; color: #1f2937; font-size: 1.25rem;">Care Guide</h2>
                            <button onclick="this.closest('div[style*=\"position: fixed\"]').remove()" style="background: #ef4444; color: white; border: none; border-radius: 4px; padding: 0.5rem; cursor: pointer; font-size: 1rem;">✕</button>
                        </div>
                        <pre style="white-space: pre-wrap; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #374151; line-height: 1.5; margin: 0;">${guidelines}</pre>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // Close modal when clicking outside
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        },

        /**
         * Edit feeding record
         */
        editFeedingRecord: function(recordId) {
            const record = this.feedingRecords.find(r => r.id == recordId);
            if (!record) {
                this.showAlert('Feeding record not found', 'error');
                return;
            }

            // Populate the form with the record data
            const kittenSelect = document.getElementById('neonate-kitten-name');
            const dateInput = document.getElementById('neonate-feeding-date');
            const timeInput = document.getElementById('neonate-feeding-time');
            const preWeightInput = document.getElementById('neonate-pre-weight');
            const postWeightInput = document.getElementById('neonate-post-weight');
            const notesInput = document.getElementById('neonate-notes');
            const saveButton = document.querySelector('button[onclick="CLAWSApp.saveFeedingRecord()"]');

            if (kittenSelect) kittenSelect.value = record.kitten_name;
            if (dateInput) dateInput.value = record.feeding_date;
            if (timeInput) timeInput.value = record.feeding_time;
            if (preWeightInput) preWeightInput.value = record.pre_weight;
            if (postWeightInput) postWeightInput.value = record.post_weight;
            if (notesInput) notesInput.value = record.notes || '';

            // Change save button to update mode
            if (saveButton) {
                saveButton.innerHTML = '💾 Update Record';
                saveButton.onclick = () => this.updateFeedingRecord(recordId);
            }

            // Scroll to form
            const form = document.querySelector('#neonate-kitten-name').closest('div').closest('div');
            if (form) {
                form.scrollIntoView({ behavior: 'smooth' });
            }

            this.showAlert('Editing record - update the fields and click "Update Record"', 'info');
        },

        /**
         * 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 || !preWeight || !postWeight || !feedingDate || !feedingTime) {
                this.showAlert('Please fill in all required fields.', 'error');
                return;
            }

            try {
                const response = await fetch(`${clawsData.apiUrl}feedings/${recordId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': clawsData.nonce
                    },
                    body: JSON.stringify({
                        kitten_name: kittenName,
                        pre_weight: parseFloat(preWeight),
                        post_weight: parseFloat(postWeight),
                        feeding_date: feedingDate,
                        feeding_time: feedingTime,
                        notes: notes
                    })
                });

                if (response.ok) {
                    this.showAlert('Feeding record updated successfully!', 'success');
                    this.clearFeedingForm();
                    this.loadFeedingData();
                    
                    // Reset save button
                    const saveButton = document.querySelector('button[onclick^="CLAWSApp.updateFeedingRecord"]');
                    if (saveButton) {
                        saveButton.innerHTML = '💾 Save Record';
                        saveButton.onclick = () => this.saveFeedingRecord();
                    }
                } else {
                    const errorText = await response.text();
                    throw new Error(`Failed to update feeding record: ${response.status} - ${errorText}`);
                }

            } catch (error) {
                this.showAlert('Failed to update feeding record. Please try again.', 'error');
            }
        },

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

            try {
                const response = await fetch(`${clawsData.apiUrl}feedings/${recordId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-WP-Nonce': clawsData.nonce
                    }
                });

                if (response.ok) {
                    this.showAlert('Feeding record deleted successfully!', 'success');
                    this.loadFeedingData();
                } else {
                    const errorText = await response.text();
                    throw new Error(`Failed to delete feeding record: ${response.status} - ${errorText}`);
                }

            } catch (error) {
                this.showAlert('Failed to delete feeding record. Please try again.', 'error');
            }
        },

        /**
         * Load volunteer content (restored from backup)
         */
        loadVolunteerContent: function() {
            
            // Set default sub-tab to My Time
            this.currentVolunteerSubTab = 'mytime';
            
            // Initialize sub-tab content if needed
            this.switchVolunteerSubTab('mytime');
        },

        /**
         * Load my time content
         */
        loadMyTimeContent: function() {
            // Placeholder - implement my time content
        },

        /**
         * 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;">My/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; margin-bottom: 0.5rem;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                            New Cat Intake
                        </button>
                        <button onclick="CLAWSApp.exportIntakeData()" style="width: 100%; background: rgba(34, 197, 94, 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(34,197,94,0.3)'" onmouseout="this.style.background='rgba(34,197,94,0.2)'">
                            Export Data
                        </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>
                </div>
            `;
        },

        /**
         * Load intake data - RESTORED ORIGINAL FROM BACKUP
         */
        loadIntakeData: async function() {
            try {
                const timestamp = new Date().getTime();
                const randomParam = Math.random().toString(36).substring(7);
                
                // Check if user is admin to determine which intakes to fetch
                const isAdmin = clawsData.userRoles && (
                    clawsData.userRoles.includes('administrator') || 
                    clawsData.userRoles.includes('editor')
                );
                
                
                // Fetch intakes (admin gets all intakes, non-admin gets only their own)
                const intakeEndpoint = isAdmin ? 
                    this.config.apiUrl + 'admin/intakes' : 
                    this.config.apiUrl + 'intakes';
                
                const intakeResponse = await fetch(intakeEndpoint + '?_=' + 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'
                    }
                });
                
                // Fetch discharges (admin gets all discharges, non-admin gets only their own)
                const dischargeEndpoint = isAdmin ? 
                    this.config.apiUrl + 'admin/discharges' : 
                    this.config.apiUrl + 'discharges';
                
                const dischargeResponse = await fetch(dischargeEndpoint + '?_=' + timestamp + '&r2=' + randomParam, {
                    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'
                    }
                });
                
                if (intakeResponse.ok) {
                    const intakeData = await intakeResponse.json();
                    this.intakeRecords = Array.isArray(intakeData) ? intakeData : [];
                } else {
                    throw new Error(`Failed to load intakes: HTTP ${intakeResponse.status}`);
                }
                
                if (dischargeResponse.ok) {
                    const dischargeData = await dischargeResponse.json();
                    this.dischargeRecords = Array.isArray(dischargeData) ? dischargeData : [];
                } else {
                    this.dischargeRecords = [];
                }
                
                // Link discharge data to intake records by cat name
                this.linkDischargeData();
                
            } catch (error) {
                this.intakeRecords = [];
                this.dischargeRecords = [];
            }
            
            this.updateIntakeStats();
            this.updateRecentIntakes();
        },

        /**
         * Link discharge data to intake records by cat name
         */
        linkDischargeData: function() {
            if (!this.dischargeRecords || this.dischargeRecords.length === 0) {
                // No discharge records available - all intakes are active
                this.intakeRecords.forEach(intake => {
                    intake.discharged = false;
                    intake.status = 'active';
                });
                return;
            }
            
            // Create a lookup map of discharge records by cat name
            const dischargeMap = {};
            this.dischargeRecords.forEach(discharge => {
                const catName = (discharge.cat_name || '').toLowerCase().trim();
                if (catName) {
                    dischargeMap[catName] = discharge;
                }
            });
            
            // Link discharge data to intake records
            this.intakeRecords.forEach(intake => {
                const catName = (intake.cat_name || intake.name || '').toLowerCase().trim();
                const matchingDischarge = dischargeMap[catName];
                
                if (matchingDischarge) {
                    // Add discharge information to intake record
                    intake.discharge_date = matchingDischarge.discharge_date;
                    intake.discharge_type = matchingDischarge.outcome;
                    intake.discharged = true;
                    intake.status = 'discharged';
                } else {
                    // No discharge found - cat is still active
                    intake.discharged = false;
                    intake.status = 'active';
                }
            });
        },

        /**
         * Update intake statistics with My/Total breakdown for admins
         */
        updateIntakeStats: function() {
            
            if (!this.intakeRecords || !Array.isArray(this.intakeRecords)) {
                this.intakeRecords = [];
            }
            
            // Check if user is admin
            const isAdmin = clawsData.userRoles && (
                clawsData.userRoles.includes('administrator') || 
                clawsData.userRoles.includes('editor')
            );
            
            // Calculate time-based statistics
            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);
            
            // Separate my intakes vs all intakes for admins
            let myIntakes, myWeekIntakes, myMonthIntakes;
            
            if (isAdmin) {
                myIntakes = this.intakeRecords.filter(record => 
                    record.author == clawsData.userId || record.user_id == clawsData.userId
                );
                
                myWeekIntakes = myIntakes.filter(record => {
                    const intakeDate = new Date(record.intake_date || record.date);
                    return intakeDate >= weekAgo;
                }).length;
                
                myMonthIntakes = myIntakes.filter(record => {
                    const intakeDate = new Date(record.intake_date || record.date);
                    return intakeDate >= monthAgo;
                }).length;
            }
            
            const weekIntakes = this.intakeRecords.filter(record => {
                const intakeDate = new Date(record.intake_date || record.date);
                return intakeDate >= weekAgo;
            }).length;
            
            const monthIntakes = this.intakeRecords.filter(record => {
                const intakeDate = new Date(record.intake_date || record.date);
                return intakeDate >= monthAgo;
            }).length;
            
            // Update statistics display
            const totalElement = document.getElementById('claws-total-intakes');
            const weekElement = document.getElementById('claws-week-intakes');
            const monthElement = document.getElementById('claws-month-intakes');
            
            if (isAdmin) {
                // Show "My/Total" format for admins
                if (totalElement) totalElement.textContent = `${myIntakes.length}/${this.intakeRecords.length}`;
                if (weekElement) weekElement.textContent = `${myWeekIntakes}/${weekIntakes}`;
                if (monthElement) monthElement.textContent = `${myMonthIntakes}/${monthIntakes}`;
            } else {
                // Show just totals for regular users
                if (totalElement) totalElement.textContent = this.intakeRecords.length;
                if (weekElement) weekElement.textContent = weekIntakes;
                if (monthElement) monthElement.textContent = monthIntakes;
            }
            
            if (isAdmin) {
            }
        },

        /**
         * Update recent intakes display with admin-level sections
         */
        updateRecentIntakes: function() {
            
            const container = document.getElementById('claws-recent-intakes');
            if (!container) return;
            
            if (!this.intakeRecords || this.intakeRecords.length === 0) {
                container.innerHTML = '<p style="color: #6b7280; text-align: center; font-style: italic;">No intake records found.</p>';
                return;
            }
            
            // Check if user is admin
            const isAdmin = clawsData.userRoles && (
                clawsData.userRoles.includes('administrator') || 
                clawsData.userRoles.includes('editor')
            );
            
            // Sort by date (newest first)
            const sortedIntakes = this.intakeRecords
                .sort((a, b) => new Date(b.intake_date || b.date) - new Date(a.intake_date || a.date));
            
            let html = '';
            
            if (isAdmin) {
                // Admin view: Show "My Intakes" and "All Other Intakes"
                const myIntakes = sortedIntakes.filter(record => 
                    record.author == clawsData.userId || record.user_id == clawsData.userId
                ).slice(0, 10);
                
                const otherIntakes = sortedIntakes.filter(record => 
                    record.author != clawsData.userId && record.user_id != clawsData.userId
                ).slice(0, 10);
                
                
                // My Intakes section
                if (myIntakes.length > 0) {
                    html += `
                        <div style="margin-bottom: 1.5rem;">
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #3b82f6; padding-bottom: 0.5rem;">My Intakes (${myIntakes.length})</h4>
                            ${this.renderIntakeList(myIntakes)}
                        </div>
                    `;
                } else {
                    html += `
                        <div style="margin-bottom: 1.5rem;">
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #3b82f6; padding-bottom: 0.5rem;">My Intakes (0)</h4>
                            <p style="color: #6b7280; text-align: center; font-style: italic; margin: 1rem 0;">No intake records found for you.</p>
                        </div>
                    `;
                }
                
                // All Other Intakes section
                if (otherIntakes.length > 0) {
                    html += `
                        <div>
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #6b7280; padding-bottom: 0.5rem;">All Other Intakes (${otherIntakes.length})</h4>
                            ${this.renderIntakeList(otherIntakes)}
                        </div>
                    `;
                } else {
                    html += `
                        <div>
                            <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem; border-bottom: 2px solid #6b7280; padding-bottom: 0.5rem;">All Other Intakes (0)</h4>
                            <p style="color: #6b7280; text-align: center; font-style: italic; margin: 1rem 0;">No other intake records found.</p>
                        </div>
                    `;
                }
                
                if (myIntakes.length === 0 && otherIntakes.length === 0) {
                    html = '<p style="color: #6b7280; text-align: center; font-style: italic;">No intake records found.</p>';
                }
            } else {
                // Non-admin view: Show just their intakes (top 20)
                const recentIntakes = sortedIntakes.slice(0, 20);
                html = this.renderIntakeList(recentIntakes);
            }
            
            container.innerHTML = html;
        },

        /**
         * Render a list of intake records
         */
        renderIntakeList: function(intakes) {
            return intakes.map(record => {
                const intakeDate = new Date(record.intake_date || record.date);
                const formattedDate = intakeDate.toLocaleDateString();
                const catName = record.cat_name || record.name || 'Unknown Cat';
                const age = record.age || record.age_category || 'Unknown age';
                
                // Determine status based on discharge information
                const isActive = !record.discharge_date && !record.discharged && (!record.status || record.status === 'active');
                const dischargeDate = record.discharge_date;
                const dischargeType = record.discharge_type || record.outcome;
                
                let statusDisplay = '';
                if (isActive) {
                    statusDisplay = '<span style="background: #dbeafe; color: #1e40af; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.625rem; font-weight: 500;">Active</span>';
                } else {
                    // Cat has been discharged - use color coding by outcome
                    const statusColor = dischargeType === 'Adoption' ? '#059669' : 
                                       dischargeType === 'Foster to Adopt' ? '#059669' :
                                       dischargeType === 'TNR' || dischargeType === 'Return to Colony' ? '#7c3aed' : 
                                       dischargeType === 'Transfer' ? '#ea580c' : 
                                       dischargeType === 'Died' || dischargeType === 'Euthanasia' ? '#dc2626' :
                                       '#6b7280';
                    const statusBg = dischargeType === 'Adoption' ? '#dcfce7' : 
                                    dischargeType === 'Foster to Adopt' ? '#dcfce7' :
                                    dischargeType === 'TNR' || dischargeType === 'Return to Colony' ? '#f3e8ff' : 
                                    dischargeType === 'Transfer' ? '#fed7aa' : 
                                    dischargeType === 'Died' || dischargeType === 'Euthanasia' ? '#fecaca' :
                                    '#f3f4f6';
                    const statusText = dischargeType || 'Discharged';
                    
                    statusDisplay = `<span style="background: ${statusBg}; color: ${statusColor}; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.625rem; font-weight: 500;">${statusText}</span>`;
                }
                
                return `
                    <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 0.75rem; margin-bottom: 0.5rem;">
                        <div style="display: flex; justify-content: space-between; align-items: start;">
                            <div>
                                <h4 style="font-weight: 600; color: #1f2937; margin: 0 0 0.25rem; font-size: 0.875rem;">${catName}</h4>
                                <p style="color: #6b7280; font-size: 0.75rem; margin: 0 0 0.25rem;">${age}</p>
                                <p style="color: #9ca3af; font-size: 0.625rem; margin: 0;">Intake: ${formattedDate}</p>
                                ${dischargeDate ? `<p style="color: #9ca3af; font-size: 0.625rem; margin: 0;">Discharged: ${new Date(dischargeDate).toLocaleDateString()}</p>` : ''}
                            </div>
                            ${statusDisplay}
                        </div>
                    </div>
                `;
            }).join('');
        },

        /**
         * Load team content
         */
        loadTeamContent: function() {
            // Placeholder - implement team content
        },

        /**
         * Load volunteer stats
         */
        loadVolunteerStats: function() {
            this.loadPersonalStats();
            
            // Load org stats if admin
            const isAdmin = document.getElementById('claws-org-stats-grid');
            if (isAdmin) {
                this.loadOrganizationStats();
                this.loadTopVolunteers();
            }
        },
        
        /**
         * Load personal volunteer stats
         */
        loadPersonalStats: function() {
            console.log('=== LOAD PERSONAL STATS STARTED ===');
            const container = document.getElementById('claws-personal-stats-grid');
            if (!container) {
                console.log('❌ Personal stats container not found');
                return;
            }
            
            console.log('✅ Container found, fetching stats...');
            
            fetch(window.wpApiSettings.root + 'claws/v1/stats/personal', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => {
                console.log('Stats API response status:', response.status);
                return response.json();
            })
            .then(stats => {
                console.log('Personal stats received:', stats);
                container.innerHTML = this.renderStatsGrid(stats, 'personal');
                
                // Show recent activity if available
                if (stats.recent_activity && stats.recent_activity.length > 0) {
                    console.log('Recent activity:', stats.recent_activity);
                    document.getElementById('claws-personal-details').style.display = 'block';
                    document.getElementById('claws-recent-activity').innerHTML = 
                        this.renderRecentActivity(stats.recent_activity);
                } else {
                    console.log('No recent activity found');
                }
            })
            .catch(error => {
                console.error('❌ Error loading personal stats:', error);
                container.innerHTML = `
                    <div style="grid-column: 1/-1; text-align: center; padding: 2rem; background: #fef2f2; border-radius: 0.75rem;">
                        <p style="color: #991b1b; margin: 0;">Failed to load stats</p>
                    </div>
                `;
            });
        },
        
        /**
         * Load organization stats (admin only)
         */
        loadOrganizationStats: function() {
            const container = document.getElementById('claws-org-stats-grid');
            if (!container) return;
            
            fetch(window.wpApiSettings.root + 'claws/v1/stats/organization', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(stats => {
                container.innerHTML = this.renderStatsGrid(stats, 'organization');
            })
            .catch(error => {
                console.error('Error loading org stats:', error);
                container.innerHTML = `
                    <div style="grid-column: 1/-1; text-align: center; padding: 2rem; background: #fef2f2; border-radius: 0.75rem;">
                        <p style="color: #991b1b; margin: 0;">Failed to load organization stats</p>
                    </div>
                `;
            });
        },
        
        /**
         * Load top volunteers (admin only)
         */
        loadTopVolunteers: function() {
            const container = document.getElementById('claws-top-volunteers');
            if (!container) return;
            
            fetch(window.wpApiSettings.root + 'claws/v1/stats/top-volunteers', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(volunteers => {
                if (!volunteers || volunteers.length === 0) {
                    container.innerHTML = '<p style="color: #6b7280; text-align: center; margin: 0;">No volunteer data yet</p>';
                    return;
                }
                
                let html = '<div style="display: grid; gap: 1rem;">';
                volunteers.forEach((volunteer, index) => {
                    const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '🏅';
                    html += `
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 1rem; background: #f9fafb; border-radius: 0.5rem; border-left: 4px solid ${index === 0 ? '#f59e0b' : index === 1 ? '#9ca3af' : index === 2 ? '#cd7f32' : '#e5e7eb'};">
                            <div style="display: flex; align-items: center; gap: 1rem;">
                                <span style="font-size: 1.5rem;">${medal}</span>
                                <div>
                                    <p style="margin: 0; font-weight: 600; color: #1f2937;">${volunteer.name}</p>
                                    <p style="margin: 0; font-size: 0.75rem; color: #6b7280;">${volunteer.hours} hours volunteered</p>
                                </div>
                            </div>
                            <div style="text-align: right;">
                                <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${volunteer.tasks_completed} tasks</p>
                                <p style="margin: 0; font-size: 0.875rem; color: #6b7280;">${volunteer.events_attended} events</p>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            })
            .catch(error => {
                console.error('Error loading top volunteers:', error);
                container.innerHTML = '<p style="color: #991b1b; text-align: center; margin: 0;">Failed to load top volunteers</p>';
            });
        },
        
        /**
         * Render stats grid
         */
        renderStatsGrid: function(stats, type) {
            // Define stat cards with different labels for personal vs organization
            const statCards = [
                { key: 'hours_volunteered', label: 'Hours Volunteered', icon: '⏰', color: '#3b82f6' },
                { key: 'tasks_completed', label: 'Tasks Completed', icon: '✅', color: '#10b981' },
                { 
                    key: 'events_participated', 
                    label: type === 'organization' ? 'Events Organized' : 'Events Attended', 
                    icon: '📅', 
                    color: '#8b5cf6' 
                },
                { 
                    key: 'projects_participated', 
                    label: type === 'organization' ? 'Projects Initiated' : 'Projects Joined', 
                    icon: '🔄', 
                    color: '#f59e0b' 
                },
                { key: 'cats_fostered', label: 'Cats Fostered', icon: '🏠', color: '#ec4899' },
                { key: 'bottle_babies', label: 'Bottle Babies', icon: '🍼', color: '#06b6d4' },
                { key: 'adoptions_facilitated', label: 'Adoptions Facilitated', icon: '❤️', color: '#ef4444' },
                { key: 'tnr_assists', label: 'TNR Assists', icon: '🎯', color: '#84cc16' },
                { key: 'shelter_transfers', label: 'Shelter Transfers', icon: '🏥', color: '#8b5cf6' }
            ];
            
            // Add org-specific stats for organization view
            if (type === 'organization') {
                statCards.push(
                    { key: 'total_volunteers', label: 'Total Volunteers', icon: '👥', color: '#6366f1' },
                    { key: 'active_teams', label: 'Active Teams', icon: '🤝', color: '#a855f7' },
                    { key: 'upcoming_events', label: 'Upcoming Events', icon: '📆', color: '#0ea5e9' },
                    { key: 'active_projects', label: 'Active Projects', icon: '🔧', color: '#f97316' }
                );
            }
            
            let html = '';
            statCards.forEach(card => {
                const value = stats[card.key] !== undefined ? stats[card.key] : 0;
                html += `
                    <div style="background: white; border-radius: 0.75rem; border: 1px solid #e5e7eb; padding: 1.5rem; position: relative; overflow: hidden;">
                        <div style="position: absolute; top: 0; right: 0; width: 80px; height: 80px; background: ${card.color}15; border-radius: 0 0 0 100%;"></div>
                        <div style="position: relative;">
                            <div style="font-size: 2rem; margin-bottom: 0.5rem;">${card.icon}</div>
                            <div style="font-size: 2rem; font-weight: 700; color: #1f2937; margin-bottom: 0.25rem;">${value}</div>
                            <div style="font-size: 0.875rem; color: #6b7280; font-weight: 500;">${card.label}</div>
                        </div>
                    </div>
                `;
            });
            
            return html;
        },
        
        /**
         * Render recent activity
         */
        renderRecentActivity: function(activities) {
            let html = '<div style="display: grid; gap: 0.75rem;">';
            
            activities.slice(0, 5).forEach(activity => {
                const icon = activity.type === 'event' ? '📅' : 
                             activity.type === 'project' ? '🔄' : 
                             activity.type === 'task' ? '✅' : '📌';
                
                html += `
                    <div style="display: flex; gap: 1rem; padding: 0.75rem; background: #f9fafb; border-radius: 0.5rem; border-left: 3px solid #3b82f6;">
                        <span style="font-size: 1.25rem;">${icon}</span>
                        <div style="flex: 1;">
                            <p style="margin: 0; font-weight: 600; color: #1f2937; font-size: 0.875rem;">${activity.title}</p>
                            <p style="margin: 0; color: #6b7280; font-size: 0.75rem;">${activity.date}</p>
                        </div>
                        ${activity.hours ? `<div style="text-align: right; color: #3b82f6; font-weight: 600; font-size: 0.875rem;">${activity.hours}h</div>` : ''}
                    </div>
                `;
            });
            
            html += '</div>';
            return html;
        },

        /**
         * Show system analytics
         */
        showSystemAnalytics: function() {
            // Placeholder - implement system analytics
        },

        /**
         * Export intake data as CSV
         */
        exportIntakeData: function() {
            
            if (!this.intakeRecords || this.intakeRecords.length === 0) {
                alert('No intake data available to export.');
                return;
            }

            // Create CSV content
            const headers = ['Date', 'Cat Name', 'Age', 'Age Category', 'Gender', 'Source', 'Intake Condition', 'Colony', 'Added By', 'Status'];
            
            const csvContent = [
                headers.join(','),
                ...this.intakeRecords.map(record => {
                    const intakeDate = new Date(record.intake_date || record.date).toLocaleDateString();
                    const catName = `"${(record.cat_name || record.name || 'Unknown').replace(/"/g, '""')}"`;
                    const age = record.age || 'Unknown';
                    const ageCategory = record.age_category || 'Unknown';
                    const gender = record.gender || 'Unknown';
                    const source = `"${(record.source || 'Unknown').replace(/"/g, '""')}"`;
                    const condition = `"${(record.intake_condition || 'Unknown').replace(/"/g, '""')}"`;
                    const colony = `"${(record.colony || 'Unknown').replace(/"/g, '""')}"`;
                    const addedBy = `"${(record.added_by_name || record.author || 'Unknown').replace(/"/g, '""')}"`;
                    const status = record.discharged ? 'Discharged' : 'Active';
                    
                    return [intakeDate, catName, age, ageCategory, gender, source, condition, colony, addedBy, status].join(',');
                })
            ].join('\\n');

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

        /**
         * Export discharge data as CSV
         */
        exportDischargeData: function() {
            
            if (!this.dischargeRecords || this.dischargeRecords.length === 0) {
                alert('No discharge data available to export.');
                return;
            }

            // Create CSV content
            const headers = ['Discharge Date', 'Cat Name', 'Age', 'Age Category', 'Gender', 'Outcome', 'Discharge Type', 'Colony', 'Added By'];
            
            const csvContent = [
                headers.join(','),
                ...this.dischargeRecords.map(record => {
                    const dischargeDate = new Date(record.discharge_date || record.date).toLocaleDateString();
                    const catName = `"${(record.cat_name || record.name || 'Unknown').replace(/"/g, '""')}"`;
                    const age = record.age || 'Unknown';
                    const ageCategory = record.age_category || 'Unknown';
                    const gender = record.gender || 'Unknown';
                    const outcome = `"${(record.outcome || 'Unknown').replace(/"/g, '""')}"`;
                    const dischargeType = `"${(record.discharge_type || record.outcome || 'Unknown').replace(/"/g, '""')}"`;
                    const colony = `"${(record.colony || 'Unknown').replace(/"/g, '""')}"`;
                    const addedBy = `"${(record.added_by_name || record.author || 'Unknown').replace(/"/g, '""')}"`;
                    
                    return [dischargeDate, catName, age, ageCategory, gender, outcome, dischargeType, colony, addedBy].join(',');
                })
            ].join('\\n');

            // Create and download file
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `claws-discharge-data-${new Date().toISOString().split('T')[0]}.csv`;
            link.click();
            window.URL.revokeObjectURL(url);
            
        },
        
        /**
         * Track feature usage for analytics
         */
        trackFeatureUsage: function(featureName, action = 'used') {
            // Only track if user is logged in
            if (!window.wpApiSettings || !window.wpApiSettings.nonce) {
                return;
            }
            
            // Send tracking data to server
            fetch(window.wpApiSettings.root + 'claws/v1/analytics/track', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({
                    feature: featureName,
                    action: action,
                    timestamp: new Date().toISOString()
                })
            }).catch(err => {
                // Silently fail - don't disrupt user experience
                console.debug('Feature tracking failed:', err);
            });
        }

    });

})();