/**
 * 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, {
        
        /**
         * Parse date string as local date (avoid timezone conversion issues)
         * @param {string} dateString - Date string in YYYY-MM-DD format
         * @returns {Date} Date object in local timezone
         */
        parseDateAsLocal: function(dateString) {
            if (!dateString) return null;
            // Split the date string and create Date using year, month, day
            // This avoids UTC conversion that happens with new Date('2025-12-09')
            const parts = dateString.split('-');
            if (parts.length !== 3) return new Date(dateString); // Fallback
            const year = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1; // Month is 0-indexed
            const day = parseInt(parts[2], 10);
            return new Date(year, month, day);
        },

        // Tab notification state
        tabNotifications: {
            hasNotification: false,
            originalFavicon: null,
            notificationFavicon: null
        },
        
        // Notification polling interval
        notificationPolling: null,

        /**
         * Start polling for notifications
         */
        startNotificationPolling: function() {
            // Initialize favicon notification system
            this.initFaviconNotification();
            
            // Poll every 30 seconds
            this.notificationPolling = setInterval(() => {
                // Only check if tab is hidden
                if (document.hidden) {
                    this.checkForNotifications();
                }
            }, 30000); // 30 seconds
            
        },

        /**
         * Stop polling for notifications
         */
        stopNotificationPolling: function() {
            if (this.notificationPolling) {
                clearInterval(this.notificationPolling);
                this.notificationPolling = null;
            }
        },

        /**
         * Check for new notifications
         */
        checkForNotifications: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/notifications/check', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(data => {
                if (data.has_notifications) {
                    // Build notification message
                    const messages = data.notifications.map(n => n.message).join(', ');
                    this.showTabNotification(messages);
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error checking notifications:', error);
            });
        },

        /**
         * Initialize favicon notification system
         */
        initFaviconNotification: function() {
            // Store original favicon
            let faviconLink = document.querySelector("link[rel*='icon']");
            
            if (!faviconLink) {
                // Create favicon if it doesn't exist
                faviconLink = document.createElement('link');
                faviconLink.type = 'image/x-icon';
                faviconLink.rel = 'shortcut icon';
                faviconLink.href = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90">🐱</text></svg>';
                document.head.appendChild(faviconLink);
            }
            
            this.tabNotifications.originalFavicon = faviconLink.href;
            
            // Create notification favicon with red badge
            this.createNotificationFavicon();
        },

        /**
         * Create a favicon with a red notification badge
         */
        createNotificationFavicon: function() {
            const canvas = document.createElement('canvas');
            canvas.width = 32;
            canvas.height = 32;
            const ctx = canvas.getContext('2d');
            
            // Draw cat emoji as base (or use existing favicon)
            ctx.font = '28px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('🐱', 16, 16);
            
            // Draw red notification badge in top-right corner
            ctx.fillStyle = '#ef4444';
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(24, 8, 6, 0, 2 * Math.PI);
            ctx.fill();
            ctx.stroke();
            
            this.tabNotifications.notificationFavicon = canvas.toDataURL();
        },

        /**
         * Show notification badge on favicon
         */
        showTabNotification: function(message) {
            if (this.tabNotifications.hasNotification) return; // Already showing
            
            this.tabNotifications.hasNotification = true;
            
            // Change favicon to notification version
            const faviconLink = document.querySelector("link[rel*='icon']");
            if (faviconLink && this.tabNotifications.notificationFavicon) {
                faviconLink.href = this.tabNotifications.notificationFavicon;
            }
        },

        /**
         * Clear tab notification and restore original favicon
         */
        clearTabNotification: function() {
            if (!this.tabNotifications.hasNotification) return;
            
            // Restore original favicon
            const faviconLink = document.querySelector("link[rel*='icon']");
            if (faviconLink && this.tabNotifications.originalFavicon) {
                faviconLink.href = this.tabNotifications.originalFavicon;
            }
            
            this.tabNotifications.hasNotification = false;
        },

        /**
         * 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');
            }
            
            // CHART FIX: Reload page when switching TO colony tab from another tab
            // This ensures the chart renders properly (manual refresh works, so auto-refresh will too)
            if (tabName === 'colony' && this.currentTab && this.currentTab !== 'colony') {
                sessionStorage.setItem('claws_no_scroll', 'true');
                setTimeout(() => window.location.reload(), 100);
                return;
            }
            
            // 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() {
            
            const isEditing = !!(this.editingTaskId || window.CLAWSApp.editingTaskId);
            const taskId = this.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
            };
            
            
            // Validate required fields
            if (!taskData.date || !taskData.type || !taskData.description || !taskData.totalHours || !taskData.coordinator) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('❌ Validation failed - missing required fields');
                this.showAlert('Please fill in all required fields', 'error');
                return;
            }
            
            
            // Validate colony selection for colony care tasks
            if (this.requiresColonySelection(taskData.type) && !taskData.colony) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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';
            
            
            // Save to backend
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(payload)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.id || data.success) {
                    // Task saved successfully
                    
                    // Clear editing mode
                    this.editingTaskId = null;
                    window.CLAWSApp.editingTaskId = null;
                    
                    // Refresh pending items
                    this.loadPendingItems();
                } else {
                    (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('❌ ERROR saving task:', error);
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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
            
            // 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 || [];
                
                // Now load events and projects
                this.loadAvailableEvents();
                this.loadAvailableProjects();
                this.loadPastEvents();
                this.loadRetiredProjects();
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading volunteers:', error);
                this.allVolunteers = [];
                // Still try to load events/projects even if volunteers fail
                this.loadAvailableEvents();
                this.loadAvailableProjects();
                this.loadPastEvents();
                this.loadRetiredProjects();
            });
        },

        /**
         * 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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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() {
            const container = document.getElementById('claws-event-teams-list');
            if (!container) {
                return;
            }
            
            // 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 => {
                return response.json();
            })
            .then(teams => {
                
                if (!teams || teams.length === 0) {
                    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;
                }
                
                // Display teams
                let html = '';
                teams.forEach(team => {
                    html += this.renderTeamCard(team, 'event');
                });
                container.innerHTML = html;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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() {
            const container = document.getElementById('claws-project-teams-list');
            if (!container) {
                return;
            }
            
            // 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 => {
                return response.json();
            })
            .then(teams => {
                
                if (!teams || teams.length === 0) {
                    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;
                }
                
                // Display teams
                let html = '';
                teams.forEach(team => {
                    html += this.renderTeamCard(team, 'project');
                });
                container.innerHTML = html;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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() {
            const container = document.querySelector('#claws-events-list');
            if (!container) {
                return;
            }
            
            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 => {
                return response.json();
            })
            .then(events => {
                
                if (!events || events.length === 0) {
                    container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #9ca3af;">No events available at this time.</p>';
                    return;
                }
                
                const currentUserId = parseInt(window.wpApiSettings.userId);
                
                let html = '<div style="display: grid; gap: 1.5rem; margin-top: 1.5rem;">';
                events.forEach(event => {
                    const eventDate = this.parseDateAsLocal(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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading events:', error);
                container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #ef4444;">Failed to load events</p>';
            });
        },
        
        loadPastEvents: function() {
            const container = document.querySelector('#claws-past-events-list');
            if (!container) {
                return;
            }
            
            container.innerHTML = '<p style="text-align: center; padding: 1rem; color: #9ca3af; font-size: 0.875rem;">Loading...</p>';
            
            // Fetch all events and filter for past ones
            fetch(window.wpApiSettings.root + 'claws/v1/events', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(allEvents => {
                // Filter for past events (date before today)
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                
                const pastEvents = allEvents.filter(event => {
                    const eventDate = this.parseDateAsLocal(event.date);
                    return eventDate < today;
                });
                
                if (!pastEvents || pastEvents.length === 0) {
                    container.innerHTML = '<p style="text-align: center; padding: 1rem; color: #9ca3af; font-size: 0.875rem;">No past events yet</p>';
                    return;
                }
                
                // Sort by date descending (newest first)
                pastEvents.sort((a, b) => {
                    const dateA = this.parseDateAsLocal(a.date);
                    const dateB = this.parseDateAsLocal(b.date);
                    return dateB - dateA;
                });
                
                let html = '<div style="display: flex; flex-direction: column; gap: 0.75rem;">';
                pastEvents.forEach(event => {
                    const eventDate = this.parseDateAsLocal(event.date).toLocaleDateString('en-US', { 
                        month: 'short', 
                        day: 'numeric',
                        year: 'numeric'
                    });
                    
                    // Count filled spots
                    const spots = event.volunteer_spots || [];
                    const filledSpots = spots.filter(s => s.volunteer_id).length;
                    const totalSpots = spots.length;
                    
                    html += `
                        <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 0.375rem; padding: 0.75rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.25rem;">
                                <div style="font-weight: 600; color: #374151; font-size: 0.875rem;">${event.name}</div>
                                <div style="font-size: 0.75rem; color: #6b7280;">${eventDate}</div>
                            </div>
                            <div style="font-size: 0.75rem; color: #6b7280;">
                                Team: ${filledSpots}/${totalSpots} volunteers
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                
                container.innerHTML = html;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading past events:', error);
                container.innerHTML = '<p style="text-align: center; padding: 1rem; color: #ef4444; font-size: 0.875rem;">Failed to load past events</p>';
            });
        },
        
        loadAvailableProjects: function() {
            const container = document.querySelector('#claws-projects-list');
            if (!container) {
                return;
            }
            
            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 => {
                return response.json();
            })
            .then(projects => {
                
                if (!projects || projects.length === 0) {
                    container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #9ca3af;">No ongoing projects available.</p>';
                    return;
                }
                
                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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading projects:', error);
                container.innerHTML = '<p style="text-align: center; padding: 2rem; color: #ef4444;">Failed to load projects</p>';
            });
        },
        
        loadRetiredProjects: function() {
            const container = document.querySelector('#claws-retired-projects-list');
            if (!container) {
                return;
            }
            
            container.innerHTML = '<p style="text-align: center; padding: 1rem; color: #9ca3af; font-size: 0.875rem;">Loading...</p>';
            
            // Fetch all projects and filter for retired ones
            fetch(window.wpApiSettings.root + 'claws/v1/projects', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(allProjects => {
                // Filter for retired projects
                const retiredProjects = allProjects.filter(project => project.retired == 1);
                
                if (!retiredProjects || retiredProjects.length === 0) {
                    container.innerHTML = '<p style="text-align: center; padding: 1rem; color: #9ca3af; font-size: 0.875rem;">No retired projects yet</p>';
                    return;
                }
                
                // Sort by retired_at date if available, otherwise by name
                retiredProjects.sort((a, b) => {
                    if (a.retired_at && b.retired_at) {
                        return new Date(b.retired_at) - new Date(a.retired_at);
                    }
                    return (a.name || '').localeCompare(b.name || '');
                });
                
                let html = '<div style="display: flex; flex-direction: column; gap: 0.75rem;">';
                retiredProjects.forEach(project => {
                    // Get category/colony info
                    let categoryInfo = project.category || 'General';
                    if (project.colony_name) {
                        categoryInfo += ` - ${project.colony_name}`;
                    }
                    
                    // Count filled spots
                    const spots = project.volunteer_spots || [];
                    const filledSpots = spots.filter(s => s.volunteer_id).length;
                    const totalSpots = spots.length;
                    
                    // Format retired date if available
                    let retiredDate = '';
                    if (project.retired_at) {
                        const date = new Date(project.retired_at);
                        retiredDate = date.toLocaleDateString('en-US', { 
                            month: 'short', 
                            day: 'numeric',
                            year: 'numeric'
                        });
                    }
                    
                    html += `
                        <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 0.375rem; padding: 0.75rem;">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.25rem;">
                                <div style="font-weight: 600; color: #374151; font-size: 0.875rem;">${project.name}</div>
                                ${retiredDate ? `<div style="font-size: 0.75rem; color: #6b7280;">Retired: ${retiredDate}</div>` : ''}
                            </div>
                            <div style="font-size: 0.75rem; color: #6b7280; margin-bottom: 0.25rem;">${categoryInfo}</div>
                            <div style="font-size: 0.75rem; color: #6b7280;">
                                Team: ${filledSpots}/${totalSpots} volunteers
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                
                container.innerHTML = html;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading retired projects:', error);
                container.innerHTML = '<p style="text-align: center; padding: 1rem; color: #ef4444; font-size: 0.875rem;">Failed to load retired projects</p>';
            });
        },

        /**
         * Get volunteer name by ID from cached list
         */
        getVolunteerNameById: function(volunteerId) {
            
            if (!this.allVolunteers) {
                return 'Unknown';
            }
            
            const volunteer = this.allVolunteers.find(v => v.id === parseInt(volunteerId));
            
            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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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;
                }
                
                
                // 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"]');
                    if (submitBtn) {
                        submitBtn.textContent = event.type === 'project' ? '💾 Update Project' : '💾 Update Event';
                    } else {
                        (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('❌ Submit button not found with selector: #claws-add-event-modal button[onclick*="saveEvent"]');
                    }
                    
                }, 200);
                
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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;
                }
                
                
                // 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"]');
                    if (submitBtn) {
                        submitBtn.textContent = '💾 Update Project';
                    } else {
                        (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('❌ Submit button not found with selector: #claws-add-event-modal button[onclick*="saveEvent"]');
                    }
                    
                }, 200);
                
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error retiring project:', error);
                this.showAlert('Failed to retire project', 'error');
            });
        },

        loadVolunteerStatsGoals: function() {
            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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 both volunteers and unread counts
            Promise.all([
                fetch(window.wpApiSettings.root + 'claws/v1/volunteers', {
                    headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
                }).then(r => r.json()),
                fetch(window.wpApiSettings.root + 'claws/v1/messages/unread-counts', {
                    headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
                }).then(r => r.json())
            ])
            .then(([volunteers, unreadData]) => {
                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;
                const unreadCounts = unreadData.individuals || {};
                
                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];
                    
                    // Determine online status
                    const statusColor = volunteer.is_online ? '#10b981' : '#9ca3af';
                    const statusText = volunteer.is_online ? 'Online' : 'Offline';
                    
                    // Get unread count
                    const unreadCount = unreadCounts[volunteer.id] || 0;
                    const unreadBadge = unreadCount > 0 ? `
                        <span style="background: #ef4444; color: white; font-size: 0.7rem; font-weight: 700; padding: 0.125rem 0.4rem; border-radius: 9999px; min-width: 1.25rem; text-align: center; display: inline-block;">${unreadCount}</span>
                    ` : '';
                    
                    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;">
                                    <div style="display: flex; align-items: center; justify-content: space-between; gap: 0.5rem;">
                                        <p style="margin: 0; font-weight: 600; font-size: 0.875rem; color: #1f2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${volunteer.name}</p>
                                        ${unreadBadge}
                                    </div>
                                    <p style="margin: 0; font-size: 0.75rem; color: ${statusColor};">● ${statusText}</p>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                container.innerHTML = html;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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; justify-content: space-between; width: 100%;">
                    <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>
                    <button 
                        onclick="CLAWSApp.confirmClearConversation()"
                        style="background: #ef4444; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.5rem; font-size: 0.75rem; font-weight: 500; cursor: pointer; transition: background 0.2s;"
                        onmouseover="this.style.background='#dc2626'"
                        onmouseout="this.style.background='#ef4444'"
                    >
                        🗑️ Clear Chat
                    </button>
                </div>
            `;
            
            // Update recipient indicator above message input
            const recipientIndicator = document.getElementById('claws-chat-recipient');
            if (recipientIndicator) {
                recipientIndicator.innerHTML = `
                    <div style="background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 0.5rem; padding: 0.5rem 0.75rem; margin-bottom: 0.75rem;">
                        <span style="font-size: 0.75rem; font-weight: 600; color: #0369a1;">Messaging: </span>
                        <span style="font-size: 0.875rem; font-weight: 600; color: #0c4a6e;">[${this.escapeHtml(name)}]</span>
                    </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;
                }
                
                // Check for new messages (if polling silently)
                if (silent && this.lastMessageCount) {
                    const currentUserId = window.wpApiSettings.currentUserId;
                    const newMessages = messages.slice(this.lastMessageCount);
                    const hasNewFromOthers = newMessages.some(msg => msg.sender_id != currentUserId);
                    
                    // Trigger notification if user is not focused on the page
                    if (hasNewFromOthers && document.hidden) {
                        this.showTabNotification('New Message');
                    }
                }
                
                // Store message count for next poll
                this.lastMessageCount = messages.length;
                
                // 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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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);
                    
                    // Refresh conversation lists to update unread counts
                    this.loadChatIndividuals();
                    this.loadChatTeams();
                } else {
                    alert('Failed to send message');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error sending message:', error);
                alert('Failed to send message');
            })
            .finally(() => {
                input.disabled = false;
                input.focus();
            });
        },
        
        /**
         * Confirm before clearing conversation
         */
        confirmClearConversation: function() {
            if (!this.currentChat) return;
            
            const chatName = this.currentChat.name;
            if (confirm(`Are you sure you want to delete ALL messages in this conversation with "${chatName}"? This cannot be undone.`)) {
                this.clearConversation();
            }
        },
        
        /**
         * Clear/delete current conversation
         */
        clearConversation: function() {
            if (!this.currentChat) return;
            
            fetch(window.wpApiSettings.root + `claws/v1/messages/clear/${this.currentChat.type}/${this.currentChat.id}`, {
                method: 'DELETE',
                headers: {
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    // Reload messages (will show "No messages yet")
                    this.loadChatMessages();
                    
                    // Refresh conversation lists
                    this.loadChatIndividuals();
                    this.loadChatTeams();
                    
                    // Show success message
                    this.showAlert('Conversation cleared successfully', 'success');
                } else {
                    alert('Failed to clear conversation');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error clearing conversation:', error);
                alert('Failed to clear conversation');
            });
        },
        
        // ==========================================
        // ADMIN MANAGEMENT FUNCTIONS
        // ==========================================
        
        /**
         * Donor Management Functions
         */
        showAddDonorForm: function(donorData = null) {
            const isEdit = donorData !== null && !donorData.isAdditional;
            const isAdditional = donorData && donorData.isAdditional;
            
            // Compatibility layer: split name into first_name and last_name if needed
            if (donorData && donorData.name && !donorData.first_name && !donorData.last_name) {
                const nameParts = donorData.name.split(' ');
                donorData.first_name = nameParts[0] || '';
                donorData.last_name = nameParts.slice(1).join(' ') || '';
            }
            
            const modalTitle = isAdditional ? 'Record Additional Donation' : (isEdit ? 'Edit Donor' : 'Add Donor');
            const readonly = isAdditional ? 'readonly' : '';
            const readonlyStyle = isAdditional ? 'background: #f3f4f6; cursor: not-allowed;' : '';
            
            const modalHtml = `
                <div id="claws-donor-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">💰 ${modalTitle}</h3>
                        ${isAdditional ? '<p style="background: #dbeafe; color: #1e40af; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem; font-size: 0.875rem;">Recording additional donation for existing donor. Contact information is read-only.</p>' : ''}
                        
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Donor ID</label>
                                <input type="text" id="donor-id" value="${isEdit ? donorData.donor_id : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">First Name *</label>
                                <input type="text" id="donor-first-name" value="${donorData ? donorData.first_name : ''}" required ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Last Name *</label>
                                <input type="text" id="donor-last-name" value="${donorData ? donorData.last_name : ''}" required ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Email</label>
                                <input type="email" id="donor-email" value="${donorData ? (donorData.email || '') : ''}" ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Phone</label>
                                <input type="tel" id="donor-phone" value="${donorData ? (donorData.phone || '') : ''}" ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 0.5rem; padding: 0.75rem;">
                                <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer; margin: 0;">
                                    <input type="checkbox" id="donor-do-not-contact" ${isEdit && donorData.do_not_contact ? 'checked' : ''} style="width: 1.25rem; height: 1.25rem; cursor: pointer;">
                                    <div>
                                        <span style="font-weight: 600; color: #92400e; font-size: 0.875rem;">Do Not Contact Me</span>
                                        <p style="margin: 0.25rem 0 0; font-size: 0.75rem; color: #78350f;">Check this if you prefer not to receive mass mailings or newsletters</p>
                                    </div>
                                </label>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Donation Date *</label>
                                <input type="date" id="donor-date" value="${isEdit ? donorData.date : ''}" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Amount *</label>
                                <input type="number" id="donor-amount" value="${isEdit ? donorData.amount : ''}" step="0.01" min="0" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Donation Type *</label>
                                <select id="donor-donation-type" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Select type...</option>
                                    <option value="one-time" ${isEdit && donorData.donation_type === 'one-time' ? 'selected' : ''}>One time</option>
                                    <option value="recurring-monthly" ${isEdit && donorData.donation_type === 'recurring-monthly' ? 'selected' : ''}>Recurring (Monthly)</option>
                                    <option value="recurring-annual" ${isEdit && donorData.donation_type === 'recurring-annual' ? 'selected' : ''}>Recurring (Annual)</option>
                                </select>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Purpose/Restrictions</label>
                                <textarea id="donor-purpose" rows="3" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">${isEdit ? donorData.purpose : ''}</textarea>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Payment Method *</label>
                                <select id="donor-payment" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Select method...</option>
                                    <option value="check" ${isEdit && donorData.payment_method === 'check' ? 'selected' : ''}>Check</option>
                                    <option value="cash" ${isEdit && donorData.payment_method === 'cash' ? 'selected' : ''}>Cash</option>
                                    <option value="card" ${isEdit && donorData.payment_method === 'card' ? 'selected' : ''}>Card</option>
                                    <option value="paypal" ${isEdit && donorData.payment_method === 'paypal' ? 'selected' : ''}>PayPal</option>
                                </select>
                            </div>
                            
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <input type="checkbox" id="donor-acknowledged" ${isEdit && donorData.acknowledged ? 'checked' : ''} style="width: 1.25rem; height: 1.25rem;">
                                <label for="donor-acknowledged" style="font-weight: 600; color: #374151;">Acknowledgement Sent</label>
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.saveDonor(${isEdit ? donorData.id : 'null'})" style="flex: 1; background: var(--claws-primary-button-color); color: var(--claws-button-text-color); border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                ${isEdit ? 'Update' : 'Add'} Donor
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-donor-modal')" style="
                                flex: 1;
                                background: linear-gradient(to bottom, #9ca3af, #6b7280);
                                color: white;
                                border: none;
                                border-top: 1px solid rgba(255, 255, 255, 0.3);
                                border-bottom: 2px solid rgba(0, 0, 0, 0.2);
                                padding: 0.75rem;
                                border-radius: 0.75rem;
                                font-weight: 600;
                                cursor: pointer;
                                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1);
                                transition: all 0.2s ease;
                                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
                            " onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
        },
        
        saveDonor: function(donorId) {
            const firstName = document.getElementById('donor-first-name').value;
            const lastName = document.getElementById('donor-last-name').value;
            
            const data = {
                donor_id: document.getElementById('donor-id').value,
                first_name: firstName,
                last_name: lastName,
                name: `${firstName} ${lastName}`.trim(), // Compatibility: combine for backend
                email: document.getElementById('donor-email').value,
                phone: document.getElementById('donor-phone').value,
                do_not_contact: document.getElementById('donor-do-not-contact')?.checked || false,
                date: document.getElementById('donor-date').value,
                amount: document.getElementById('donor-amount').value,
                donation_type: document.getElementById('donor-donation-type').value,
                purpose: document.getElementById('donor-purpose').value,
                payment_method: document.getElementById('donor-payment').value,
                acknowledged: document.getElementById('donor-acknowledged').checked
            };
            
            if (!data.first_name || !data.last_name || !data.date || !data.amount || !data.donation_type || !data.payment_method) {
                alert('Please fill in all required fields');
                return;
            }
            
            const url = donorId 
                ? `${window.wpApiSettings.root}claws/v1/donors/${donorId}`
                : `${window.wpApiSettings.root}claws/v1/donors`;
            
            fetch(url, {
                method: donorId ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    this.closeModal('claws-donor-modal');
                    alert(donorId ? 'Donor updated successfully!' : 'Donor added successfully!');
                } else {
                    alert('Error saving donor');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error saving donor');
            });
        },
        
        recordAdditionalDonation: function(donorName, email, phone, donorId) {
            // Split name into first and last
            const nameParts = donorName.split(' ');
            const firstName = nameParts[0] || '';
            const lastName = nameParts.slice(1).join(' ') || '';
            
            // Open donor form with pre-filled, read-only contact info including donor_id
            this.showAddDonorForm({
                donor_id: donorId,
                first_name: firstName,
                last_name: lastName,
                email: email,
                phone: phone,
                isAdditional: true  // Flag to make fields read-only
            });
        },
        
        processRecurringDonation: function(donorId, donorName, amount) {
            if (!confirm(`Create new $${amount} recurring donation for ${donorName}?`)) return;
            
            // Fetch the original donation details
            fetch(`${window.wpApiSettings.root}claws/v1/donors`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(donors => {
                const originalDonation = donors.find(d => d.id === donorId);
                if (!originalDonation) {
                    alert('Original donation not found');
                    return;
                }
                
                // Create new donation with today's date
                const newDonation = {
                    donor_id: originalDonation.donor_id,
                    first_name: originalDonation.first_name,
                    last_name: originalDonation.last_name,
                    name: originalDonation.name,
                    email: originalDonation.email,
                    phone: originalDonation.phone,
                    date: new Date().toISOString().split('T')[0],
                    amount: originalDonation.amount,
                    donation_type: originalDonation.donation_type,
                    purpose: originalDonation.purpose,
                    payment_method: originalDonation.payment_method,
                    acknowledged: false
                };
                
                fetch(`${window.wpApiSettings.root}claws/v1/donors`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpApiSettings.nonce
                    },
                    body: JSON.stringify(newDonation)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        alert('Recurring donation processed successfully!');
                        this.showDonorList(); // Refresh list
                    } else {
                        alert('Error processing recurring donation');
                    }
                })
                .catch(error => {
                    (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                    alert('Error processing recurring donation');
                });
            });
        },
        
        processAllRecurringDonations: function() {
            // Fetch all donors
            fetch(`${window.wpApiSettings.root}claws/v1/donors`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(donors => {
                // Find all recurring donations
                const recurringDonations = donors.filter(d => 
                    d.donation_type && (d.donation_type.includes('recurring') || d.donation_type.includes('Recurring'))
                );
                
                if (recurringDonations.length === 0) {
                    alert('No recurring donations found');
                    return;
                }
                
                // Show confirmation modal
                const donorList = recurringDonations.map(d => `${d.name}: $${d.amount}`).join('\n');
                if (!confirm(`Process ${recurringDonations.length} recurring donations?\n\n${donorList}\n\nThis will create new donation entries with today's date.`)) {
                    return;
                }
                
                // Process each recurring donation
                let processed = 0;
                let errors = 0;
                
                const processNext = (index) => {
                    if (index >= recurringDonations.length) {
                        alert(`Processed ${processed} recurring donations${errors > 0 ? ` (${errors} errors)` : ''}`);
                        this.showDonorList(); // Refresh list
                        return;
                    }
                    
                    const original = recurringDonations[index];
                    const newDonation = {
                        donor_id: original.donor_id,
                        first_name: original.first_name,
                        last_name: original.last_name,
                        name: original.name,
                        email: original.email,
                        phone: original.phone,
                        date: new Date().toISOString().split('T')[0],
                        amount: original.amount,
                        donation_type: original.donation_type,
                        purpose: original.purpose,
                        payment_method: original.payment_method,
                        acknowledged: false
                    };
                    
                    fetch(`${window.wpApiSettings.root}claws/v1/donors`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': window.wpApiSettings.nonce
                        },
                        body: JSON.stringify(newDonation)
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            processed++;
                        } else {
                            errors++;
                        }
                        processNext(index + 1);
                    })
                    .catch(error => {
                        (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                        errors++;
                        processNext(index + 1);
                    });
                };
                
                processNext(0);
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error fetching recurring donations');
            });
        },
        
        showDonorList: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/donors', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(donors => {
                // Group donations by donor name and sort by date (oldest first)
                const donorGroups = {};
                donors.forEach(d => {
                    const name = d.name;
                    if (!donorGroups[name]) {
                        donorGroups[name] = [];
                    }
                    donorGroups[name].push(d);
                });
                
                // Sort each group by date (oldest first)
                Object.keys(donorGroups).forEach(name => {
                    donorGroups[name].sort((a, b) => new Date(a.date) - new Date(b.date));
                });
                
                // Calculate annual and cumulative totals per donor name
                const currentYear = new Date().getFullYear();
                const donorTotals = {};
                
                Object.keys(donorGroups).forEach(name => {
                    donorTotals[name] = { annual: 0, cumulative: 0, donorId: null };
                    
                    donorGroups[name].forEach((d, index) => {
                        // Capture donor_id from first/oldest entry
                        if (index === 0 && d.donor_id) {
                            donorTotals[name].donorId = d.donor_id;
                        }
                        
                        const amount = parseFloat(d.amount) || 0;
                        donorTotals[name].cumulative += amount;
                        
                        const donationYear = new Date(d.date).getFullYear();
                        if (donationYear === currentYear) {
                            donorTotals[name].annual += amount;
                        }
                    });
                });
                
                let rows = '';
                
                // Render each donor group as an accordion
                Object.keys(donorGroups).forEach(donorName => {
                    const donations = donorGroups[donorName];
                    const totals = donorTotals[donorName];
                    const hasMultiple = donations.length > 1;
                    
                    donations.forEach((donor, index) => {
                        const isFirst = index === 0;
                        const donationType = donor.donation_type ? donor.donation_type.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) : 'N/A';
                        
                        // First/oldest entry - full row with accordion toggle if multiple
                        if (isFirst) {
                            const accordionIcon = hasMultiple ? '► ' : '';
                            const accordionClick = hasMultiple ? `onclick="CLAWSApp.toggleDonorAccordion('${donorName.replace(/'/g, "\\'")}')"` : '';
                            const accordionStyle = hasMultiple ? 'cursor: pointer; user-select: none;' : '';
                            
                            // Check for "Do Not Contact" flag
                            const doNotContactFlag = (donor.do_not_contact === true || donor.do_not_contact === 'true' || donor.do_not_contact === '1') 
                                ? '<span style="background: #fef3c7; color: #92400e; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.625rem; white-space: nowrap; display: inline-block; margin-left: 0.5rem; font-weight: 600;" title="This contact prefers not to receive mass mailings">🚫 Do Not Contact</span>'
                                : '';
                            
                            rows += `
                                <tr style="border-bottom: 1px solid #e5e7eb; background: #f9fafb;" data-donor-group="${donorName}">
                                    <td style="padding: 0.75rem; white-space: nowrap;">${totals.donorId || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600;" ${accordionClick} ${accordionStyle}>${accordionIcon}${donor.name}${doNotContactFlag}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.date}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">$${parseFloat(donor.amount).toFixed(2)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donationType}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.purpose || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.payment_method}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.acknowledged ? '✅ Yes' : '❌ No'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600; color: #059669;">$${totals.annual.toFixed(2)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600; color: #7c3aed;">$${totals.cumulative.toFixed(2)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">
                                        <button onclick="CLAWSApp.recordAdditionalDonation('${donor.name.replace(/'/g, "\\'")}', '${donor.email || ''}', '${donor.phone || ''}', '${totals.donorId || ''}')" style="background: #10b981; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;" title="Record Additional Donation">➕</button>
                                        <button onclick="CLAWSApp.editDonor(${donor.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                        <button onclick="CLAWSApp.deleteDonor(${donor.id})" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                                    </td>
                                </tr>
                            `;
                        } else {
                            // Subsequent entries - indented, collapsed by default
                            const isRecurring = donor.donation_type && (donor.donation_type.includes('recurring') || donor.donation_type.includes('Recurring'));
                            const recurringIcon = isRecurring ? '🔄' : '↳';
                            const processButton = isRecurring ? `<button onclick="CLAWSApp.processRecurringDonation(${donor.id}, '${donor.name.replace(/'/g, "\\'")}', ${donor.amount})" style="background: #f59e0b; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;" title="Process This Recurring Donation">📅</button>` : '';
                            
                            rows += `
                                <tr class="donor-sub-entry donor-sub-${donorName.replace(/[^a-zA-Z0-9]/g, '_')}" style="border-bottom: 1px solid #e5e7eb; display: none;">
                                    <td style="padding: 0.75rem 0.75rem 0.75rem 2rem; white-space: nowrap; color: #6b7280;">${recurringIcon}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; color: #6b7280;">${donor.name}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.date}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">$${parseFloat(donor.amount).toFixed(2)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donationType}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.purpose || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.payment_method}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${donor.acknowledged ? '✅ Yes' : '❌ No'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; color: #9ca3af;">—</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; color: #9ca3af;">—</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">
                                        ${processButton}
                                        <button onclick="CLAWSApp.editDonor(${donor.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                        <button onclick="CLAWSApp.deleteDonor(${donor.id})" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                                    </td>
                                </tr>
                            `;
                        }
                    });
                });
                
                // Calculate grand totals
                let grandTotalAnnual = 0;
                let grandTotalCumulative = 0;
                Object.values(donorTotals).forEach(total => {
                    grandTotalAnnual += total.annual;
                    grandTotalCumulative += total.cumulative;
                });
                
                // Add grand totals row
                rows += `
                    <tr style="border-top: 3px solid #1f2937; background: #f3f4f6; font-weight: 700;">
                        <td colspan="8" style="padding: 0.75rem; text-align: right;">GRAND TOTAL:</td>
                        <td style="padding: 0.75rem; white-space: nowrap; color: #059669; font-size: 1rem;">$${grandTotalAnnual.toFixed(2)}</td>
                        <td style="padding: 0.75rem; white-space: nowrap; color: #7c3aed; font-size: 1rem;">$${grandTotalCumulative.toFixed(2)}</td>
                        <td style="padding: 0.75rem;"></td>
                    </tr>
                `;
                
                const modalHtml = `
                    <div id="claws-donor-list-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 95vw; width: 95%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
                            <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">💰 Donor List</h3>
                            
                            <div style="overflow-x: auto; overflow-y: auto; flex: 1;">
                                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 1000px;">
                                    <thead style="position: sticky; top: 0; background: white; z-index: 1;">
                                        <tr style="background: #f3f4f6; border-bottom: 2px solid #d1d5db;">
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Donor ID</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Date</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Amount</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Donation Type</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Purpose</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Payment Method</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Acknowledged</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Annual Donation</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Cumulative Donation</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${rows || '<tr><td colspan="11" style="padding: 2rem; text-align: center; color: #6b7280;">No donors found</td></tr>'}
                                    </tbody>
                                </table>
                            </div>
                            
                            <div style="margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem; display: flex; justify-content: space-between;">
                                <div style="display: flex; gap: 0.5rem;">
                                    <button onclick="CLAWSApp.processAllRecurringDonations()" style="background: #f59e0b; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                        📅 Process All Recurring Donations
                                    </button>
                                    <button onclick="CLAWSApp.exportDonors()" style="background: #10b981; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                        📥 Export Donors
                                    </button>
                                </div>
                                <button onclick="CLAWSApp.closeModal('claws-donor-list-modal')" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error loading donors');
            });
        },
        
        showDonorListFiltered: function(firstName, lastName) {
            const fullName = `${firstName} ${lastName}`;
            fetch(window.wpApiSettings.root + 'claws/v1/donors', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(allDonors => {
                // Filter to matching name
                const donors = allDonors.filter(d => d.name.toLowerCase().includes(fullName.toLowerCase()));
                
                let rows = '';
                donors.forEach(donor => {
                    const donationType = donor.donation_type ? donor.donation_type.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) : 'N/A';
                    // Highlight matching rows
                    rows += `
                        <tr style="border-bottom: 1px solid #e5e7eb; background: #fef3c7;">
                            <td style="padding: 0.75rem; white-space: nowrap;">${donor.donor_id || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600;">${donor.name}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${donor.date}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">$${parseFloat(donor.amount).toFixed(2)}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${donationType}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${donor.purpose || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${donor.payment_method}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${donor.acknowledged ? '✅ Yes' : '❌ No'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">
                                <button onclick="CLAWSApp.editDonor(${donor.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                <button onclick="CLAWSApp.deleteDonor(${donor.id})" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                            </td>
                        </tr>
                    `;
                });
                
                const modalHtml = `
                    <div id="claws-donor-list-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 95vw; width: 95%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
                            <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">💰 Donor Records for ${fullName}</h3>
                            
                            <div style="overflow-x: auto; overflow-y: auto; flex: 1;">
                                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 1000px;">
                                    <thead style="position: sticky; top: 0; background: white; z-index: 1;">
                                        <tr style="background: #f3f4f6; border-bottom: 2px solid #d1d5db;">
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Donor ID</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Date</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Amount</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Donation Type</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Purpose</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Payment Method</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Acknowledged</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${rows || `<tr><td colspan="9" style="padding: 2rem; text-align: center; color: #6b7280;">No donor records found for ${fullName}</td></tr>`}
                                    </tbody>
                                </table>
                            </div>
                            
                            <div style="margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem; display: flex; justify-content: space-between;">
                                <button onclick="CLAWSApp.exportDonors()" style="background: #10b981; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    📥 Export Donors
                                </button>
                                <button onclick="CLAWSApp.closeModal('claws-donor-list-modal')" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error loading donors');
            });
        },
        
        toggleDonorAccordion: function(donorName) {
            const className = 'donor-sub-' + donorName.replace(/[^a-zA-Z0-9]/g, '_');
            const subRows = document.querySelectorAll('.' + className);
            const mainRow = document.querySelector(`[data-donor-group="${donorName}"]`);
            
            if (subRows.length === 0) return;
            
            const isHidden = subRows[0].style.display === 'none';
            
            subRows.forEach(row => {
                row.style.display = isHidden ? 'table-row' : 'none';
            });
            
            // Toggle arrow icon in Name column (second cell)
            if (mainRow) {
                const nameCell = mainRow.querySelectorAll('td')[1]; // Second column (Name)
                if (nameCell) {
                    const currentText = nameCell.textContent.trim();
                    if (isHidden) {
                        nameCell.textContent = currentText.replace('► ', '▼ ');
                    } else {
                        nameCell.textContent = currentText.replace('▼ ', '► ');
                    }
                }
            }
        },
        
        editDonor: function(donorId) {
            fetch(`${window.wpApiSettings.root}claws/v1/donors`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(donors => {
                const donor = donors.find(d => d.id === donorId);
                if (donor) {
                    this.closeModal('claws-donor-list-modal');
                    this.showAddDonorForm(donor);
                }
            });
        },
        
        deleteDonor: function(donorId) {
            if (!confirm('Are you sure you want to delete this donor?')) return;
            
            fetch(`${window.wpApiSettings.root}claws/v1/donors/${donorId}`, {
                method: 'DELETE',
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Donor deleted successfully');
                    this.showDonorList();
                }
            });
        },
        
        exportDonors: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/donors', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(donors => {
                const headers = ['Donor ID', 'Name', 'Do Not Contact', 'Date', 'Amount', 'Purpose', 'Payment Method', 'Acknowledged'];
                const csvContent = [
                    headers.join(','),
                    ...donors.map(d => [
                        d.donor_id || '',
                        `"${d.name}"`,
                        (d.do_not_contact === true || d.do_not_contact === 'true' || d.do_not_contact === '1') ? 'Yes' : 'No',
                        d.date,
                        d.amount,
                        `"${d.purpose || ''}"`,
                        d.payment_method,
                        d.acknowledged ? 'Yes' : 'No'
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob([csvContent], { type: 'text/csv' });
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `donors-${new Date().toISOString().split('T')[0]}.csv`;
                link.click();
                window.URL.revokeObjectURL(url);
            });
        },
        
        /**
         * Sponsor Management Functions
         */
        showAddSponsorForm: function(sponsorData = null) {
            const isEdit = sponsorData !== null && !sponsorData.isAdditional;
            const isAdditional = sponsorData && sponsorData.isAdditional;
            
            // Compatibility layer: split contact_name into first_name and last_name if needed
            if (sponsorData && sponsorData.contact_name && !sponsorData.first_name && !sponsorData.last_name) {
                const nameParts = sponsorData.contact_name.split(' ');
                sponsorData.first_name = nameParts[0] || '';
                sponsorData.last_name = nameParts.slice(1).join(' ') || '';
            }
            
            // Compatibility layer: handle old 'name' field as organization_name
            if (sponsorData && sponsorData.name && !sponsorData.organization_name) {
                sponsorData.organization_name = sponsorData.name;
            }
            
            const modalTitle = isAdditional ? 'Record Additional Sponsorship' : (isEdit ? 'Edit Sponsor' : 'Add Sponsor');
            const readonly = isAdditional ? 'readonly' : '';
            const readonlyStyle = isAdditional ? 'background: #f3f4f6; cursor: not-allowed;' : '';
            
            const modalHtml = `
                <div id="claws-sponsor-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">🤝 ${modalTitle}</h3>
                        ${isAdditional ? '<p style="background: #dbeafe; color: #1e40af; padding: 0.75rem; border-radius: 0.5rem; margin-bottom: 1rem; font-size: 0.875rem;">Recording additional sponsorship for existing contact. Contact information is read-only.</p>' : ''}
                        
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Organization Name</label>
                                <input type="text" id="sponsor-org-name" value="${sponsorData ? (sponsorData.organization_name || '') : ''}" ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Contact First Name *</label>
                                <input type="text" id="sponsor-first-name" value="${sponsorData ? sponsorData.first_name : ''}" required ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Contact Last Name *</label>
                                <input type="text" id="sponsor-last-name" value="${sponsorData ? sponsorData.last_name : ''}" required ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Website</label>
                                <input type="url" id="sponsor-website" value="${sponsorData ? (sponsorData.website || '') : ''}" placeholder="https://example.com" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Email</label>
                                <input type="email" id="sponsor-email" value="${sponsorData ? (sponsorData.email || '') : ''}" ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Phone</label>
                                <input type="tel" id="sponsor-phone" value="${sponsorData ? (sponsorData.phone || '') : ''}" ${readonly} style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; ${readonlyStyle}">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Sponsorship Type</label>
                                <input type="text" id="sponsor-type" value="${isEdit ? sponsorData.sponsorship_type : ''}" placeholder="e.g., Sponsor Colony, Sponsor (Event Name)" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">$ Amount Asked</label>
                                <input type="number" id="sponsor-amount-asked" value="${isEdit ? (sponsorData.amount_asked || '') : ''}" step="0.01" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Amount</label>
                                <input type="number" id="sponsor-amount" value="${isEdit ? sponsorData.amount : ''}" step="0.01" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Frequency</label>
                                <select id="sponsor-frequency" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Select...</option>
                                    <option value="monthly" ${isEdit && sponsorData.frequency === 'monthly' ? 'selected' : ''}>Monthly</option>
                                    <option value="annual" ${isEdit && sponsorData.frequency === 'annual' ? 'selected' : ''}>Annual</option>
                                    <option value="one-time" ${isEdit && sponsorData.frequency === 'one-time' ? 'selected' : ''}>One-time</option>
                                </select>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Start Date</label>
                                <input type="date" id="sponsor-start-date" value="${isEdit ? sponsorData.start_date : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Status</label>
                                <select id="sponsor-status" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="active" ${isEdit && sponsorData.status === 'active' ? 'selected' : ''}>Active</option>
                                    <option value="inactive" ${isEdit && sponsorData.status === 'inactive' ? 'selected' : ''}>Inactive</option>
                                </select>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Notes</label>
                                <textarea id="sponsor-notes" rows="3" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">${isEdit ? (sponsorData.notes || '') : ''}</textarea>
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.saveSponsor(${isEdit ? sponsorData.id : 'null'})" style="flex: 1; background: var(--claws-primary-button-color); color: var(--claws-button-text-color); border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                ${isEdit ? 'Update' : 'Add'} Sponsor
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-sponsor-modal')" style="flex: 1; background: #6b7280; color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
        },
        
        saveSponsor: function(sponsorId) {
            const firstName = document.getElementById('sponsor-first-name').value;
            const lastName = document.getElementById('sponsor-last-name').value;
            const orgName = document.getElementById('sponsor-org-name').value;
            
            const data = {
                organization_name: orgName,
                first_name: firstName,
                last_name: lastName,
                contact_name: `${firstName} ${lastName}`.trim(), // Compatibility: combine for backend
                name: orgName || `${firstName} ${lastName}`.trim(), // Compatibility: fallback to contact name if no org
                website: document.getElementById('sponsor-website').value,
                email: document.getElementById('sponsor-email').value,
                phone: document.getElementById('sponsor-phone').value,
                sponsorship_type: document.getElementById('sponsor-type').value,
                amount_asked: document.getElementById('sponsor-amount-asked').value,
                amount: document.getElementById('sponsor-amount').value,
                frequency: document.getElementById('sponsor-frequency').value,
                start_date: document.getElementById('sponsor-start-date').value,
                status: document.getElementById('sponsor-status').value,
                notes: document.getElementById('sponsor-notes').value
            };
            
            if (!data.first_name || !data.last_name) {
                alert('Please enter contact first and last name');
                return;
            }
            
            const url = sponsorId 
                ? `${window.wpApiSettings.root}claws/v1/sponsors/${sponsorId}`
                : `${window.wpApiSettings.root}claws/v1/sponsors`;
            
            fetch(url, {
                method: sponsorId ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    this.closeModal('claws-sponsor-modal');
                    alert(sponsorId ? 'Sponsor updated successfully!' : 'Sponsor added successfully!');
                } else {
                    alert('Error saving sponsor');
                }
            });
        },
        
        recordAdditionalSponsorship: function(contactName, orgName, email, phone) {
            // Split name into first and last
            const nameParts = contactName.split(' ');
            const firstName = nameParts[0] || '';
            const lastName = nameParts.slice(1).join(' ') || '';
            
            // Open sponsor form with pre-filled, read-only contact info
            this.showAddSponsorForm({
                first_name: firstName,
                last_name: lastName,
                organization_name: orgName,
                email: email,
                phone: phone,
                isAdditional: true  // Flag to make fields read-only
            });
        },
        
        showSponsorList: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/sponsors', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(sponsors => {
                // Group sponsorships by contact name and sort by start_date (oldest first)
                const sponsorGroups = {};
                sponsors.forEach(s => {
                    const contactName = s.contact_name || s.name;
                    if (!sponsorGroups[contactName]) {
                        sponsorGroups[contactName] = [];
                    }
                    sponsorGroups[contactName].push(s);
                });
                
                // Sort each group by start_date (oldest first)
                Object.keys(sponsorGroups).forEach(name => {
                    sponsorGroups[name].sort((a, b) => {
                        const dateA = a.start_date ? new Date(a.start_date) : new Date(0);
                        const dateB = b.start_date ? new Date(b.start_date) : new Date(0);
                        return dateA - dateB;
                    });
                });
                
                // Calculate annual and cumulative totals per contact name
                const currentYear = new Date().getFullYear();
                const sponsorTotals = {};
                
                Object.keys(sponsorGroups).forEach(name => {
                    sponsorTotals[name] = { annual: 0, cumulative: 0 };
                    
                    sponsorGroups[name].forEach(s => {
                        const amount = parseFloat(s.amount) || 0;
                        sponsorTotals[name].cumulative += amount;
                        
                        if (s.start_date) {
                            const sponsorYear = new Date(s.start_date).getFullYear();
                            if (sponsorYear === currentYear) {
                                sponsorTotals[name].annual += amount;
                            }
                        }
                    });
                });
                
                let rows = '';
                
                // Render each sponsor group as an accordion
                Object.keys(sponsorGroups).forEach(contactName => {
                    const sponsorships = sponsorGroups[contactName];
                    const totals = sponsorTotals[contactName];
                    const hasMultiple = sponsorships.length > 1;
                    
                    sponsorships.forEach((sponsor, index) => {
                        const isFirst = index === 0;
                        
                        const truncateNotes = (notes) => {
                            if (!notes) return 'N/A';
                            return notes.length > 50 ? notes.substring(0, 50) + '...' : notes;
                        };
                        
                        // First/oldest entry - full row with accordion toggle if multiple
                        if (isFirst) {
                            const accordionIcon = hasMultiple ? '► ' : '';
                            const accordionClick = hasMultiple ? `onclick="CLAWSApp.toggleSponsorAccordion('${contactName.replace(/'/g, "\\'")}')"` : '';
                            const accordionStyle = hasMultiple ? 'cursor: pointer; user-select: none;' : '';
                            
                            rows += `
                                <tr style="border-bottom: 1px solid #e5e7eb; background: #f9fafb;" data-sponsor-group="${contactName}">
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.name || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.website ? `<a href="${sponsor.website}" target="_blank" style="color: #3b82f6;">🔗 Link</a>` : 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600;" ${accordionClick} ${accordionStyle}>${accordionIcon}${sponsor.contact_name || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.email || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.phone || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.sponsorship_type || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.amount_asked ? '$' + parseFloat(sponsor.amount_asked).toFixed(2) : 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.amount ? '$' + parseFloat(sponsor.amount).toFixed(2) : 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.frequency || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.start_date || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;"><span style="background: ${sponsor.status === 'active' ? '#10b981' : '#6b7280'}; color: white; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem;">${sponsor.status}</span></td>
                                    <td style="padding: 0.75rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${sponsor.notes || 'N/A'}">${truncateNotes(sponsor.notes)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600; color: #059669;">$${totals.annual.toFixed(2)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600; color: #7c3aed;">$${totals.cumulative.toFixed(2)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">
                                        <button onclick="CLAWSApp.recordAdditionalSponsorship('${contactName.replace(/'/g, "\\'")}', '${sponsor.organization_name || ''}', '${sponsor.email || ''}', '${sponsor.phone || ''}')" style="background: #10b981; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;" title="Record Additional Sponsorship">➕</button>
                                        <button onclick="CLAWSApp.editSponsor(${sponsor.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                        <button onclick="CLAWSApp.deleteSponsor(${sponsor.id})" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                                    </td>
                                </tr>
                            `;
                        } else {
                            // Subsequent entries - indented, collapsed by default
                            rows += `
                                <tr class="sponsor-sub-entry sponsor-sub-${contactName.replace(/[^a-zA-Z0-9]/g, '_')}" style="border-bottom: 1px solid #e5e7eb; display: none;">
                                    <td style="padding: 0.75rem 0.75rem 0.75rem 2rem; white-space: nowrap; color: #6b7280;">↳ ${sponsor.name || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.website ? `<a href="${sponsor.website}" target="_blank" style="color: #3b82f6;">🔗 Link</a>` : 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; color: #6b7280;">${sponsor.contact_name || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.email || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.phone || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.sponsorship_type || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.amount_asked ? '$' + parseFloat(sponsor.amount_asked).toFixed(2) : 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.amount ? '$' + parseFloat(sponsor.amount).toFixed(2) : 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.frequency || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.start_date || 'N/A'}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;"><span style="background: ${sponsor.status === 'active' ? '#10b981' : '#6b7280'}; color: white; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem;">${sponsor.status}</span></td>
                                    <td style="padding: 0.75rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${sponsor.notes || 'N/A'}">${truncateNotes(sponsor.notes)}</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; color: #9ca3af;">—</td>
                                    <td style="padding: 0.75rem; white-space: nowrap; color: #9ca3af;">—</td>
                                    <td style="padding: 0.75rem; white-space: nowrap;">
                                        <button onclick="CLAWSApp.editSponsor(${sponsor.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                        <button onclick="CLAWSApp.deleteSponsor(${sponsor.id})" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                                    </td>
                                </tr>
                            `;
                        }
                    });
                });
                
                const modalHtml = `
                    <div id="claws-sponsor-list-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 95vw; width: 95%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
                            <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">🤝 Sponsor List</h3>
                            
                            <div style="overflow-x: auto; overflow-y: auto; flex: 1;">
                                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 1400px;">
                                    <thead style="position: sticky; top: 0; background: white; z-index: 1;">
                                        <tr style="background: #f3f4f6; border-bottom: 2px solid #d1d5db;">
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Organization</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Website</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Contact Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Email</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Phone</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Type</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">$ Asked</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Amount</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Frequency</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Start Date</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Status</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Notes</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Annual Sponsorship</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Cumulative Sponsorship</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${rows || '<tr><td colspan="15" style="padding: 2rem; text-align: center; color: #6b7280;">No sponsors found</td></tr>'}
                                    </tbody>
                                </table>
                            </div>
                            
                            <div style="margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem; display: flex; justify-content: space-between;">
                                <button onclick="CLAWSApp.exportSponsors()" style="background: #10b981; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    📥 Export Sponsors
                                </button>
                                <button onclick="CLAWSApp.closeModal('claws-sponsor-list-modal')" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
            });
        },
        
        showSponsorListFiltered: function(firstName, lastName) {
            const fullName = `${firstName} ${lastName}`;
            fetch(window.wpApiSettings.root + 'claws/v1/sponsors', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(allSponsors => {
                // Filter to matching name (check both contact_name and name fields)
                const sponsors = allSponsors.filter(s => 
                    (s.contact_name && s.contact_name.toLowerCase().includes(fullName.toLowerCase())) ||
                    (s.name && s.name.toLowerCase().includes(fullName.toLowerCase()))
                );
                
                let rows = '';
                sponsors.forEach(sponsor => {
                    const truncateNotes = (notes) => {
                        if (!notes) return 'N/A';
                        return notes.length > 50 ? notes.substring(0, 50) + '...' : notes;
                    };
                    
                    // Highlight matching rows
                    rows += `
                        <tr style="border-bottom: 1px solid #e5e7eb; background: #fef3c7;">
                            <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600;">${sponsor.name}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.website ? `<a href="${sponsor.website}" target="_blank" style="color: #3b82f6;">🔗 Link</a>` : 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap; font-weight: 600;">${sponsor.contact_name || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.email || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.phone || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.sponsorship_type || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.amount_asked ? '$' + parseFloat(sponsor.amount_asked).toFixed(2) : 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.amount ? '$' + parseFloat(sponsor.amount).toFixed(2) : 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.frequency || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${sponsor.start_date || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;"><span style="background: ${sponsor.status === 'active' ? '#10b981' : '#6b7280'}; color: white; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem;">${sponsor.status}</span></td>
                            <td style="padding: 0.75rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${sponsor.notes || 'N/A'}">${truncateNotes(sponsor.notes)}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">
                                <button onclick="CLAWSApp.editSponsor(${sponsor.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                <button onclick="CLAWSApp.deleteSponsor(${sponsor.id})" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                            </td>
                        </tr>
                    `;
                });
                
                const modalHtml = `
                    <div id="claws-sponsor-list-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 95vw; width: 95%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
                            <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">🤝 Sponsor Records for ${fullName}</h3>
                            
                            <div style="overflow-x: auto; overflow-y: auto; flex: 1;">
                                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 1400px;">
                                    <thead style="position: sticky; top: 0; background: white; z-index: 1;">
                                        <tr style="background: #f3f4f6; border-bottom: 2px solid #d1d5db;">
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Organization</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Website</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Contact Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Email</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Phone</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Type</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">$ Asked</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Amount</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Frequency</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Start Date</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Status</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Notes</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${rows || `<tr><td colspan="13" style="padding: 2rem; text-align: center; color: #6b7280;">No sponsor records found for ${fullName}</td></tr>`}
                                    </tbody>
                                </table>
                            </div>
                            
                            <div style="margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem; display: flex; justify-content: space-between;">
                                <button onclick="CLAWSApp.exportSponsors()" style="background: #10b981; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    📥 Export Sponsors
                                </button>
                                <button onclick="CLAWSApp.closeModal('claws-sponsor-list-modal')" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
            });
        },
        
        toggleSponsorAccordion: function(contactName) {
            const className = 'sponsor-sub-' + contactName.replace(/[^a-zA-Z0-9]/g, '_');
            const subRows = document.querySelectorAll('.' + className);
            const mainRow = document.querySelector(`[data-sponsor-group="${contactName}"]`);
            
            if (subRows.length === 0) return;
            
            const isHidden = subRows[0].style.display === 'none';
            
            subRows.forEach(row => {
                row.style.display = isHidden ? 'table-row' : 'none';
            });
            
            // Toggle arrow icon in Contact Name column (third cell)
            if (mainRow) {
                const nameCell = mainRow.querySelectorAll('td')[2]; // Third column (Contact Name)
                if (nameCell) {
                    const currentText = nameCell.textContent.trim();
                    if (isHidden) {
                        nameCell.textContent = currentText.replace('► ', '▼ ');
                    } else {
                        nameCell.textContent = currentText.replace('▼ ', '► ');
                    }
                }
            }
        },
        
        editSponsor: function(sponsorId) {
            fetch(`${window.wpApiSettings.root}claws/v1/sponsors`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(sponsors => {
                const sponsor = sponsors.find(s => s.id === sponsorId);
                if (sponsor) {
                    this.closeModal('claws-sponsor-list-modal');
                    this.showAddSponsorForm(sponsor);
                }
            });
        },
        
        deleteSponsor: function(sponsorId) {
            if (!confirm('Are you sure you want to delete this sponsor?')) return;
            
            fetch(`${window.wpApiSettings.root}claws/v1/sponsors/${sponsorId}`, {
                method: 'DELETE',
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Sponsor deleted successfully');
                    this.showSponsorList();
                }
            });
        },
        
        exportSponsors: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/sponsors', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(sponsors => {
                const headers = ['Organization', 'Contact Name', 'Email', 'Phone', 'Type', 'Amount', 'Frequency', 'Start Date', 'Status'];
                const csvContent = [
                    headers.join(','),
                    ...sponsors.map(s => [
                        `"${s.name}"`,
                        `"${s.contact_name || ''}"`,
                        s.email || '',
                        s.phone || '',
                        s.sponsorship_type || '',
                        s.amount || '',
                        s.frequency || '',
                        s.start_date || '',
                        s.status
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob([csvContent], { type: 'text/csv' });
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `sponsors-${new Date().toISOString().split('T')[0]}.csv`;
                link.click();
                window.URL.revokeObjectURL(url);
            });
        },
        
        /**
         * Volunteer Management Functions
         */
        showAddVolunteerForm: function(volunteerData = null) {
            const isEdit = volunteerData !== null;
            const modalHtml = `
                <div id="claws-volunteer-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">👥 ${isEdit ? 'Edit' : 'Add'} Volunteer Application</h3>
                        
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">First Name *</label>
                                <input type="text" id="volunteer-first-name" value="${isEdit ? volunteerData.first_name : ''}" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Last Name *</label>
                                <input type="text" id="volunteer-last-name" value="${isEdit ? volunteerData.last_name : ''}" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Email${!isEdit ? ' (required if no phone)' : ''}</label>
                                <input type="email" id="volunteer-email" value="${isEdit ? (volunteerData.email || '') : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Phone${!isEdit ? ' (required if no email)' : ''}</label>
                                <input type="tel" id="volunteer-phone" value="${isEdit ? (volunteerData.phone || '') : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Birthday</label>
                                <input type="date" id="volunteer-birthday" value="${isEdit ? (volunteerData.birthday || '') : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Volunteer Type *</label>
                                <select id="volunteer-type" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Select type...</option>
                                    <option value="Generalist" ${isEdit && volunteerData.volunteer_type === 'Generalist' ? 'selected' : ''}>Generalist</option>
                                    <option value="Foster" ${isEdit && volunteerData.volunteer_type === 'Foster' ? 'selected' : ''}>Foster</option>
                                    <option value="Colony Caretaker" ${isEdit && volunteerData.volunteer_type === 'Colony Caretaker' ? 'selected' : ''}>Colony Caretaker</option>
                                </select>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Notes</label>
                                <textarea id="volunteer-notes" rows="3" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">${isEdit ? (volunteerData.notes || '') : ''}</textarea>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Username *</label>
                                <div style="display: flex; gap: 0.5rem;">
                                    <input type="text" id="volunteer-username" value="${isEdit ? (volunteerData.username || '') : ''}" required style="flex: 1; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="WordPress username">
                                    ${isEdit ? `
                                        <button type="button" onclick="CLAWSApp.autoMatchUsername(${volunteerData.id}, 'volunteer')" style="background: #6366f1; color: white; border: none; padding: 0.75rem 1rem; border-radius: 0.5rem; font-size: 0.875rem; white-space: nowrap; cursor: pointer;">
                                            🔍 Auto-Match
                                        </button>
                                    ` : ''}
                                </div>
                                <p style="margin: 0.25rem 0 0; font-size: 0.75rem; color: #6b7280;">Required - volunteers must have a WordPress account</p>
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.saveVolunteerApplication(${isEdit ? volunteerData.id : 'null'})" style="flex: 1; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                ${isEdit ? 'Update' : 'Add'} Application
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-volunteer-modal')" style="flex: 1; background: #6b7280; color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
        },
        
        saveVolunteerApplication: function(volunteerId) {
            const data = {
                first_name: document.getElementById('volunteer-first-name').value,
                last_name: document.getElementById('volunteer-last-name').value,
                email: document.getElementById('volunteer-email').value,
                phone: document.getElementById('volunteer-phone').value,
                birthday: document.getElementById('volunteer-birthday').value,
                volunteer_type: document.getElementById('volunteer-type').value,
                notes: document.getElementById('volunteer-notes').value,
                username: document.getElementById('volunteer-username').value
            };
            
            if (!data.first_name || !data.last_name) {
                alert('Please enter first and last name');
                return;
            }
            
            if (!data.email && !data.phone) {
                alert('Please provide either an email or phone number');
                return;
            }
            
            if (!data.volunteer_type) {
                alert('Please select a volunteer type');
                return;
            }
            
            if (!data.username) {
                alert('Username is required for volunteers');
                return;
            }
            
            const url = volunteerId 
                ? `${window.wpApiSettings.root}claws/v1/volunteer-applications/${volunteerId}`
                : `${window.wpApiSettings.root}claws/v1/volunteer-applications`;
            
            fetch(url, {
                method: volunteerId ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    this.closeModal('claws-volunteer-modal');
                    alert(volunteerId ? 'Volunteer application updated successfully!' : 'Volunteer application added successfully!');
                    this.loadVolunteerAdmin(); // Refresh pending list
                } else {
                    alert('Error saving application');
                }
            });
        },
        
        showVolunteerList: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-applications?status=approved', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(volunteers => {
                let rows = '';
                volunteers.forEach(vol => {
                    const truncateNotes = (notes) => {
                        if (!notes) return 'N/A';
                        return notes.length > 50 ? notes.substring(0, 50) + '...' : notes;
                    };
                    
                    rows += `
                        <tr style="border-bottom: 1px solid #e5e7eb;">
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.first_name || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.last_name || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.email || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.phone || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.birthday || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.volunteer_type}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.username || 'N/A'}</td>
                            <td style="padding: 0.75rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${vol.notes || 'N/A'}">${truncateNotes(vol.notes)}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${new Date(vol.submitted_date).toLocaleDateString()}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${new Date(vol.reviewed_date).toLocaleDateString()}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${vol.reviewed_by || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">
                                <button onclick="CLAWSApp.editVolunteerFromList(${vol.id})" style="background: #3b82f6; color: white; border: none; padding: 0.5rem 0.75rem; border-radius: 0.375rem; font-size: 0.75rem; cursor: pointer; margin-right: 0.25rem;" title="Edit Volunteer">
                                    ✏️ Edit
                                </button>
                                <button onclick="CLAWSApp.deleteVolunteerFromList(${vol.id}, '${vol.first_name} ${vol.last_name}')" style="background: #ef4444; color: white; border: none; padding: 0.5rem 0.75rem; border-radius: 0.375rem; font-size: 0.75rem; cursor: pointer;" title="Delete Volunteer">
                                    🗑️ Delete
                                </button>
                            </td>
                        </tr>
                    `;
                });
                
                const modalHtml = `
                    <div id="claws-volunteer-list-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 95vw; width: 95%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
                            <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">👥 Approved Volunteers</h3>
                            
                            <div style="overflow-x: auto; overflow-y: auto; flex: 1;">
                                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 1200px;">
                                    <thead style="position: sticky; top: 0; background: white; z-index: 1;">
                                        <tr style="background: #f3f4f6; border-bottom: 2px solid #d1d5db;">
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">First Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Last Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Email</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Phone</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Birthday</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Type</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Username</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Notes</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Submitted</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Approved</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Reviewed By</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${rows || '<tr><td colspan="12" style="padding: 2rem; text-align: center; color: #6b7280;">No approved volunteers found</td></tr>'}
                                    </tbody>
                                </table>
                            </div>
                            
                            <div style="margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem;">
                                <button onclick="CLAWSApp.closeModal('claws-volunteer-list-modal')" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
            });
        },
        
        editVolunteerFromList: function(volunteerId) {
            // Fetch volunteer data and open edit form
            fetch(`${window.wpApiSettings.root}claws/v1/volunteer-applications/${volunteerId}`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(volunteer => {
                this.closeModal('claws-volunteer-list-modal');
                this.showEditVolunteerForm(volunteer);
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error fetching volunteer:', error);
                alert('Error loading volunteer data');
            });
        },
        
        deleteVolunteerFromList: function(volunteerId, volunteerName) {
            if (confirm(`Are you sure you want to delete volunteer "${volunteerName}"? This action cannot be undone.`)) {
                fetch(`${window.wpApiSettings.root}claws/v1/volunteer-applications/${volunteerId}`, {
                    method: 'DELETE',
                    headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        alert('Volunteer deleted successfully');
                        this.closeModal('claws-volunteer-list-modal');
                        // Refresh the volunteer list if needed
                        this.loadVolunteerContent();
                    } else {
                        alert(result.message || 'Error deleting volunteer');
                    }
                })
                .catch(error => {
                    (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error deleting volunteer:', error);
                    alert('Error deleting volunteer');
                });
            }
        },
        
        showEditVolunteerForm: function(volunteer) {
            const modalHtml = `
                <div id="claws-edit-volunteer-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10001;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">✏️ Edit Volunteer</h3>
                        
                        <div style="display: grid; gap: 1rem;">
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">First Name *</label>
                                <input type="text" id="edit-vol-first-name" value="${volunteer.first_name || ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Last Name *</label>
                                <input type="text" id="edit-vol-last-name" value="${volunteer.last_name || ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Email *</label>
                                <input type="email" id="edit-vol-email" value="${volunteer.email || ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Phone</label>
                                <input type="tel" id="edit-vol-phone" value="${volunteer.phone || ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Birthday</label>
                                <input type="date" id="edit-vol-birthday" value="${volunteer.birthday || ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Volunteer Type *</label>
                                <select id="edit-vol-type" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="Generalist" ${volunteer.volunteer_type === 'Generalist' ? 'selected' : ''}>Generalist</option>
                                    <option value="Foster" ${volunteer.volunteer_type === 'Foster' ? 'selected' : ''}>Foster</option>
                                    <option value="Colony Caretaker" ${volunteer.volunteer_type === 'Colony Caretaker' ? 'selected' : ''}>Colony Caretaker</option>
                                </select>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Username</label>
                                <input type="text" id="edit-vol-username" value="${volunteer.username || ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Notes</label>
                                <textarea id="edit-vol-notes" rows="4" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">${volunteer.notes || ''}</textarea>
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.saveVolunteerEdit(${volunteer.id})" style="flex: 1; background: #3b82f6; color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                Save Changes
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-edit-volunteer-modal')" style="flex: 1; background: #6b7280; color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML += modalHtml;
        },
        
        saveVolunteerEdit: function(volunteerId) {
            const data = {
                first_name: document.getElementById('edit-vol-first-name').value.trim(),
                last_name: document.getElementById('edit-vol-last-name').value.trim(),
                email: document.getElementById('edit-vol-email').value.trim(),
                phone: document.getElementById('edit-vol-phone').value.trim(),
                birthday: document.getElementById('edit-vol-birthday').value,
                volunteer_type: document.getElementById('edit-vol-type').value,
                username: document.getElementById('edit-vol-username').value.trim(),
                notes: document.getElementById('edit-vol-notes').value.trim()
            };
            
            if (!data.first_name || !data.last_name || !data.email || !data.volunteer_type) {
                alert('Please fill in all required fields');
                return;
            }
            
            fetch(`${window.wpApiSettings.root}claws/v1/volunteer-applications/${volunteerId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Volunteer updated successfully');
                    this.closeModal('claws-edit-volunteer-modal');
                    // Refresh volunteer list
                    this.loadVolunteerContent();
                } else {
                    alert(result.message || 'Error updating volunteer');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error updating volunteer:', error);
                alert('Error updating volunteer');
            });
        },
        
        exportVolunteers: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-applications?status=approved', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(volunteers => {
                const headers = ['Name', 'Email', 'Phone', 'Type', 'Submitted Date', 'Approved Date', 'Reviewed By'];
                const csvContent = [
                    headers.join(','),
                    ...volunteers.map(v => [
                        `"${v.name}"`,
                        v.email,
                        v.phone,
                        v.volunteer_type,
                        v.submitted_date,
                        v.reviewed_date || '',
                        `"${v.reviewed_by || ''}"`
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob([csvContent], { type: 'text/csv' });
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `volunteers-${new Date().toISOString().split('T')[0]}.csv`;
                link.click();
                window.URL.revokeObjectURL(url);
            });
        },
        
        showFormIntegrationSettings: function() {
            const modalHtml = `
                <div id="claws-form-integration-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">⚙️ Form Integration Settings</h3>
                        
                        <div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem;">
                            <p style="margin: 0; font-size: 0.875rem; color: #92400e;"><strong>Coming Soon:</strong> Fluent Forms integration will allow automatic import of volunteer applications from your website forms.</p>
                        </div>
                        
                        <div style="background: #f3f4f6; border-radius: 0.5rem; padding: 1.5rem;">
                            <h4 style="margin: 0 0 1rem 0; font-size: 1rem; font-weight: 600; color: #1f2937;">Planned Features:</h4>
                            <ul style="margin: 0; padding-left: 1.5rem; color: #374151; font-size: 0.875rem; line-height: 1.8;">
                                <li>Connect to Fluent Forms, Gravity Forms, WPForms</li>
                                <li>Map form fields to volunteer data</li>
                                <li>Auto-create pending applications</li>
                                <li>Duplicate detection</li>
                                <li>Webhook support for custom integrations</li>
                            </ul>
                        </div>
                        
                        <div style="margin-top: 2rem;">
                            <button onclick="CLAWSApp.closeModal('claws-form-integration-modal')" style="width: 100%; background: #6b7280; color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
        },
        
        /**
         * Close modal helper
         */
        closeModal: function(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) modal.remove();
        },
        
        /**
         * Contact Management Functions
         */
        showAddContactForm: function(contactData = null) {
            
            const container = document.getElementById('claws-admin-modals-container');
            if (!container) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Modal container not found! Creating it...');
                const newContainer = document.createElement('div');
                newContainer.id = 'claws-admin-modals-container';
                document.body.appendChild(newContainer);
            }
            
            const isEdit = contactData !== null;
            const modalHtml = `
                <div id="claws-contact-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">📇 ${isEdit ? 'Edit' : 'Add'} Contact</h3>
                        
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">First Name *</label>
                                <input type="text" id="contact-first-name" value="${isEdit ? contactData.first_name : ''}" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Last Name *</label>
                                <input type="text" id="contact-last-name" value="${isEdit ? contactData.last_name : ''}" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Email${!isEdit ? ' (required if no phone)' : ''}</label>
                                <input type="email" id="contact-email" value="${isEdit ? (contactData.email || '') : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Phone${!isEdit ? ' (required if no email)' : ''}</label>
                                <input type="tel" id="contact-phone" value="${isEdit ? (contactData.phone || '') : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 0.5rem; padding: 0.75rem;">
                                <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer; margin: 0;">
                                    <input type="checkbox" id="contact-do-not-contact" ${isEdit && contactData.do_not_contact ? 'checked' : ''} style="width: 1.25rem; height: 1.25rem; cursor: pointer;">
                                    <div>
                                        <span style="font-weight: 600; color: #92400e; font-size: 0.875rem;">Do Not Contact Me</span>
                                        <p style="margin: 0.25rem 0 0; font-size: 0.75rem; color: #78350f;">Check this if you prefer not to receive mass mailings or newsletters</p>
                                    </div>
                                </label>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Birthday</label>
                                <input type="date" id="contact-birthday" value="${isEdit ? (contactData.birthday || '') : ''}" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Contact Type</label>
                                <select id="contact-type" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="interested" ${isEdit && contactData.contact_type === 'interested' ? 'selected' : ''}>Interested</option>
                                    <option value="colony-caretaker" ${isEdit && contactData.contact_type === 'colony-caretaker' ? 'selected' : ''}>Colony Caretaker</option>
                                    <option value="other" ${isEdit && contactData.contact_type === 'other' ? 'selected' : ''}>Other</option>
                                </select>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Notes</label>
                                <textarea id="contact-notes" rows="3" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">${isEdit ? (contactData.notes || '') : ''}</textarea>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Username</label>
                                <div style="display: flex; gap: 0.5rem;">
                                    <input type="text" id="contact-username" value="${isEdit ? (contactData.username || '') : ''}" style="flex: 1; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="WordPress username">
                                    ${isEdit ? `
                                        <button type="button" onclick="CLAWSApp.autoMatchUsername(${contactData.id}, 'contact')" style="background: #6366f1; color: white; border: none; padding: 0.75rem 1rem; border-radius: 0.5rem; font-size: 0.875rem; white-space: nowrap; cursor: pointer;">
                                            🔍 Auto-Match
                                        </button>
                                    ` : ''}
                                </div>
                                <p style="margin: 0.25rem 0 0; font-size: 0.75rem; color: #6b7280;">Auto-match searches WordPress users by email to find matching username</p>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: 0.75rem; font-weight: 600; color: #374151;">Contact Attributes</label>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                    ${Object.entries(clawsData.contactAttributes || {}).map(([key, label]) => `
                                        <label style="display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem; border: 1px solid #e5e7eb; border-radius: 0.375rem; cursor: pointer;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='white'">
                                            <input type="checkbox" class="contact-attr-checkbox" value="${key}" ${isEdit && contactData.attributes && contactData.attributes.includes(key) ? 'checked' : ''} style="width: 1rem; height: 1rem;">
                                            <span style="font-size: 0.875rem;">${label}</span>
                                        </label>
                                    `).join('')}
                                </div>
                                <p style="margin: 0.75rem 0 0; font-size: 0.75rem; color: #6b7280; line-height: 1.4;">
                                    ℹ️ <strong>Note:</strong> Checking "Donor" or "Sponsor" will save this contact and automatically open the respective form to complete additional details.
                                </p>
                            </div>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.saveContact(${isEdit ? contactData.id : 'null'})" style="flex: 1; background: var(--claws-primary-button-color); color: var(--claws-button-text-color); border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                ${isEdit ? 'Update' : 'Add'} Contact
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-contact-modal')" style="flex: 1; background: #6b7280; color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
        },
        
        saveContact: function(contactId) {
            const data = {
                first_name: document.getElementById('contact-first-name').value,
                last_name: document.getElementById('contact-last-name').value,
                email: document.getElementById('contact-email').value,
                phone: document.getElementById('contact-phone').value,
                do_not_contact: document.getElementById('contact-do-not-contact')?.checked || false,
                birthday: document.getElementById('contact-birthday').value,
                contact_type: document.getElementById('contact-type').value,
                notes: document.getElementById('contact-notes').value,
                username: document.getElementById('contact-username').value,
                attributes: []
            };
            
            // Collect all checked attributes using class selector
            const checkboxes = document.querySelectorAll('.contact-attr-checkbox:checked');
            checkboxes.forEach(checkbox => {
                data.attributes.push(checkbox.value);
            });
            
            // Check if donor or sponsor attributes are selected
            const isDonorChecked = data.attributes.includes('donor');
            const isSponsorChecked = data.attributes.includes('potential_volunteer'); // 'potential_volunteer' key maps to 'Sponsor' label
            
            // Auto-add notes for donor/sponsor (similar to "Created from intake" pattern)
            let autoNotes = [];
            if (isDonorChecked && !data.notes.includes('Is Donor')) {
                autoNotes.push('Is Donor');
            }
            if (isSponsorChecked && !data.notes.includes('Is Sponsor')) {
                autoNotes.push('Is Sponsor');
            }
            if (autoNotes.length > 0) {
                data.notes = data.notes ? `${data.notes}\n${autoNotes.join('\n')}` : autoNotes.join('\n');
            }
            
            if (!data.first_name || !data.last_name) {
                alert('Please enter first and last name');
                return;
            }
            
            if (!data.email && !data.phone) {
                alert('Please provide either an email or phone number');
                return;
            }
            
            const url = contactId 
                ? `${window.wpApiSettings.root}claws/v1/contacts/${contactId}`
                : `${window.wpApiSettings.root}claws/v1/contacts`;
            
            fetch(url, {
                method: contactId ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    this.closeModal('claws-contact-modal');
                    alert(contactId ? 'Contact updated successfully!' : 'Contact added successfully!');
                    
                    // Auto-open donor/sponsor forms if checked
                    if (isDonorChecked) {
                        setTimeout(() => {
                            this.showAddDonorForm({
                                first_name: data.first_name,
                                last_name: data.last_name,
                                email: data.email,
                                phone: data.phone
                            });
                        }, 500);
                    }
                    
                    if (isSponsorChecked) {
                        const delay = isDonorChecked ? 1000 : 500; // If both checked, delay sponsor form
                        setTimeout(() => {
                            this.showAddSponsorForm({
                                first_name: data.first_name,
                                last_name: data.last_name,
                                email: data.email,
                                phone: data.phone
                            });
                        }, delay);
                    }
                } else {
                    alert(result.message || 'Error saving contact');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error saving contact');
            });
        },
        
        showContactList: function(filterAttribute = 'none') {
            fetch(window.wpApiSettings.root + 'claws/v1/contacts?status=active', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(allContacts => {
                // Apply filter
                let contacts = allContacts;
                if (filterAttribute !== 'none') {
                    contacts = allContacts.filter(contact => {
                        return contact.attributes && contact.attributes.includes(filterAttribute);
                    });
                }
                
                let rows = '';
                contacts.forEach(contact => {
                    const displayName = `${contact.first_name} ${contact.last_name}`;
                    const truncateNotes = (notes) => {
                        if (!notes) return 'N/A';
                        return notes.length > 50 ? notes.substring(0, 50) + '...' : notes;
                    };
                    const hasUsername = contact.username && contact.username.trim();
                    
                    // Format attributes as badges (with clickable donor/sponsor badges)
                    let attributesBadges = '';
                    if (contact.attributes && contact.attributes.length > 0) {
                        attributesBadges = contact.attributes.map(attr => {
                            // Check if this is donor or sponsor - make them clickable
                            if (attr === 'donor') {
                                return `<span onclick="CLAWSApp.showDonorListFiltered('${contact.first_name}', '${contact.last_name}')" style="background: #10b981; color: white; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.625rem; white-space: nowrap; display: inline-block; margin: 0.125rem; cursor: pointer; font-weight: 600;" title="Click to view donor records">💰 Donor</span>`;
                            } else if (attr === 'potential_volunteer') {
                                return `<span onclick="CLAWSApp.showSponsorListFiltered('${contact.first_name}', '${contact.last_name}')" style="background: #f59e0b; color: white; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.625rem; white-space: nowrap; display: inline-block; margin: 0.125rem; cursor: pointer; font-weight: 600;" title="Click to view sponsor records">🤝 Sponsor</span>`;
                            } else {
                                // Regular attribute badges
                                const label = attr.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                                return `<span style="background: #dbeafe; color: #1e40af; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.625rem; white-space: nowrap; display: inline-block; margin: 0.125rem;">${label}</span>`;
                            }
                        }).join('');
                    } else {
                        attributesBadges = '<span style="color: #9ca3af; font-size: 0.75rem;">None</span>';
                    }
                    
                    // Add "Do Not Contact" flag if applicable
                    if (contact.do_not_contact === true || contact.do_not_contact === 'true' || contact.do_not_contact === '1') {
                        attributesBadges += '<span style="background: #fef3c7; color: #92400e; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.625rem; white-space: nowrap; display: inline-block; margin: 0.125rem; font-weight: 600;" title="This contact prefers not to receive mass mailings">🚫 Do Not Contact</span>';
                    }
                    
                    rows += `
                        <tr style="border-bottom: 1px solid #e5e7eb;">
                            <td style="padding: 0.75rem; white-space: nowrap;">${contact.first_name || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${contact.last_name || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${contact.email || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${contact.phone || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${contact.birthday || 'N/A'}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${contact.contact_type || 'N/A'}</td>
                            <td style="padding: 0.75rem;">${attributesBadges}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${hasUsername ? `✅ ${contact.username}` : '❌ None'}</td>
                            <td style="padding: 0.75rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${contact.notes || 'N/A'}">${truncateNotes(contact.notes)}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">${new Date(contact.created_date).toLocaleDateString()}</td>
                            <td style="padding: 0.75rem; white-space: nowrap;">
                                <button onclick="CLAWSApp.editContact(${contact.id})" style="background: #3b82f6; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; margin-right: 0.5rem; font-size: 0.75rem;">Edit</button>
                                <button onclick="CLAWSApp.showDeleteContactForm(${contact.id}, '${displayName.replace(/'/g, "\\'")}', '${contact.email || contact.phone}')" style="background: #ef4444; color: white; border: none; padding: 0.375rem 0.75rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.75rem;">Delete</button>
                            </td>
                        </tr>
                    `;
                });
                
                const counterText = filterAttribute === 'none' ? `${allContacts.length} contacts` : `${contacts.length} of ${allContacts.length} contacts`;
                
                const modalHtml = `
                    <div id="claws-contact-list-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                        <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 95vw; width: 95%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                                <h3 style="margin: 0; font-size: 1.5rem; color: #1f2937;">📇 Contact List <span style="font-size: 0.875rem; color: #6b7280; font-weight: normal;">(${counterText})</span></h3>
                                <div style="display: flex; align-items: center; gap: 0.5rem;">
                                    <label style="font-size: 0.875rem; color: #374151; font-weight: 600;">Filter:</label>
                                    <select id="contact-filter" onchange="CLAWSApp.showContactList(this.value)" style="padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                                        <option value="none" ${filterAttribute === 'none' ? 'selected' : ''}>None (Show All)</option>
                                        ${Object.entries(clawsData.contactAttributes || {}).map(([key, label]) => `
                                            <option value="${key}" ${filterAttribute === key ? 'selected' : ''}>${label}</option>
                                        `).join('')}
                                    </select>
                                </div>
                            </div>
                            
                            <div style="overflow-x: auto; overflow-y: auto; flex: 1;">
                                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem; min-width: 1400px;">
                                    <thead style="position: sticky; top: 0; background: white; z-index: 1;">
                                        <tr style="background: #f3f4f6; border-bottom: 2px solid #d1d5db;">
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">First Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Last Name</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Email</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Phone</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Birthday</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Type</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Attributes</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Username</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Notes</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Created</th>
                                            <th style="padding: 0.75rem; text-align: left; white-space: nowrap;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${rows || '<tr><td colspan="11" style="padding: 2rem; text-align: center; color: #6b7280;">No contacts found</td></tr>'}
                                    </tbody>
                                </table>
                            </div>
                            
                            <div style="margin-top: 1.5rem; border-top: 1px solid #e5e7eb; padding-top: 1rem; display: flex; justify-content: space-between;">
                                <button onclick="CLAWSApp.exportContacts()" style="background: #10b981; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    📥 Export Contacts
                                </button>
                                <button onclick="CLAWSApp.closeModal('claws-contact-list-modal')" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error loading contacts');
            });
        },
        
        editContact: function(contactId) {
            fetch(`${window.wpApiSettings.root}claws/v1/contacts?status=active`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(contacts => {
                const contact = contacts.find(c => c.id === contactId);
                if (contact) {
                    this.closeModal('claws-contact-list-modal');
                    this.showAddContactForm(contact);
                }
            });
        },
        
        
        showDeleteContactForm: function(contactId, name, contact) {
            const modalHtml = `
                <div id="claws-delete-contact-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10001;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">❌ Delete Contact</h3>
                        
                        <div style="background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem;">
                            <p style="margin: 0; font-size: 0.875rem; color: #991b1b;">
                                <strong>Contact:</strong> ${name}<br>
                                <strong>Info:</strong> ${contact}
                            </p>
                        </div>
                        
                        <div>
                            <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Deletion Reason (Required) *</label>
                            <textarea id="delete-contact-reason" rows="4" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="Provide a reason for deletion. This will be stored for internal reference."></textarea>
                            <p style="margin: 0.5rem 0 0; font-size: 0.75rem; color: #6b7280;">Note: The contact will be soft-deleted and remain visible in the backend for reference.</p>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.deleteContact(${contactId})" style="flex: 1; background: #ef4444; color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                Delete Contact
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-delete-contact-modal')" style="flex: 1; background: #6b7280; color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); padding: 0.75rem; border-radius: 0.75rem; font-weight: 600; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML += modalHtml;
        },
        
        deleteContact: function(contactId) {
            const reason = document.getElementById('delete-contact-reason').value.trim();
            
            if (!reason) {
                alert('Please provide a reason for deletion');
                return;
            }
            
            fetch(`${window.wpApiSettings.root}claws/v1/contacts/${contactId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ reason: reason })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    this.closeModal('claws-delete-contact-modal');
                    alert('Contact deleted successfully');
                    this.showContactList();
                } else {
                    alert(result.message || 'Error deleting contact');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error deleting contact');
            });
        },
        
        exportContacts: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/contacts?status=active', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(contacts => {
                const headers = ['First Name', 'Last Name', 'Email', 'Phone', 'Do Not Contact', 'Birthday', 'Contact Type', 'Notes', 'Created Date'];
                const csvContent = [
                    headers.join(','),
                    ...contacts.map(c => [
                        `"${c.first_name}"`,
                        `"${c.last_name}"`,
                        c.email || '',
                        c.phone || '',
                        (c.do_not_contact === true || c.do_not_contact === 'true' || c.do_not_contact === '1') ? 'Yes' : 'No',
                        c.birthday || '',
                        c.contact_type || '',
                        `"${(c.notes || '').replace(/"/g, '""')}"`,
                        c.created_date
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob([csvContent], { type: 'text/csv' });
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = `contacts-${new Date().toISOString().split('T')[0]}.csv`;
                link.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error exporting contacts');
            });
        },
        
        /**
         * Auto-match username by searching WordPress users by email
         */
        autoMatchUsername: function(recordId, recordType) {
            // Get email from form
            const emailField = recordType === 'contact' ? 'contact-email' : 'volunteer-email';
            const usernameField = recordType === 'contact' ? 'contact-username' : 'volunteer-username';
            const email = document.getElementById(emailField).value;
            
            if (!email) {
                alert('Please enter an email address first');
                return;
            }
            
            // Call API to match username
            fetch(`${window.wpApiSettings.root}claws/v1/match-username`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ 
                    email: email,
                    record_id: recordId,
                    record_type: recordType
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success && result.username) {
                    document.getElementById(usernameField).value = result.username;
                    alert(`✓ Found matching username: ${result.username}`);
                    
                    // If contact form, enable the elevate button
                    if (recordType === 'contact') {
                        const elevateBtn = document.getElementById(`elevate-btn-${recordId}`);
                        if (elevateBtn) {
                            elevateBtn.disabled = false;
                            elevateBtn.style.background = 'linear-gradient(135deg, #3b82f6, #1d4ed8)';
                            elevateBtn.style.cursor = 'pointer';
                        }
                    }
                } else {
                    alert(result.message || 'No matching WordPress user found for this email');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error:', error);
                alert('Error searching for username');
            });
        },
        
        /**
         * Helper to escape HTML
         */
        escapeHtml: function(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        },

        loadVolunteerAdmin: function() {
            this.loadTasksNeedingApproval();
            this.loadApprovedTasksForAdmin();
            this.loadPendingVolunteerApplications();
            this.loadDeniedVolunteerApplications();
        },
        
        /**
         * Load pending volunteer applications
         */
        loadPendingVolunteerApplications: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-applications?status=pending', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(applications => {
                if (applications && applications.length > 0) {
                    applications.forEach(app => {
                        const appHtml = `
                            <div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem;">
                                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                    <div>
                                        <p style="margin: 0; font-weight: 600; color: #92400e;">👥 ${app.name}</p>
                                        <p style="margin: 0.25rem 0 0; font-size: 0.75rem; color: #92400e;">${app.volunteer_type} Volunteer</p>
                                    </div>
                                </div>
                                <p style="margin: 0.5rem 0; font-size: 0.875rem; color: #92400e;">
                                    <strong>Email:</strong> ${app.email}<br>
                                    <strong>Phone:</strong> ${app.phone}<br>
                                    <strong>Submitted:</strong> ${new Date(app.submitted_date).toLocaleDateString()}
                                </p>
                                <div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
                                    <button onclick="CLAWSApp.approveVolunteerApplication(${app.id})" style="background: #10b981; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.375rem; font-size: 0.875rem; font-weight: 500; cursor: pointer;">
                                        ✅ Approve
                                    </button>
                                    <button onclick="CLAWSApp.showDenyVolunteerForm(${app.id}, '${app.name.replace(/'/g, "\\'")}', '${app.email}')" style="background: #ef4444; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.375rem; font-size: 0.875rem; font-weight: 500; cursor: pointer;">
                                        ❌ Deny
                                    </button>
                                </div>
                            </div>
                        `;
                        
                        const container = document.querySelector('#claws-admin-pending');
                        if (container) {
                            // Append to existing content or replace empty message
                            if (container.innerHTML.includes('No pending items')) {
                                container.innerHTML = appHtml;
                            } else {
                                container.innerHTML += appHtml;
                            }
                        }
                    });
                }
            })
            .catch(error => (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading volunteer applications:', error));
        },
        
        /**
         * Load denied volunteer applications
         */
        loadDeniedVolunteerApplications: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-applications?status=denied', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(applications => {
                const container = document.querySelector('#claws-admin-denied');
                if (!container) return;
                
                if (!applications || applications.length === 0) {
                    container.innerHTML = '<p style="color: #6b7280; text-align: center; padding: 1.5rem; font-size: 0.875rem;">No denied applications.</p>';
                    return;
                }
                
                let html = '';
                applications.forEach(app => {
                    html += `
                        <div style="background: #fee2e2; border: 1px solid #ef4444; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1rem;">
                            <p style="margin: 0; font-weight: 600; color: #991b1b;">${app.name} - ${app.volunteer_type}</p>
                            <p style="margin: 0.5rem 0; font-size: 0.875rem; color: #991b1b;">
                                <strong>Email:</strong> ${app.email}<br>
                                <strong>Phone:</strong> ${app.phone}<br>
                                <strong>Denied:</strong> ${new Date(app.reviewed_date).toLocaleDateString()} by ${app.reviewed_by}
                            </p>
                            <div style="background: #fef2f2; border-radius: 0.375rem; padding: 0.75rem; margin-top: 0.75rem;">
                                <p style="margin: 0; font-size: 0.75rem; font-weight: 600; color: #991b1b;">Reason:</p>
                                <p style="margin: 0.25rem 0 0; font-size: 0.875rem; color: #7f1d1d;">${app.denial_reason}</p>
                            </div>
                        </div>
                    `;
                });
                
                container.innerHTML = html;
            })
            .catch(error => (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading denied applications:', error));
        },
        
        /**
         * Approve volunteer application
         */
        approveVolunteerApplication: function(appId) {
            if (!confirm('Approve this volunteer application? An email will be sent to the applicant.')) return;
            
            fetch(`${window.wpApiSettings.root}claws/v1/volunteer-applications/${appId}/approve`, {
                method: 'POST',
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('Application approved! Email sent to applicant.');
                    this.loadVolunteerAdmin();
                } else {
                    alert('Error approving application');
                }
            });
        },
        
        /**
         * Show deny form for volunteer application
         */
        showDenyVolunteerForm: function(appId, name, email) {
            const modalHtml = `
                <div id="claws-deny-volunteer-modal" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%;">
                        <h3 style="margin: 0 0 1.5rem 0; font-size: 1.5rem; color: #1f2937;">❌ Deny Volunteer Application</h3>
                        
                        <div style="background: #fef2f2; border: 1px solid #fecaca; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem;">
                            <p style="margin: 0; font-size: 0.875rem; color: #991b1b;">
                                <strong>Applicant:</strong> ${name}<br>
                                <strong>Email:</strong> ${email}
                            </p>
                        </div>
                        
                        <div>
                            <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Denial Reason (Required) *</label>
                            <textarea id="denial-reason" rows="4" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="Provide a reason for denial. This will be stored for internal reference."></textarea>
                            <p style="margin: 0.5rem 0 0; font-size: 0.75rem; color: #6b7280;">Note: The denial reason is for internal use only. A generic email will be sent to the applicant.</p>
                        </div>
                        
                        <div style="display: flex; gap: 1rem; margin-top: 2rem;">
                            <button onclick="CLAWSApp.denyVolunteerApplication(${appId})" style="flex: 1; background: #ef4444; color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                Deny Application
                            </button>
                            <button onclick="CLAWSApp.closeModal('claws-deny-volunteer-modal')" style="flex: 1; background: #6b7280; color: white; border: none; padding: 0.75rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer;">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('claws-admin-modals-container').innerHTML = modalHtml;
        },
        
        /**
         * Deny volunteer application
         */
        denyVolunteerApplication: function(appId) {
            const reason = document.getElementById('denial-reason').value.trim();
            
            if (!reason) {
                alert('Please provide a reason for denial');
                return;
            }
            
            fetch(`${window.wpApiSettings.root}claws/v1/volunteer-applications/${appId}/deny`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ reason: reason })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    this.closeModal('claws-deny-volunteer-modal');
                    alert('Application denied. Email sent to applicant.');
                    this.loadVolunteerAdmin();
                } else {
                    alert('Error denying application');
                }
            });
        },
        
        /**
         * Load tasks that need approval (for Admin tab)
         */
        loadTasksNeedingApproval: function() {
            const container = document.querySelector('#claws-admin-pending');
            
            if (!container) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                return response.json();
            })
            .then(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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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');
            
            if (!container) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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;
            
            fetch(window.wpApiSettings.root + 'claws/v1/volunteer-time/pending?view=my', {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            })
            .then(response => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Pending items response status:', response.status);
                return response.json();
            })
            .then(entries => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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.');
                }
            }
            
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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) {
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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
                
                // 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';
                }
                
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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;
            }
            
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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() {
            // CRITICAL: Load config first (for standalone shortcode usage)
            this.loadConfig();
            
            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() {
            // CRITICAL: Load config first (for standalone shortcode usage)
            this.loadConfig();
            
            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: var(--claws-primary-button-color); border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; font-weight: 600; transition: all 0.2s ease; color: white; margin-bottom: 0.5rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                            Record New Discharge
                        </button>
                        <button onclick="CLAWSApp.exportDischargeData()" style="width: 100%; background: var(--claws-secondary-button-color); border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; font-weight: 600; transition: all 0.2s ease; color: white; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                            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 rawOutcome = record.outcome || 'Unknown';
                
                // NORMALIZE OUTCOME: Handle long backend-edited outcomes
                // Example: "Transfer to on-site shelter for eventual adoption" → "Transfer"
                let outcome = rawOutcome;
                if (rawOutcome.toLowerCase().includes('transfer')) {
                    outcome = 'Transfer';
                } else if (rawOutcome.toLowerCase().includes('adoption') || rawOutcome.toLowerCase().includes('adopted')) {
                    outcome = 'Adoption';
                } else if (rawOutcome.toLowerCase().includes('foster')) {
                    outcome = 'Foster to Adopt';
                } else if (rawOutcome.toLowerCase().includes('tnr') || rawOutcome.toLowerCase().includes('trap') || rawOutcome.toLowerCase().includes('neuter')) {
                    outcome = 'TNR';
                } else if (rawOutcome.toLowerCase().includes('died') || rawOutcome.toLowerCase().includes('death')) {
                    outcome = 'Died';
                } else if (rawOutcome.toLowerCase().includes('euthan')) {
                    outcome = 'Euthanasia';
                } else if (rawOutcome.toLowerCase().includes('return') && rawOutcome.toLowerCase().includes('owner')) {
                    outcome = 'Returned to Owner';
                } else if (rawOutcome.toLowerCase().includes('escape')) {
                    outcome = 'Escaped';
                }
                
                // Color coding by normalized 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() {
            // CRITICAL: Load config first (for standalone shortcode usage)
            this.loadConfig();
            
            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: var(--claws-primary-button-color); color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); border-radius: 0.75rem; padding: 0.75rem 1.5rem; font-weight: 600; cursor: pointer; font-size: 0.875rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); transition: all 0.2s ease;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                💾 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: var(--claws-secondary-button-color); color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); border-radius: 0.75rem; padding: 1rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">📊</div>
                                <div>Export Data</div>
                            </button>
                            <button onclick="CLAWSApp.showCareGuide()" style="background: var(--claws-primary-button-color); color: white; border: none; border-top: 1px solid rgba(255, 255, 255, 0.3); border-bottom: 2px solid rgba(0, 0, 0, 0.2); border-radius: 0.75rem; padding: 1rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1); text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                                <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 modal
            const modal = document.createElement('div');
            modal.id = 'care-guide-modal';
            modal.innerHTML = `
                <div id="care-guide-backdrop" 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 id="care-guide-close-x" 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 0 1.5rem 0;">${guidelines}</pre>
                        <div style="text-align: center;">
                            <button id="care-guide-close-btn" style="background: #3b82f6; color: white; border: none; border-radius: 6px; padding: 0.75rem 2rem; cursor: pointer; font-size: 1rem; font-weight: 500;">Close</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // Add event listeners AFTER modal is in DOM
            const closeX = document.getElementById('care-guide-close-x');
            const closeBtn = document.getElementById('care-guide-close-btn');
            const backdrop = document.getElementById('care-guide-backdrop');
            
            const closeModal = () => {
                modal.remove();
            };
            
            closeX.addEventListener('click', closeModal);
            closeBtn.addEventListener('click', closeModal);
            backdrop.addEventListener('click', (e) => {
                if (e.target === backdrop) {
                    closeModal();
                }
            });
        },

        /**
         * 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() {
            // Check if user is admin/editor
            const isAdmin = clawsData.userRoles && (
                clawsData.userRoles.includes('administrator') || 
                clawsData.userRoles.includes('editor')
            );
            
            // Check if intake is restricted to editors/admins
            const intakeRestricted = clawsData.restrictIntakeToEditors == 1;
            const canCreateIntake = !intakeRestricted || isAdmin;
            
            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>
                    
                    ${!canCreateIntake ? `
                    <!-- Access Restricted Message -->
                    <div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 1rem; padding: 1.5rem; margin-bottom: 1rem;">
                        <div style="display: flex; align-items: start; gap: 0.75rem;">
                            <div style="flex-shrink: 0;">
                                <span style="font-size: 1.5rem;">🔒</span>
                            </div>
                            <div>
                                <h3 style="font-weight: 600; color: #92400e; margin: 0 0 0.5rem;">Intake Form Access Restricted</h3>
                                <p style="color: #78350f; margin: 0; font-size: 0.875rem;">
                                    The intake form is currently restricted to Editors and Administrators. 
                                    If you need to create an intake record, please contact an administrator.
                                </p>
                            </div>
                        </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>
                        ${canCreateIntake ? `
                        <button onclick="CLAWSApp.showIntakeForm()" style="
                            width: 100%;
                            background: var(--claws-primary-button-color);
                            color: white;
                            border: none;
                            border-top: 1px solid rgba(255, 255, 255, 0.3);
                            border-bottom: 2px solid rgba(0, 0, 0, 0.2);
                            border-radius: 0.75rem;
                            padding: 0.75rem;
                            font-weight: 600;
                            cursor: pointer;
                            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1);
                            transition: all 0.2s ease;
                            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
                            margin-bottom: 0.5rem;
                        " onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                            New Cat Intake
                        </button>
                        ` : `
                        <div style="background: #f3f4f6; border-radius: 0.75rem; padding: 1rem; text-align: center; color: #6b7280; font-size: 0.875rem; margin-bottom: 0.5rem;">
                            Intake form access is restricted
                        </div>
                        `}
                        <button onclick="CLAWSApp.exportIntakeData()" style="
                            width: 100%;
                            background: var(--claws-secondary-button-color);
                            color: white;
                            border: none;
                            border-top: 1px solid rgba(255, 255, 255, 0.3);
                            border-bottom: 2px solid rgba(0, 0, 0, 0.2);
                            border-radius: 0.75rem;
                            padding: 0.75rem;
                            font-weight: 600;
                            cursor: pointer;
                            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1);
                            transition: all 0.2s ease;
                            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
                        " onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 8px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), inset 0 1px 0 0 rgba(255, 255, 255, 0.1)';">
                            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;">My 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>
                    
                    ${isAdmin ? `
                    <!-- All Active Intakes by User (Admin/Editor 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;">Active Intakes by User</h3>
                        <p style="font-size: 0.875rem; color: #6b7280; margin: 0 0 1rem;">Shows cats with intake forms but no discharge (currently in care)</p>
                        <div style="position: relative; height: 300px; display: flex; align-items: center; justify-content: center;">
                            <canvas id="claws-active-intakes-by-user-chart" width="400" height="300"></canvas>
                        </div>
                        <div id="claws-active-intakes-legend" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 0.5rem; margin-top: 1rem;"></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();
            this.updateActiveIntakesByUserChart();
        },

        /**
         * 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')
            );
            
            // FILTER: Only show ACTIVE cats (no discharge date)
            const activeIntakes = this.intakeRecords.filter(record => 
                !record.discharge_date && !record.discharged && (!record.status || record.status === 'active')
            );
            
            // Sort by date (newest first)
            const sortedIntakes = activeIntakes
                .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';
                
	                // Get FIV and Special Needs flags (be liberal in what we accept)
	                // Values can be stored as booleans, ints, or strings depending on how they were saved.
	                const isTruthy = (v) => {
	                    if (v === true || v === 1) return true;
	                    if (v === false || v === 0 || v === null || v === undefined) return false;
	                    const s = String(v).trim().toLowerCase();
	                    return s === '1' || s === 'true' || s === 'yes' || s === 'y' || s === 'on' || s === 'checked';
	                };
	                const isFIV = isTruthy(record.fiv);
	                const isSpecialNeeds = isTruthy(record.special_needs);
                
                // Debug logging
                if (record.cat_name === 'harrison' || record.cat_name === 'Harrison') {
                    (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Harrison Debug:', {
                        cat_name: record.cat_name,
                        fiv_raw: record.fiv,
                        fiv_type: typeof record.fiv,
                        isFIV: isFIV,
                        special_needs_raw: record.special_needs,
                        special_needs_type: typeof record.special_needs,
                        isSpecialNeeds: isSpecialNeeds
                    });
                }
                
                // Determine status based on discharge information
                const isActive = !record.discharge_date && !record.discharged && (!record.status || record.status === 'active');
                const dischargeDate = record.discharge_date;
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>`;
                }
                
                // Build special flags row (FIV, Special Needs)
                let flagsRow = '';
                if (isFIV || isSpecialNeeds) {
                    const flags = [];
                    if (isFIV) {
                        flags.push('<span style="background: #fed7aa; color: #ea580c; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.625rem; font-weight: 500;">🧡 FIV+</span>');
                    }
                    if (isSpecialNeeds) {
                        flags.push('<span style="background: #f3e8ff; color: #7c3aed; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.625rem; font-weight: 500;">💜 Special Needs</span>');
                    }
                    flagsRow = `<div style="display: flex; gap: 0.5rem; margin-top: 0.5rem; flex-wrap: wrap;">${flags.join('')}</div>`;
                }
                
                // Add edit button for active intakes
                const editButton = isActive ? `
                    <button onclick="CLAWSApp.showEditIntakeModal(${record.id || record.ID})" 
                            style="padding: 0.375rem 0.75rem; background: #3b82f6; color: white; border: none; border-radius: 0.375rem; font-size: 0.75rem; cursor: pointer; font-weight: 500; margin-left: 0.5rem;"
                            onmouseover="this.style.background='#2563eb'" 
                            onmouseout="this.style.background='#3b82f6'">
                        Edit
                    </button>
                ` : '';
                
                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 style="flex: 1;">
                                <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>
                            <div style="display: flex; align-items: center;">
                                ${statusDisplay}
                                ${editButton}
                            </div>
                        </div>
                        ${flagsRow}
                    </div>
                `;
            }).join('');
        },

        /**
         * Update active intakes by user pie chart (admin/editor only)
         */
        updateActiveIntakesByUserChart: function() {
            // Check if user is admin/editor
            const isAdmin = clawsData.userRoles && (
                clawsData.userRoles.includes('administrator') || 
                clawsData.userRoles.includes('editor')
            );
            
            if (!isAdmin) return; // Only admins see this chart
            
            const canvas = document.getElementById('claws-active-intakes-by-user-chart');
            const legendContainer = document.getElementById('claws-active-intakes-legend');
            
            if (!canvas || !legendContainer) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart if it exists
            if (this.activeIntakesByUserChart) {
                this.activeIntakesByUserChart.destroy();
                this.activeIntakesByUserChart = null;
            }
            
            // Filter to ACTIVE intakes only (no discharge)
            const activeIntakes = this.intakeRecords.filter(record => 
                !record.discharge_date && !record.discharged && (!record.status || record.status === 'active')
            );
            
            if (activeIntakes.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No active intakes', canvas.width / 2, canvas.height / 2);
                legendContainer.innerHTML = '';
                return;
            }
            
            // Group by user
            const userCounts = {};
            activeIntakes.forEach(record => {
                const userName = record.author_name || record.user_name || `User ${record.author || record.user_id || 'Unknown'}`;
                userCounts[userName] = (userCounts[userName] || 0) + 1;
            });
            
            // Prepare chart data
            const labels = Object.keys(userCounts);
            const data = Object.values(userCounts);
            const backgroundColors = labels.map((_, index) => {
                const colors = [
                    '#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6',
                    '#ec4899', '#06b6d4', '#84cc16', '#f97316', '#14b8a6'
                ];
                return colors[index % colors.length];
            });
            
            try {
                // Create pie chart
                this.activeIntakesByUserChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: data,
                            backgroundColor: backgroundColors,
                            borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                            borderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        const label = context.label || '';
                                        const value = context.parsed || 0;
                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                        const percentage = ((value / total) * 100).toFixed(1);
                                        return `${label}: ${value} cats (${percentage}%)`;
                                    }
                                }
                            }
                        }
                    }
                });
                
                // Update legend
                let legendHTML = '';
                labels.forEach((label, index) => {
                    legendHTML += `
                        <div style="display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem; background: #f9fafb; border-radius: 0.5rem;">
                            <div style="width: 1rem; height: 1rem; background: ${backgroundColors[index]}; border-radius: 0.25rem;"></div>
                            <span style="font-size: 0.875rem; color: #1f2937;">${label}: <strong>${data[index]} cats</strong></span>
                        </div>
                    `;
                });
                legendContainer.innerHTML = legendHTML;
                
            } catch (error) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Active intakes by user chart creation failed:', error);
            }
        },
        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();
                this.loadMoverShaker();
                this.loadVolunteerHours('task', 'none');
                
                // Setup filter change handlers
                const typeFilter = document.getElementById('hours-type-filter');
                const intervalFilter = document.getElementById('hours-interval-filter');
                const exportBtn = document.getElementById('export-hours-btn');
                
                if (typeFilter && intervalFilter) {
                    typeFilter.addEventListener('change', () => {
                        this.loadVolunteerHours(typeFilter.value, intervalFilter.value);
                    });
                    
                    intervalFilter.addEventListener('change', () => {
                        this.loadVolunteerHours(typeFilter.value, intervalFilter.value);
                    });
                }
                
                if (exportBtn) {
                    exportBtn.addEventListener('click', () => {
                        this.exportVolunteerHours();
                    });
                }
            }
        },
        
        /**
         * Load personal volunteer stats
         */
        loadPersonalStats: function() {
            const container = document.getElementById('claws-personal-stats-grid');
            if (!container) {
                return;
            }
            
            
            fetch(window.wpApiSettings.root + 'claws/v1/stats/personal', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Stats API response status:', response.status);
                return response.json();
            })
            .then(stats => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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) {
                    (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 {
                    (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('No recent activity found');
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&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 => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading top volunteers:', error);
                container.innerHTML = '<p style="color: #991b1b; text-align: center; margin: 0;">Failed to load top volunteers</p>';
            });
        },
        
        /**
         * Load mover & shaker award (admin only) - volunteer with most team memberships
         */
        loadMoverShaker: function() {
            const container = document.getElementById('claws-mover-shaker');
            if (!container) return;
            
            fetch(window.wpApiSettings.root + 'claws/v1/stats/mover-shaker', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(volunteer => {
                if (!volunteer || !volunteer.name) {
                    container.innerHTML = '<p style="color: #6b7280; text-align: center; margin: 0;">No volunteer data yet</p>';
                    return;
                }
                
                container.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 1.5rem; background: linear-gradient(135deg, #fbbf24, #f59e0b); border-radius: 0.75rem; color: white;">
                        <div style="display: flex; align-items: center; gap: 1.5rem;">
                            <span style="font-size: 3rem;">🌟</span>
                            <div>
                                <p style="margin: 0; font-weight: 700; font-size: 1.25rem;">${volunteer.name}</p>
                                <p style="margin: 0.25rem 0 0; font-size: 0.875rem; opacity: 0.9;">Most plugged-in volunteer</p>
                            </div>
                        </div>
                        <div style="text-align: right;">
                            <p style="margin: 0; font-size: 2rem; font-weight: 700;">${volunteer.team_count}</p>
                            <p style="margin: 0; font-size: 0.875rem; opacity: 0.9;">teams joined</p>
                        </div>
                    </div>
                `;
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading mover & shaker:', error);
                container.innerHTML = '<p style="color: #991b1b; text-align: center; margin: 0;">Failed to load mover & shaker</p>';
            });
        },
        
        /**
         * Load volunteer hours summary with filtering (admin only)
         */
        loadVolunteerHours: function(type = 'task', interval = 'none') {
            const container = document.getElementById('claws-volunteer-hours-summary');
            if (!container) return;
            
            container.innerHTML = '<p style="text-align: center; color: #6b7280;">Loading volunteer hours...</p>';
            
            fetch(window.wpApiSettings.root + `claws/v1/stats/volunteer-hours?type=${type}&interval=${interval}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(data => {
                if (type === 'task') {
                    container.innerHTML = this.renderTaskHours(data.volunteers || []);
                } else {
                    container.innerHTML = this.renderTeamHours(data.teams || []);
                }
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error loading volunteer hours:', error);
                container.innerHTML = '<p style="color: #991b1b; text-align: center; margin: 0;">Failed to load volunteer hours</p>';
            });
        },
        
        /**
         * Render task hours (alphabetical volunteer list with total hours)
         */
        renderTaskHours: function(volunteers) {
            if (!volunteers || volunteers.length === 0) {
                return '<p style="text-align: center; color: #6b7280; padding: 2rem;">No volunteer hours logged yet.</p>';
            }
            
            // Sort volunteers alphabetically by name
            volunteers.sort((a, b) => a.name.localeCompare(b.name));
            
            const volunteerRows = volunteers.map(v => `
                <div style="display: flex; justify-content: space-between; padding: 0.75rem 1rem; background: #f9fafb; border-radius: 0.5rem; border-left: 3px solid #3b82f6;">
                    <span style="color: #1f2937; font-weight: 600;">${v.name}</span>
                    <span style="color: #6b7280; font-weight: 700;">${v.hours.toFixed(2)} hrs</span>
                </div>
            `).join('');
            
            const totalHours = volunteers.reduce((sum, v) => sum + parseFloat(v.hours), 0);
            
            return `
                <div style="display: grid; gap: 0.5rem; margin-bottom: 1rem;">
                    ${volunteerRows}
                </div>
                <div style="padding: 1rem; background: linear-gradient(135deg, #3b82f6, #1d4ed8); border-radius: 0.5rem; color: white; text-align: center;">
                    <span style="font-size: 0.875rem; opacity: 0.9;">Total Hours:</span>
                    <span style="font-size: 1.5rem; font-weight: 700; margin-left: 1rem;">${totalHours.toFixed(2)}</span>
                </div>
            `;
        },
        
        /**
         * Render team hours summary with collapsible accordion
         */
        /**
         * Render team hours summary with collapsible accordion
         */
        renderTeamHours: function(teams) {
            if (!teams || teams.length === 0) {
                return '<p style="text-align: center; color: #6b7280; padding: 2rem;">No team hours logged yet.</p>';
            }
            
            // Sort teams alphabetically
            teams.sort((a, b) => a.name.localeCompare(b.name));
            
            const teamCards = teams.map(team => {
                // Sort volunteers with team lead first, then alphabetically
                const sortedVolunteers = [...team.volunteers].sort((a, b) => {
                    if (a.is_lead && !b.is_lead) return -1;
                    if (!a.is_lead && b.is_lead) return 1;
                    return a.name.localeCompare(b.name);
                });
                
                const volunteersHTML = sortedVolunteers.map(v => `
                    <div style="display: flex; justify-content: space-between; padding: 0.75rem; background: ${v.is_lead ? '#dbeafe' : '#f9fafb'}; border-radius: 0.375rem; border-left: 3px solid ${v.is_lead ? '#3b82f6' : 'transparent'};">
                        <span style="color: #374151; font-size: 0.875rem; font-weight: ${v.is_lead ? '600' : '400'};">
                            ${v.is_lead ? '👤 ' : ''}${v.name}${v.is_lead ? ' (Team Lead)' : ''}
                        </span>
                        <span style="color: #6b7280; font-size: 0.875rem; font-weight: 600;">${v.hours.toFixed(2)} hrs</span>
                    </div>
                `).join('');
                
                const totalHours = team.volunteers.reduce((sum, v) => sum + parseFloat(v.hours), 0);
                
                return `
                    <div style="background: white; border: 1px solid #e5e7eb; border-radius: 0.75rem; overflow: hidden;">
                        <!-- Team Header (Accordion) -->
                        <div onclick="CLAWSApp.toggleTeamDetails(${team.id})" style="padding: 1rem; cursor: pointer; display: flex; justify-content: space-between; align-items: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                            <div style="flex: 1;">
                                <div style="font-weight: 600; font-size: 1rem; margin-bottom: 0.25rem;">${team.name}</div>
                                <div style="font-size: 0.75rem; opacity: 0.9;">${team.type} • ${team.volunteer_count} volunteer${team.volunteer_count !== 1 ? 's' : ''}</div>
                            </div>
                            <div style="text-align: right; margin-right: 1rem;">
                                <div style="font-size: 1.5rem; font-weight: 700;">${totalHours.toFixed(2)}</div>
                                <div style="font-size: 0.75rem; opacity: 0.9;">total hours</div>
                            </div>
                            <div id="team-arrow-${team.id}" style="font-size: 1.25rem; transition: transform 0.3s;">▼</div>
                        </div>
                        
                        <!-- Volunteer Details (Collapsible) -->
                        <div id="team-details-${team.id}" style="display: none; padding: 1rem; background: #fafafa;">
                            <h4 style="margin: 0 0 0.75rem; font-size: 0.875rem; font-weight: 600; color: #374151;">Volunteer Breakdown:</h4>
                            <div style="display: grid; gap: 0.5rem;">
                                ${volunteersHTML}
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
            const totalHours = teams.reduce((sum, team) => 
                sum + team.volunteers.reduce((tsum, v) => tsum + parseFloat(v.hours), 0), 0);
            
            return `
                <div style="display: grid; gap: 1rem; margin-bottom: 1rem;">
                    ${teamCards}
                </div>
                <div style="padding: 1rem; background: linear-gradient(135deg, #10b981, #059669); border-radius: 0.5rem; color: white; text-align: center;">
                    <span style="font-size: 0.875rem; opacity: 0.9;">Total Hours Across All Teams:</span>
                    <span style="font-size: 1.5rem; font-weight: 700; margin-left: 1rem;">${totalHours.toFixed(2)}</span>
                </div>
            `;
        },
        
        /**
         * Toggle team details visibility
         */
        toggleTeamDetails: function(teamId) {
            const details = document.getElementById(`team-details-${teamId}`);
            const arrow = document.getElementById(`team-arrow-${teamId}`);
            
            if (details.style.display === 'none') {
                details.style.display = 'block';
                arrow.style.transform = 'rotate(180deg)';
            } else {
                details.style.display = 'none';
                arrow.style.transform = 'rotate(0deg)';
            }
        },
        
        /**
         * Export personal stats to CSV
         */
        exportPersonalStats: function() {
            fetch(window.wpApiSettings.root + 'claws/v1/stats/personal', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(stats => {
                const csv = [
                    ['Metric', 'Value'],
                    ['Hours Volunteered', stats.hours_volunteered || 0],
                    ['Tasks Completed', stats.tasks_completed || 0],
                    ['Events Attended', stats.events_participated || 0],
                    ['Projects Joined', stats.projects_participated || 0],
                    ['Cats Fostered', stats.cats_fostered || 0],
                    ['Bottle Babies', stats.bottle_babies || 0],
                    ['Adoptions Facilitated', stats.adoptions_facilitated || 0],
                    ['TNR Assists', stats.tnr_assists || 0],
                    ['Shelter Transfers', stats.shelter_transfers || 0]
                ].map(row => row.join(',')).join('\n');
                
                this.downloadCSV(csv, 'my-volunteer-stats.csv');
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error exporting personal stats:', error);
                alert('Failed to export personal stats');
            });
        },
        
        /**
         * Export team hours to CSV
         */
        /**
         * Export volunteer hours to CSV based on current filters
         */
        exportVolunteerHours: function() {
            const type = document.getElementById('hours-type-filter')?.value || 'task';
            const interval = document.getElementById('hours-interval-filter')?.value || 'none';
            
            fetch(window.wpApiSettings.root + `claws/v1/stats/volunteer-hours?type=${type}&interval=${interval}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                }
            })
            .then(response => response.json())
            .then(data => {
                let rows = [];
                
                if (type === 'task') {
                    rows = [['Volunteer Name', 'Total Hours']];
                    const volunteers = data.volunteers || [];
                    volunteers.sort((a, b) => a.name.localeCompare(b.name));
                    volunteers.forEach(v => {
                        rows.push([v.name, v.hours.toFixed(2)]);
                    });
                    const totalHours = volunteers.reduce((sum, v) => sum + parseFloat(v.hours), 0);
                    rows.push(['', '']); // Empty row
                    rows.push(['TOTAL', totalHours.toFixed(2)]);
                } else {
                    rows = [['Team Name', 'Team Type', 'Volunteer Name', 'Role', 'Hours']];
                    const teams = data.teams || [];
                    teams.sort((a, b) => a.name.localeCompare(b.name));
                    teams.forEach(team => {
                        team.volunteers.forEach(v => {
                            rows.push([
                                team.name, 
                                team.type, 
                                v.name, 
                                v.is_lead ? 'Team Lead' : 'Member',
                                v.hours.toFixed(2)
                            ]);
                        });
                    });
                }
                
                const csv = rows.map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');
                const intervalLabel = interval === 'none' ? 'all-time' : interval;
                this.downloadCSV(csv, `volunteer-hours-${type}-${intervalLabel}.csv`);
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error exporting volunteer hours:', error);
                alert('Failed to export volunteer hours');
            });
        },
        
        exportTeamHours: function() {
            // Legacy function - redirect to exportVolunteerHours
            this.exportVolunteerHours();
        },
        
        /**
         * Export teams data to CSV
         */
        exportTeamsData: function() {
            // Fetch both event and project teams
            Promise.all([
                fetch(window.wpApiSettings.root + 'claws/v1/teams/events', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpApiSettings.nonce
                    }
                }).then(r => r.json()),
                fetch(window.wpApiSettings.root + 'claws/v1/teams/projects', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpApiSettings.nonce
                    }
                }).then(r => r.json())
            ])
            .then(([eventTeams, projectTeams]) => {
                const rows = [['Team Name', 'Team Type', 'Member Name', 'Role', 'Status']];
                
                // Process event teams
                (eventTeams || []).forEach(team => {
                    const teamName = team.name || 'Unnamed Team';
                    (team.members || []).forEach(member => {
                        rows.push([
                            teamName,
                            'Event',
                            member.name || 'Unknown',
                            member.is_lead ? 'Team Lead 👑' : 'Member',
                            member.filled ? 'Active' : 'Volunteer Needed'
                        ]);
                    });
                });
                
                // Process project teams
                (projectTeams || []).forEach(team => {
                    const teamName = team.name || 'Unnamed Team';
                    (team.members || []).forEach(member => {
                        rows.push([
                            teamName,
                            'Project',
                            member.name || 'Unknown',
                            member.is_lead ? 'Team Lead 👑' : 'Member',
                            member.filled ? 'Active' : 'Volunteer Needed'
                        ]);
                    });
                });
                
                // Generate CSV
                const csv = rows.map(row => 
                    row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')
                ).join('\n');
                
                // Download
                const timestamp = new Date().toISOString().split('T')[0];
                this.downloadCSV(csv, `teams-export-${timestamp}.csv`);
            })
            .catch(error => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Error exporting teams:', error);
                alert('Failed to export teams data. Please try again.');
            });
        },
        
        /**
         * Helper function to download CSV
         */
        downloadCSV: function(csv, filename) {
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.setAttribute('hidden', '');
            a.setAttribute('href', url);
            a.setAttribute('download', filename);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        },
        
        /**
         * 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 (keep it lean: fewer "Unknown" fields = more useful export)
            // NOTE: We intentionally export only ONE of (Age, Age Category). Keeping Age Category.
            const headers = ['Date', 'Cat Name', 'Age Category', 'Gender', 'FIV', 'Special Needs', 'Colony', 'Added By', 'Status', 'Notes'];

            const truthy = (v) => {
                if (v === true) return true;
                if (typeof v === 'number') return v === 1;
                if (typeof v !== 'string') return false;
                return ['1','true','yes','on','checked','y'].includes(v.toLowerCase());
            };

            const safeCsv = (value) => {
                const s0 = (value === null || value === undefined) ? '' : String(value);
                // Newlines inside CSV cells are technically valid when quoted, but they
                // confuse a lot of spreadsheet tooling. Flatten them.
                const s = s0.replace(/[\r\n]+/g, ' ').trim();
                return `"${s.replace(/"/g, '""')}"`;
            };

            const formatNotes = (raw) => {
                if (!raw) return '';
                // Notes are often stored as a JSON array of entries. Flatten to readable text.
                try {
                    const parsed = (typeof raw === 'string') ? JSON.parse(raw) : raw;
                    if (Array.isArray(parsed)) {
                        return parsed
                            .map(n => {
                                if (typeof n === 'string') return n;
                                const ts = n.timestamp || n.date || '';
                                const who = n.author_name || n.author || '';
                                const msg = n.note || n.text || n.message || '';
                                const prefix = [ts, who].filter(Boolean).join(' ');
                                return prefix ? `${prefix}: ${msg}` : msg;
                            })
                            .filter(Boolean)
                            .join(' | ');
                    }
                } catch (e) {
                    // fall through
                }
                return String(raw);
            };
            
            const csvContent = [
                headers.join(','),
                ...this.intakeRecords.map(record => {
                    // Date
                    const rawDate = record.intake_date || record.date || record.intakeDate || record.timestamp;
                    let intakeDate = '';
                    if (rawDate) {
                        const d = new Date(rawDate);
                        intakeDate = isNaN(d.getTime()) ? '' : d.toLocaleDateString();
                    }
                    intakeDate = safeCsv(intakeDate || '');

                    // Core fields
                    const catName = safeCsv(record.cat_name || record.name || 'Unknown');

                    // NOTE: We intentionally export only ONE of (Age, Age Category). Keeping Age Category.
                    // Older records often store this as `age` (dropdown value) rather than `age_category`.
                    const ageCategory = safeCsv(
                        record.age_category || record.ageCategory || record.age || record.age_group || 'Unknown'
                    );

                    const gender = safeCsv(record.gender || record.sex || 'Unknown');

                    const isFIV = truthy(record.fiv) ? 'Yes' : 'No';
                    const isSpecialNeeds = truthy(record.special_needs) ? 'Yes' : 'No';
                    // Colony: if missing/Unknown, treat as Not Applicable (most cats are not from a tracked colony yet)
                    const rawColony = record.colony || record.colony_name || record.colonyName || '';
                    const colonyClean = (rawColony && String(rawColony).trim()) ? String(rawColony).trim() : 'NA';
                    const colony = safeCsv(['unknown', 'n/a', 'na'].includes(colonyClean.toLowerCase()) ? 'NA' : colonyClean);
                    const addedByName = record.added_by_name || record.author_name || record.authorName;
                    const addedBy = safeCsv(addedByName || (record.author ? `User #${record.author}` : 'Unknown'));
                    const status = record.discharged ? 'Discharged' : 'Active';

                    // Notes: include Intake Condition (if provided) and drop separate column
                    const rawNotes = formatNotes(record.notes || record.intake_notes || record.note || '');
                    const rawCondition = record.intake_condition || record.condition || '';
                    const conditionClean = (rawCondition && String(rawCondition).trim()) ? String(rawCondition).trim() : '';
                    const conditionText = (conditionClean && conditionClean.toLowerCase() !== 'unknown') ? `Condition: ${conditionClean}` : '';
                    const notesMerged = [rawNotes, conditionText].filter(Boolean).join(' | ');
                    const notes = safeCsv(notesMerged);
                    
                    return [intakeDate, catName, ageCategory, gender, isFIV, isSpecialNeeds, colony, addedBy, status, notes].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;
            }

            // CSV headers (lean + useful)
            // We export ONLY ONE of (Age, Age Category). Keeping Age Category.
            const headers = [
                'Discharge Date',
                'Cat Name',
                'Outcome',
                'Colony',
                'Added By',
                'Notes'
            ];

            const safeCsv = (value) => {
                if (value === null || value === undefined) return '';
                const str = String(value);
                const escaped = str.replace(/"/g, '""').replace(/\r?\n/g, ' ');
                return /[",\n]/.test(escaped) ? `"${escaped}"` : escaped;
            };

            const asDate = (raw) => {
                if (!raw) return '';
                const d = new Date(raw);
                if (isNaN(d.getTime())) return '';
                return d.toLocaleDateString();
            };

            // Try to map numeric user IDs to display names if we have a users map
            // (Some sites store "added_by" as user_id instead of username.)
            const resolveUser = (raw) => {
                if (!raw) return '';
                if (typeof raw === 'string' && raw.trim() !== '' && isNaN(Number(raw))) return raw;
                const id = Number(raw);
                if (!isNaN(id)) {
                    const map = (this.usersById || window.clawsUsersById || window.clawsUsersMap);
                    if (map && map[id]) return map[id];
                    // fallback: current user if id matches
                    if (window.clawsData && Number(window.clawsData.userId) === id) return window.clawsData.currentUser || String(id);
                    return String(id);
                }
                return String(raw);
            };

            const normalizeColony = (raw) => {
                if (!raw) return 'NA';
                const v = String(raw).trim();
                if (!v || v.toLowerCase() === 'unknown') return 'NA';
                return v;
            };

            const rows = this.dischargeRecords.map(record => {
                const dischargeDate = asDate(record.discharge_date || record.date || record.discharge_timestamp);
                const catName = record.cat_name || record.name || 'Unknown';
const outcome = record.outcome || '';
const colony = normalizeColony(record.colony || record.discharge_colony || record.colony_name);
                const addedByRaw = record.added_by_name || record.added_by_username || record.added_by_display || record.added_by;
                const addedBy = resolveUser(addedByRaw);
                const notes = record.notes || record.note || '';

                return [
                    dischargeDate,
                    catName,
                    outcome,
                    colony,
                    addedBy,
                    notes
                ].map(safeCsv).join(',');
            });

            const csvContent = [headers.join(','), ...rows].join('\n');

            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
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.debug('Feature tracking failed:', err);
            });
        },
        
        /**
         * Show edit intake modal with pre-filled data
         */
        showEditIntakeModal: function(intakeId) {
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('=== EDIT INTAKE DEBUG ===');
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('1. Intake ID requested:', intakeId);
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('2. Available intake records:', this.intakeRecords);
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('3. Number of records:', this.intakeRecords ? this.intakeRecords.length : 0);
            
            // Find the intake record in our data
            const intake = this.intakeRecords.find(r => r.id === intakeId || r.ID === intakeId);
            
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('4. Found intake:', intake);
            
            if (!intake) {
                alert('Could not find intake record. Try refreshing the page.');
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Intake not found in records array');
                return;
            }
            
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('5. Opening form...');
            
            // Store the intake ID and data for editing
            this.editingIntakeId = intakeId;
            this.editingIntakeData = intake;
            
            // Open the intake form
            this.showIntakeForm();
            
            // Wait for form to render, then pre-fill it
            setTimeout(() => {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('6. Prefilling form with intake data...');
                this.prefillIntakeForm(intake);
            }, 250);
        },
        
        /**
         * Pre-fill intake form with existing data
         */
        prefillIntakeForm: function(intake) {
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('=== PREFILL FORM DEBUG ===');
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Full intake object:', intake);
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('---');
            
            // Change modal title
            const modalTitle = document.querySelector('#claws-intake-form-modal h2');
            if (modalTitle) {
                modalTitle.textContent = 'Edit Cat Intake';
            }
            
            // Pre-fill basic fields
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Date:', intake.intake_date || intake.date);
            if (document.getElementById('claws-intake-date')) {
                document.getElementById('claws-intake-date').value = intake.intake_date || intake.date || '';
            }
            
            // Pre-fill contact info
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling First Name:', intake.contact_first_name);
            if (document.getElementById('claws-intake-contact-first-name')) {
                document.getElementById('claws-intake-contact-first-name').value = intake.contact_first_name || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Last Name:', intake.contact_last_name);
            if (document.getElementById('claws-intake-contact-last-name')) {
                document.getElementById('claws-intake-contact-last-name').value = intake.contact_last_name || '';
            }
            
            // Pre-fill address fields
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Street:', intake.contact_street);
            if (document.getElementById('claws-intake-street')) {
                document.getElementById('claws-intake-street').value = intake.contact_street || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling City:', intake.contact_city);
            if (document.getElementById('claws-intake-city')) {
                document.getElementById('claws-intake-city').value = intake.contact_city || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling State:', intake.contact_state);
            if (document.getElementById('claws-intake-state')) {
                document.getElementById('claws-intake-state').value = intake.contact_state || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Zip:', intake.contact_zip);
            if (document.getElementById('claws-intake-zip')) {
                document.getElementById('claws-intake-zip').value = intake.contact_zip || '';
            }
            
            // Pre-fill phone and email (NOTE: IDs are claws-intake-phone and claws-intake-email, NOT claws-intake-contact-phone!)
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Phone:', intake.contact_phone);
            if (document.getElementById('claws-intake-phone')) {
                document.getElementById('claws-intake-phone').value = intake.contact_phone || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Email:', intake.contact_email);
            if (document.getElementById('claws-intake-email')) {
                document.getElementById('claws-intake-email').value = intake.contact_email || '';
            }
            
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('--- Cat Information ---');
            // Pre-fill cat info
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Cat Name:', intake.cat_name || intake.name);
            if (document.getElementById('claws-intake-cat-name')) {
                document.getElementById('claws-intake-cat-name').value = intake.cat_name || intake.name || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Age:', intake.age);
            if (document.getElementById('claws-intake-age')) {
                document.getElementById('claws-intake-age').value = intake.age || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Gender:', intake.gender);
            if (document.getElementById('claws-intake-gender')) {
                document.getElementById('claws-intake-gender').value = intake.gender || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Coat:', intake.coat);
            if (document.getElementById('claws-intake-coat')) {
                document.getElementById('claws-intake-coat').value = intake.coat || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Color:', intake.color);
            if (document.getElementById('claws-intake-color')) {
                document.getElementById('claws-intake-color').value = intake.color || '';
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Type:', intake.type);
            if (document.getElementById('claws-intake-type')) {
                document.getElementById('claws-intake-type').value = intake.type || '';
            }
            
            // Pre-fill checkboxes
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling FIV:', intake.fiv);
            if (document.getElementById('claws-intake-fiv')) {
                document.getElementById('claws-intake-fiv').checked = intake.fiv === '1' || intake.fiv === true || intake.fiv === 1;
            }
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Special Needs:', intake.special_needs);
            if (document.getElementById('claws-intake-special-needs')) {
                document.getElementById('claws-intake-special-needs').checked = intake.special_needs === '1' || intake.special_needs === true || intake.special_needs === 1;
            }
            
            // Pre-fill notes (handle both old string format and new JSON array)
            if (document.getElementById('claws-intake-notes')) {
                const notes = intake.notes || '';
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('Filling Notes:', notes);
                // Check if it's already JSON
                if (notes && (notes.startsWith('[') || notes.startsWith('{'))) {
                    document.getElementById('claws-intake-notes').value = notes;
                } else if (notes) {
                    // Convert old string format to new JSON format
                    const notesArray = [{
                        text: notes,
                        timestamp: (intake.intake_date || intake.date || new Date().toISOString().split('T')[0]) + 'T00:00:00'
                    }];
                    document.getElementById('claws-intake-notes').value = JSON.stringify(notesArray);
                }
                // Render the notes list
                this.renderNotesList();
            }
            
            (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.log('=== PREFILL COMPLETE ===');
            
            // Store the intake ID for updating
            this.editingIntakeId = intake.id || intake.ID;

	            // IMPORTANT: Keep the top (Contact Information) visible when editing.
	            // The intake modal body is scrollable, and browsers can preserve scroll position.
	            // Also, some DOM updates during prefill can trigger an auto-scroll.
	            // So we force-scroll to the top *after* prefill finishes.
	            const forceScrollTop = () => {
	                const scroller = document.getElementById('claws-intake-form-scroll');
	                if (scroller) scroller.scrollTop = 0;
	                // Optionally focus a top-field so the viewport stays anchored at the top.
	                const first = document.getElementById('claws-intake-contact-first-name');
	                if (first) first.focus({ preventScroll: true });
	            };

	            // Run now, on next frame, and once more after a short delay to beat any late reflow.
	            forceScrollTop();
	            requestAnimationFrame(forceScrollTop);
	            setTimeout(forceScrollTop, 50);
        },
        
        /**
         * Show dialog to add a new note
         */
        showAddNoteDialog: function() {
            const now = new Date();
            const dateStr = now.toISOString().split('T')[0];
            const timeStr = now.toTimeString().slice(0,5);
            
            const existingModal = document.getElementById('claws-add-note-modal');
            if (existingModal) existingModal.remove();
            
            const modal = document.createElement('div');
            modal.id = 'claws-add-note-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10001; display: flex; align-items: center; justify-content: center;';
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 0.75rem; padding: 1.5rem; max-width: 500px; width: 90%;">
                    <h3 style="margin: 0 0 1rem; font-size: 1.125rem; font-weight: 600; color: #1f2937;">Add Note</h3>
                    
                    <div style="margin-bottom: 1rem;">
                        <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Date & Time</label>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                            <input type="date" id="note-date" value="${dateStr}" style="padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                            <input type="time" id="note-time" value="${timeStr}" style="padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 1rem;">
                        <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Note</label>
                        <textarea id="note-text" rows="4" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; resize: vertical; box-sizing: border-box;" placeholder="Enter your note..."></textarea>
                    </div>
                    
                    <div style="display: flex; gap: 0.75rem;">
                        <button onclick="CLAWSApp.closeAddNoteDialog()" style="flex: 1; padding: 0.625rem; background: #e5e7eb; color: #374151; border: none; border-radius: 0.375rem; font-weight: 500; cursor: pointer;">Cancel</button>
                        <button onclick="CLAWSApp.saveNote()" style="flex: 1; padding: 0.625rem; background: #3b82f6; color: white; border: none; border-radius: 0.375rem; font-weight: 500; cursor: pointer;">Add Note</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            document.getElementById('note-text').focus();
        },
        
        /**
         * Close add note dialog
         */
        closeAddNoteDialog: function() {
            const modal = document.getElementById('claws-add-note-modal');
            if (modal) modal.remove();
        },
        
        /**
         * Save a new note
         */
        saveNote: function() {
            const dateInput = document.getElementById('note-date').value;
            const timeInput = document.getElementById('note-time').value;
            const noteText = document.getElementById('note-text').value.trim();
            
            if (!noteText) {
                alert('Please enter a note');
                return;
            }
            
            if (!dateInput || !timeInput) {
                alert('Please select date and time');
                return;
            }
            
            // Create timestamp
            const timestamp = `${dateInput}T${timeInput}:00`;
            
            // Get existing notes
            const notesField = document.getElementById('claws-intake-notes');
            let notes = [];
            if (notesField.value) {
                try {
                    notes = JSON.parse(notesField.value);
                } catch (e) {
                    // If notes is a string (old format), convert it
                    if (notesField.value.trim()) {
                        notes = [{
                            text: notesField.value,
                            timestamp: this.editingIntakeData ? (this.editingIntakeData.intake_date || this.editingIntakeData.date) + 'T00:00:00' : new Date().toISOString()
                        }];
                    }
                }
            }
            
            // Add new note
            notes.push({
                text: noteText,
                timestamp: timestamp,
                added_at: new Date().toISOString()
            });
            
            // Sort notes by timestamp (newest first)
            notes.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
            
            // Save back
            notesField.value = JSON.stringify(notes);
            
            // Re-render notes list
            this.renderNotesList();
            
            // Close dialog
            this.closeAddNoteDialog();
        },
        
        /**
         * Render notes list
         */
        renderNotesList: function() {
            const notesField = document.getElementById('claws-intake-notes');
            const notesList = document.getElementById('claws-intake-notes-list');
            
            if (!notesList) return;
            
            let notes = [];
            if (notesField && notesField.value) {
                try {
                    notes = JSON.parse(notesField.value);
                } catch (e) {
                    // Old format - single string
                    if (notesField.value.trim()) {
                        notes = [{
                            text: notesField.value,
                            timestamp: this.editingIntakeData ? (this.editingIntakeData.intake_date || this.editingIntakeData.date) + 'T00:00:00' : new Date().toISOString()
                        }];
                    }
                }
            }
            
            if (notes.length === 0) {
                notesList.innerHTML = '<p style="color: #9ca3af; font-size: 0.75rem; text-align: center; margin: 1rem 0; font-style: italic;">No notes yet. Click "Add Note" to add one.</p>';
                return;
            }
            
            // Sort notes by timestamp (newest first)
            notes.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
            
            notesList.innerHTML = notes.map((note, index) => {
                const date = new Date(note.timestamp);
                const dateStr = date.toLocaleDateString();
                const timeStr = date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
                
                return `
                    <div style="background: white; border: 1px solid #e5e7eb; border-radius: 0.375rem; padding: 0.625rem; margin-bottom: 0.5rem;">
                        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.25rem;">
                            <span style="font-size: 0.625rem; color: #6b7280; font-weight: 500;">${dateStr} at ${timeStr}</span>
                            <button onclick="CLAWSApp.deleteNote(${index})" style="background: none; border: none; color: #dc2626; cursor: pointer; font-size: 0.75rem; padding: 0;" title="Delete note">✕</button>
                        </div>
                        <p style="margin: 0; font-size: 0.875rem; color: #1f2937; white-space: pre-wrap;">${note.text}</p>
                    </div>
                `;
            }).join('');
        },
        
        /**
         * Delete a note
         */
        deleteNote: function(index) {
            if (!confirm('Delete this note?')) return;
            
            const notesField = document.getElementById('claws-intake-notes');
            let notes = JSON.parse(notesField.value || '[]');
            
            // Sort to match display order
            notes.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
            
            // Remove note
            notes.splice(index, 1);
            
            // Save
            notesField.value = JSON.stringify(notes);
            
            // Re-render
            this.renderNotesList();
        }

    });

    // Clear tab notification when user returns to the tab
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden && window.CLAWSApp) {
            window.CLAWSApp.clearTabNotification();
        }
    });
    
    // Start notification polling when page loads (if user is logged in)
    if (window.wpApiSettings && window.wpApiSettings.nonce) {
        // Start polling after a short delay to let the page load
        setTimeout(function() {
            if (window.CLAWSApp && window.CLAWSApp.startNotificationPolling) {
                window.CLAWSApp.startNotificationPolling();
            }
        }, 2000);
    }

})();