/**
 * CLAWS Forms Module - VERSION 2.0.20 - CACHE BUSTER ACTIVE
 * Handles all form functionality including colony forms, intake/discharge forms, and form validation
 * Updated: Console logging cleanup - syntax errors fixed
 */

(function() {
    'use strict';
    

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

        // Form state
        currentEditingColony: null,

        /**
         * Show add colony form
         */
        showAddColonyForm: function(isEditing = false) {
            
            // CRITICAL FIX: Force clean modal regeneration - remove any corrupted cached modal
            const existingModal = document.getElementById('claws-add-colony-modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modalHTML = `
                <div id="claws-add-colony-modal" class="claws-modal-backdrop" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div class="claws-modal-content" style="background: white; border-radius: 1rem; padding: 2rem; max-width: 900px; width: 90%; max-height: 90vh; overflow-y: auto; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);" onclick="event.stopPropagation();">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                            <h2 style="font-size: 1.5rem; font-weight: 600; color: #1f2937; margin: 0;">Add Colony</h2>
                            <button onclick="CLAWSApp.hideAddColonyForm()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem;">×</button>
                        </div>
                        
                        <form id="claws-colony-form" style="display: grid; gap: 1rem;">
                            <!-- Basic Information -->
                            <div>
                                <label for="claws-colony-name" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Colony Name *</label>
                                <input type="text" id="claws-colony-name" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="Enter colony name">
                            </div>
                            
                            <!-- Date -->
                            <div>
                                <label for="claws-colony-date" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Date</label>
                                <input type="date" id="claws-colony-date" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <!-- Address Fields -->
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                                <div>
                                    <label for="claws-colony-street" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Street Address *</label>
                                    <input type="text" id="claws-colony-street" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="Street address">
                                </div>
                                <div>
                                    <label for="claws-colony-city" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">City *</label>
                                    <input type="text" id="claws-colony-city" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="City">
                                </div>
                            </div>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                                <div>
                                    <label for="claws-colony-state" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">State *</label>
                                    <input type="text" id="claws-colony-state" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="State">
                                </div>
                                <div>
                                    <label for="claws-colony-zip" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">ZIP Code *</label>
                                    <input type="text" id="claws-colony-zip" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="ZIP code">
                                </div>
                            </div>
                            
                            <!-- Population Counts -->
                            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem;">
                                <div>
                                    <label for="claws-babies-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Newborn<br><span style="font-size: 0.8em; color: #6b7280;">(0-8 weeks)</span></label>
                                    <input type="number" id="claws-babies-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-kittens-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Kitten<br><span style="font-size: 0.8em; color: #6b7280;">(2-5 months)</span></label>
                                    <input type="number" id="claws-kittens-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-adults-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Cat<br><span style="font-size: 0.8em; color: #6b7280;">(6 months-8 years)</span></label>
                                    <input type="number" id="claws-adults-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-seniors-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Senior<br><span style="font-size: 0.8em; color: #6b7280;">(8+ years)</span></label>
                                    <input type="number" id="claws-seniors-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                            </div>
                            
                            <!-- Security Assessments -->
                            <div style="display: grid; grid-template-columns: 1.2fr 1.2fr 1fr; gap: 1rem;">
                                <div>
                                    <label for="claws-feeding-security" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Feeding Security *</label>
                                    <select id="claws-feeding-security" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                        <option value="">Select feeding security...</option>
                                        <option value="Very Good">Very Good</option>
                                        <option value="Good">Good</option>
                                        <option value="Sufficient">Sufficient</option>
                                        <option value="Marginal">Marginal</option>
                                        <option value="Insufficient">Insufficient</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="claws-shelter-security" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Shelter Security *</label>
                                    <select id="claws-shelter-security" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                        <option value="">Select shelter security...</option>
                                        <option value="Very Safe">Very Safe</option>
                                        <option value="Safe">Safe</option>
                                        <option value="Somewhat Safe">Somewhat Safe</option>
                                        <option value="Unsafe">Unsafe</option>
                                        <option value="Dangerous">Dangerous</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="claws-water-security" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Water Security *</label>
                                    <select id="claws-water-security" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                        <option value="">Select water security...</option>
                                        <option value="Very Good">Very Good</option>
                                        <option value="Good">Good</option>
                                        <option value="Sufficient">Sufficient</option>
                                        <option value="Marginal">Marginal</option>
                                        <option value="Insufficient">Insufficient</option>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- TNR & Care Information -->
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                                <div>
                                    <label for="claws-tipped-ears" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Tipped Ears *</label>
                                    <input type="number" id="claws-tipped-ears" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-winter-shelters" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Winter Shelters *</label>
                                    <input type="number" id="claws-winter-shelters" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                            </div>
                            
                            <!-- Caregiver Information -->
                            <div>
                                <label for="claws-caregiver-select" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Primary Caregiver</label>
                                <select id="claws-caregiver-select" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; margin-bottom: 0.5rem;">
                                    <option value="none">No assigned caregiver</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                
                                <!-- Caregiver Contact Info Display -->
                                <div id="claws-caregiver-info" style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 0.375rem; padding: 0.75rem; margin-top: 0.5rem; display: none;">
                                    <h5 style="margin: 0 0 0.5rem; font-weight: 500; color: #374151; font-size: 0.8rem;">Caregiver Contact Information</h5>
                                    <div id="claws-caregiver-details" style="font-size: 0.875rem; color: #6b7280;">
                                        <!-- Contact details will be populated here -->
                                    </div>
                                </div>
                                
                                <!-- Communication Preferences -->
                                <div id="claws-caregiver-communication" style="background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 0.375rem; padding: 0.75rem; margin-top: 0.5rem; display: none;">
                                    <h5 style="margin: 0 0 0.5rem; font-weight: 500; color: #0369a1; font-size: 0.8rem;">Communication Preferences</h5>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; font-size: 0.8rem;">
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-allow-email" style="margin-right: 0.5rem;">
                                            <span>Allow email contact</span>
                                        </label>
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-allow-phone" style="margin-right: 0.5rem;">
                                            <span>Allow phone contact</span>
                                        </label>
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-emergency-contact" style="margin-right: 0.5rem;">
                                            <span>Emergency contact</span>
                                        </label>
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-public-visible" style="margin-right: 0.5rem;">
                                            <span>Public contact visible</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Colony Location -->
                            <div>
                                <label style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Colony Location *</label>
                                <p style="font-size: 0.875rem; color: #6b7280; margin-bottom: 0.75rem;">Click on the map below to place the colony marker at the exact location:</p>
                                
                                <!-- Interactive Map -->
                                <div id="claws-add-colony-map" style="height: 400px; border: 1px solid #d1d5db; border-radius: 0.5rem; margin-bottom: 1rem;">
                                    <!-- Map will be initialized here -->
                                </div>
                                
                                <!-- Selected Coordinates Display -->
                                <div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 0.375rem; padding: 0.75rem; font-size: 0.875rem;">
                                    <span style="color: #374151; font-weight: 500;">Selected coordinates:</span>
                                    <span id="claws-selected-coordinates" style="color: #6b7280;">Click map to select location</span>
                                </div>
                                
                                <!-- Hidden coordinate inputs -->
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-top: 1rem;">
                                    <div>
                                        <label for="claws-colony-lat" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Latitude</label>
                                        <input type="number" id="claws-colony-lat" step="any" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="e.g., 39.8283" readonly>
                                    </div>
                                    <div>
                                        <label for="claws-colony-lng" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Longitude</label>
                                        <input type="number" id="claws-colony-lng" step="any" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="e.g., -98.5795" readonly>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Photo Upload -->
                            <div>
                                <label for="claws-colony-photos" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Upload Photos (Optional)</label>
                                <input type="file" id="claws-colony-photos" accept="image/jpeg,image/png,image/webp" multiple style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; box-sizing: border-box;" onchange="CLAWSApp.handleColonyPhotosChange(this)" />
                                <p style="font-size: 0.75rem; color: #6b7280; margin: 0.5rem 0 0;">JPG, PNG, or WebP. Max 5MB per photo. You can upload multiple photos to document the colony.</p>
                                
                                <!-- Photo Preview Container -->
                                <div id="claws-colony-photos-preview" style="display: none; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 0.75rem; margin-top: 1rem;">
                                    <!-- Photo previews will be added here -->
                                </div>
                            </div>
                            
                            <!-- Notes -->
                            <div>
                                <label for="claws-colony-notes" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Notes</label>
                                <textarea id="claws-colony-notes" rows="4" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; resize: vertical;" placeholder="Additional notes about this colony..."></textarea>
                            </div>
                            
                            <!-- Colony Help Section -->
                            <div style="margin-top: 1rem; padding: 1rem; background: #f9fafb; border-radius: 0.75rem; border: 1px solid #e5e7eb;">
                                <h4 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 1rem;">Colony Help: I need assistance with</h4>
                                <p style="font-size: 0.875rem; color: #6b7280; margin: 0 0 1rem;">(select all that apply)</p>
                                <div style="display: grid; grid-template-columns: 1fr; gap: 0.5rem;">
                                    <label style="display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.875rem; color: #374151; cursor: pointer;">
                                        <input type="checkbox" class="claws-help-option" data-help-type="traps" style="margin: 0.125rem 0 0 0; flex-shrink: 0;">
                                        <span>Traps or other equipment</span>
                                    </label>
                                    <label style="display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.875rem; color: #374151; cursor: pointer;">
                                        <input type="checkbox" class="claws-help-option" data-help-type="trapping" style="margin: 0.125rem 0 0 0; flex-shrink: 0;">
                                        <span>Trapping</span>
                                    </label>
                                    <label style="display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.875rem; color: #374151; cursor: pointer;">
                                        <input type="checkbox" class="claws-help-option" data-help-type="appointments" style="margin: 0.125rem 0 0 0; flex-shrink: 0;">
                                        <span>Spay/neuter appointments</span>
                                    </label>
                                    <label style="display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.875rem; color: #374151; cursor: pointer;">
                                        <input type="checkbox" class="claws-help-option" data-help-type="food" style="margin: 0.125rem 0 0 0; flex-shrink: 0;">
                                        <span>Cat food</span>
                                    </label>
                                    <label style="display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.875rem; color: #374151; cursor: pointer;">
                                        <input type="checkbox" class="claws-help-option" data-help-type="caretaking" style="margin: 0.125rem 0 0 0; flex-shrink: 0;">
                                        <span>Caretaking assistance</span>
                                    </label>
                                    <label style="display: flex; align-items: flex-start; gap: 0.5rem; font-size: 0.875rem; color: #374151; cursor: pointer;">
                                        <input type="checkbox" class="claws-help-option" data-help-type="shelters" style="margin: 0.125rem 0 0 0; flex-shrink: 0;">
                                        <span>Winter shelters</span>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Buttons -->
                            <div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1rem;">
                                <button type="button" onclick="CLAWSApp.hideAddColonyForm()" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; cursor: pointer; font-size: 0.875rem;">Cancel</button>
                                <button type="button" onclick="CLAWSApp.saveColony()" style="background: #3b82f6; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; cursor: pointer; font-size: 0.875rem;">Save Colony</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            
            if (!isEditing) {
                this.resetColonyForm();
            }
            this.setupFormEventListeners();
            
            // Initialize map for location selection - increased timeout for better reliability
            setTimeout(() => {
                this.initializeAddColonyMap();
            }, 500);
        },

        /**
         * Show edit colony form (without address/location fields)
         */
        showEditColonyForm: function() {
            
            const existingModal = document.getElementById('claws-edit-colony-modal');
            if (existingModal) {
                existingModal.style.display = 'flex';
                this.setupEditFormEventListeners();
                return;
            }
            
            const modalHTML = `
                <div id="claws-edit-colony-modal" class="claws-modal-backdrop" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div class="claws-modal-content" style="background: white; border-radius: 1rem; padding: 2rem; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);" onclick="event.stopPropagation();">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.5rem; font-weight: 600; color: #1f2937; margin: 0;">Edit Colony</h2>
                            <button onclick="CLAWSApp.hideEditColonyForm()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem;">×</button>
                        </div>
                        
                        <!-- Effective Date Display -->
                        <div style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <p style="margin: 0; font-size: 0.875rem; font-weight: 500; color: #92400e;">Current Effective Date</p>
                                    <p style="margin: 0; font-size: 1rem; font-weight: 600; color: #78350f;" id="claws-edit-effective-date">Loading...</p>
                                </div>
                                <div style="font-size: 1.5rem; color: #f59e0b;">📅</div>
                            </div>
                            <p style="margin: 0.5rem 0 0; font-size: 0.75rem; color: #92400e; line-height: 1.3;">
                                <strong>Tip:</strong> Select a date <em>before</em> this effective date to create a historical entry without updating current colony data. Select a date <em>after</em> this date to update current colony data.
                            </p>
                        </div>
                        
                        <form id="claws-edit-colony-form" style="display: grid; gap: 1rem;">
                            <!-- Basic Information -->
                            <div>
                                <label for="claws-edit-colony-name" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Colony Name *</label>
                                <input type="text" id="claws-edit-colony-name" required style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="Enter colony name">
                            </div>
                            
                            
                            <!-- Date -->
                            <div>
                                <label for="claws-edit-colony-date" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Date</label>
                                <input type="date" id="claws-edit-colony-date" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                            </div>
                            
                            <!-- Population Counts -->
                            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem;">
                                <div>
                                    <label for="claws-edit-babies-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Newborn<br><span style="font-size: 0.8em; color: #6b7280;">(0-8 weeks)</span></label>
                                    <input type="number" id="claws-edit-babies-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-edit-kittens-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Kitten<br><span style="font-size: 0.8em; color: #6b7280;">(2-5 months)</span></label>
                                    <input type="number" id="claws-edit-kittens-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-edit-adults-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Cat<br><span style="font-size: 0.8em; color: #6b7280;">(6 months-8 years)</span></label>
                                    <input type="number" id="claws-edit-adults-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-edit-seniors-count" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Senior<br><span style="font-size: 0.8em; color: #6b7280;">(8+ years)</span></label>
                                    <input type="number" id="claws-edit-seniors-count" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                            </div>
                            
                            <!-- Security Assessments -->
                            <div style="display: grid; grid-template-columns: 1.2fr 1.2fr 1fr; gap: 1rem;">
                                <div>
                                    <label for="claws-edit-feeding-security" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Feeding Security *</label>
                                    <select id="claws-edit-feeding-security" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                        <option value="">Select feeding security...</option>
                                        <option value="Very Good">Very Good</option>
                                        <option value="Good">Good</option>
                                        <option value="Sufficient">Sufficient</option>
                                        <option value="Marginal">Marginal</option>
                                        <option value="Insufficient">Insufficient</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="claws-edit-shelter-security" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Shelter Security *</label>
                                    <select id="claws-edit-shelter-security" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                        <option value="">Select shelter security...</option>
                                        <option value="Very Safe">Very Safe</option>
                                        <option value="Safe">Safe</option>
                                        <option value="Somewhat Safe">Somewhat Safe</option>
                                        <option value="Unsafe">Unsafe</option>
                                        <option value="Dangerous">Dangerous</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="claws-edit-water-security" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Water Security *</label>
                                    <select id="claws-edit-water-security" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                        <option value="">Select water security...</option>
                                        <option value="Very Good">Very Good</option>
                                        <option value="Good">Good</option>
                                        <option value="Sufficient">Sufficient</option>
                                        <option value="Marginal">Marginal</option>
                                        <option value="Insufficient">Insufficient</option>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- TNR & Care Information -->
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                                <div>
                                    <label for="claws-edit-tipped-ears" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Tipped Ears *</label>
                                    <input type="number" id="claws-edit-tipped-ears" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                                <div>
                                    <label for="claws-edit-winter-shelters" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Winter Shelters *</label>
                                    <input type="number" id="claws-edit-winter-shelters" min="0" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" placeholder="0">
                                </div>
                            </div>
                            
                            <!-- Caregiver Information -->
                            <div>
                                <label for="claws-edit-caregiver-select" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Primary Caregiver</label>
                                <select id="claws-edit-caregiver-select" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; margin-bottom: 0.5rem;">
                                    <option value="none">No assigned caregiver</option>
                                    <!-- Options will be populated dynamically -->
                                </select>
                                
                                <!-- Caregiver Contact Info Display -->
                                <div id="claws-edit-caregiver-info" style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 0.375rem; padding: 0.75rem; margin-top: 0.5rem; display: none;">
                                    <h5 style="margin: 0 0 0.5rem; font-weight: 500; color: #374151; font-size: 0.8rem;">Caregiver Contact Information</h5>
                                    <div id="claws-edit-caregiver-details" style="font-size: 0.875rem; color: #6b7280;">
                                        <!-- Contact details will be populated here -->
                                    </div>
                                </div>
                                
                                <!-- Communication Preferences -->
                                <div id="claws-edit-caregiver-communication" style="background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 0.375rem; padding: 0.75rem; margin-top: 0.5rem; display: none;">
                                    <h5 style="margin: 0 0 0.5rem; font-weight: 500; color: #0369a1; font-size: 0.8rem;">Communication Preferences</h5>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; font-size: 0.8rem;">
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-edit-allow-email" style="margin-right: 0.5rem;">
                                            <span>Allow email contact</span>
                                        </label>
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-edit-allow-phone" style="margin-right: 0.5rem;">
                                            <span>Allow phone contact</span>
                                        </label>
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-edit-emergency-contact" style="margin-right: 0.5rem;">
                                            <span>Emergency contact</span>
                                        </label>
                                        <label style="display: flex; align-items: center;">
                                            <input type="checkbox" id="claws-edit-public-visible" style="margin-right: 0.5rem;">
                                            <span>Public contact visible</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Photo Upload -->
                            <div>
                                <label for="claws-edit-colony-photos" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Upload Additional Photos (Optional)</label>
                                <input type="file" id="claws-edit-colony-photos" accept="image/jpeg,image/png,image/webp" multiple style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; box-sizing: border-box;" onchange="CLAWSApp.handleColonyPhotosChange(this)" />
                                <p style="font-size: 0.75rem; color: #6b7280; margin: 0.5rem 0 0;">JPG, PNG, or WebP. Max 5MB per photo. You can upload multiple photos to document the colony journey.</p>
                                
                                <!-- Photo Preview Container -->
                                <div id="claws-edit-colony-photos-preview" style="display: none; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 0.75rem; margin-top: 1rem;">
                                    <!-- Photo previews will be added here -->
                                </div>
                            </div>
                            
                            <!-- Notes -->
                            <div>
                                <label for="claws-edit-colony-notes" style="display: block; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Notes</label>
                                <textarea id="claws-edit-colony-notes" rows="4" style="width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; resize: vertical;" placeholder="Additional notes about this colony..."></textarea>
                            </div>
                            
                            <!-- Address/Location Display (Read-only) -->
                            <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 0.5rem; padding: 0.75rem;">
                                <h4 style="margin: 0 0 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem;">Current Location (Cannot be changed)</h4>
                                <div id="claws-edit-location-display" style="font-size: 0.875rem; color: #6b7280;">
                                    <!-- Location will be populated here -->
                                </div>
                                <div style="font-size: 0.75rem; color: #9ca3af; margin-top: 0.5rem; font-style: italic;">
                                    To change the location, please create a new colony entry.
                                </div>
                            </div>
                            
                            <!-- Buttons -->
                            <div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1rem;">
                                <button type="button" onclick="CLAWSApp.hideEditColonyForm()" style="background: #6b7280; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; cursor: pointer; font-size: 0.875rem;">Cancel</button>
                                <button type="button" id="claws-edit-save-button" style="background: #3b82f6; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 0.5rem; cursor: pointer; font-size: 0.875rem;">Update Colony</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            this.setupEditFormEventListeners();
        },

        /**
         * Hide edit colony form
         */
        hideEditColonyForm: function() {
            const modal = document.getElementById('claws-edit-colony-modal');
            if (modal) {
                modal.style.display = 'none';
            } else {
                // Try to hide add colony modal as fallback
                const addModal = document.getElementById('claws-add-colony-modal');
                if (addModal) {
                    addModal.style.display = 'none';
                }
            }
            this.currentEditingColony = null;
        },

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


        /**
         * Reset colony form to empty state
         */
        resetColonyForm: function() {
            
            // Helper function to safely set element value
            const safeSetValue = (id, value) => {
                const element = document.getElementById(id);
                if (element) {
                    element.value = value;
                } else {
                }
            };
            
            // Reset basic fields
            safeSetValue('claws-colony-name', '');
            
            // Set date to today
            safeSetValue('claws-colony-date', new Date().toISOString().split('T')[0]);
            
            // Clear address fields
            safeSetValue('claws-colony-street', '');
            safeSetValue('claws-colony-city', '');
            safeSetValue('claws-colony-state', '');
            safeSetValue('claws-colony-zip', '');
            
            // Reset counts
            safeSetValue('claws-babies-count', 0);
            safeSetValue('claws-kittens-count', 0);
            safeSetValue('claws-seniors-count', 0);
            safeSetValue('claws-adults-count', 0);
            
            // Reset security assessments
            safeSetValue('claws-feeding-security', '');
            safeSetValue('claws-shelter-security', '');
            safeSetValue('claws-water-security', '');
            
            // Reset TNR & Care fields
            safeSetValue('claws-tipped-ears', 0);
            safeSetValue('claws-winter-shelters', 0);
            safeSetValue('claws-caregiver', '');
            
            // Reset location
            safeSetValue('claws-colony-lat', '');
            safeSetValue('claws-colony-lng', '');
            
            // Reset notes
            safeSetValue('claws-colony-notes', '');
            
            // Clear photo uploads and previews
            const photosInput = document.getElementById('claws-colony-photos');
            const photosPreview = document.getElementById('claws-colony-photos-preview');
            if (photosInput) {
                photosInput.value = '';
            }
            if (photosPreview) {
                photosPreview.innerHTML = '';
                photosPreview.style.display = 'none';
            }
            
            // Reset coordinate display
            const coordsDisplay = document.getElementById('claws-selected-coordinates');
            if (coordsDisplay) {
                coordsDisplay.textContent = 'Click map to select location';
                coordsDisplay.style.color = '#6b7280';
            }
            
            // Reset modal title and button
            const modalTitle = document.querySelector('#claws-add-colony-modal h2');
            if (modalTitle) {
                modalTitle.textContent = 'Add Colony';
            }
            
            const saveButton = document.querySelector('button[onclick="CLAWSApp.saveColony()"]');
            if (saveButton) {
                saveButton.textContent = 'Save Colony';
                saveButton.onclick = () => this.saveColony();
            }
            
        },

        /**
         * Setup edit form event listeners
         */
        setupEditFormEventListeners: function() {
            
            // Auto-calculate total cats when individual counts change
            const countFields = ['claws-edit-babies-count', 'claws-edit-kittens-count', 'claws-edit-adults-count', 'claws-edit-seniors-count'];
            countFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.addEventListener('input', this.updateEditTotalCatsCount.bind(this));
                }
            });
            
            // Handle caregiver selection changes
            const caregiverSelect = document.getElementById('claws-edit-caregiver-select');
            if (caregiverSelect) {
                caregiverSelect.addEventListener('change', this.handleEditCaregiverSelection.bind(this));
            }
            
            // Load available caregivers
            this.loadAvailableCaregivers('claws-edit-caregiver-select');
        },

        /**
         * Update total cats count automatically in edit form
         */
        updateEditTotalCatsCount: function() {
            const babies = parseInt(document.getElementById('claws-edit-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-edit-kittens-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-edit-adults-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-edit-seniors-count').value) || 0;
            
            const total = babies + kittens + adults + seniors;
            
            // Update a total display if it exists
            const totalDisplay = document.getElementById('claws-edit-total-cats-display');
            if (totalDisplay) {
                totalDisplay.textContent = total;
            }
        },

        /**
         * Load available caregivers from WordPress users - VERSION 2.0
         */
        loadAvailableCaregivers: async function(selectElementId) {
            const selectElement = document.getElementById(selectElementId);
            if (!selectElement) {
                return;
            }
            
            try {
                // Load WordPress users who can be caregivers - AGGRESSIVE CACHE BUSTING
                const timestamp = new Date().getTime();
                const random = Math.floor(Math.random() * 10000);
                const cacheBuster = `${timestamp}_${random}`;
                
                // Use WordPress REST API users endpoint, not CLAWS endpoint - ABSOLUTE URL
                const url = `https://clawsva.org/wp-json/wp/v2/users?_=${cacheBuster}&nocache=${cacheBuster}&per_page=100&context=edit`;
                
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    }
                });
                
                if (response.ok) {
                    const users = await response.json();
                    
                    // Filter users who can be caregivers (exclude pure subscribers)
                    const potentialCaregivers = users.filter(user => {
                        const roles = user.roles || [];
                        // Allow contributors, authors, administrators as caregivers
                        return roles.includes('contributor') || roles.includes('author') || roles.includes('administrator');
                    });
                    
                    this.populateCaregiverDropdown(selectElement, potentialCaregivers);
                } else {
                }
            } catch (error) {
            }
        },

        /**
         * Get demo caregiver data for testing (only when API is unavailable)
         */
        getDemoCaregivers: function() {
            // Return empty array - don't use placeholder data
            return [];
        },

        /**
         * Populate caregiver dropdown with available WordPress users
         */
        populateCaregiverDropdown: function(selectElement, users) {
            
            // Clear all existing options except "No assigned caregiver"
            selectElement.innerHTML = '<option value="none">No assigned caregiver</option>';
            
            let currentUserOption = null;
            const currentUserId = clawsData.userId ? clawsData.userId.toString() : null;
            const isAuthorOrAbove = clawsData.userRoles && (
                clawsData.userRoles.includes('author') || 
                clawsData.userRoles.includes('editor') || 
                clawsData.userRoles.includes('administrator')
            );
            
            // Add user options
            users.forEach(user => {
                const option = document.createElement('option');
                option.value = user.id;
                
                // Use display name, or fallback to first/last name, or username
                const displayName = user.display_name || user.name || `${user.first_name || ''} ${user.last_name || ''}`.trim() || user.username;
                option.textContent = displayName;
                
                // Track if this is the current user
                if (currentUserId && user.id.toString() === currentUserId) {
                    currentUserOption = option;
                }
                
                // Create caregiver data object from WordPress user
                const caregiverData = {
                    id: user.id,
                    name: displayName,
                    email: user.email || '',
                    phone: user.phone || user.user_meta?.phone || '',
                    allowEmail: true, // Default to allowing email for WP users
                    allowPhone: !!user.phone,
                    emergencyContact: false, // Can be set in user preferences later
                    publicVisible: true // Default to visible for registered users
                };
                
                option.dataset.caregiverData = JSON.stringify(caregiverData);
                selectElement.appendChild(option);
            });
            
            
            // Auto-select current user as caregiver for Add Colony form (not Edit form)
            if (selectElement.id === 'claws-caregiver-select' && currentUserOption && !this._pendingCaregiverSelection) {
                currentUserOption.selected = true;
                selectElement.value = currentUserOption.value;
                
                // Trigger change event to show caregiver info
                if (selectElement.id === 'claws-caregiver-select') {
                    this.handleCaregiverSelection.call(this, { target: selectElement });
                }
                
                
                // Show note for authors/editors/admins that they can change this
                if (isAuthorOrAbove) {
                }
            }
            
            // Handle pending caregiver selection after dropdown is populated (for Edit form)
            if (this._pendingCaregiverSelection) {
                this.selectPendingCaregiver();
            }
        },
        
        /**
         * Select the pending caregiver after dropdown is populated
         */
        selectPendingCaregiver: function() {
            const pending = this._pendingCaregiverSelection;
            if (!pending) return;
            
            const selectElement = pending.selectElement;
            
            // DON'T OVERRIDE: If caregiver is already selected correctly, don't change it
            if (selectElement.value && selectElement.value !== 'none' && selectElement.value == pending.caregiverId) {
                return;
            }
            
            // First try to find caregiver by ID (most accurate)
            if (pending.caregiverId) {
                
                for (let option of selectElement.options) {
                    if (option.value == pending.caregiverId) {
                        selectElement.value = option.value;
                        
                        // Trigger change event to show contact info
                        const event = new Event('change');
                        selectElement.dispatchEvent(event);
                        
                        this._pendingCaregiverSelection = null;
                        return;
                    }
                }
            }
            
            // Then try to find caregiver by name
            if (pending.caregiverName) {
                
                for (let option of selectElement.options) {
                    if (option.textContent.toLowerCase().includes(pending.caregiverName.toLowerCase()) || 
                        pending.caregiverName.toLowerCase().includes(option.textContent.toLowerCase())) {
                        selectElement.value = option.value;
                        
                        // Trigger change event to show contact info
                        const event = new Event('change');
                        selectElement.dispatchEvent(event);
                        
                        this._pendingCaregiverSelection = null;
                        return;
                    }
                }
                
                // If not found in dropdown, add as current option
                const currentOption = document.createElement('option');
                currentOption.value = 'current';
                currentOption.textContent = pending.caregiverName;
                
                const caregiverData = {
                    id: 'current',
                    name: pending.caregiverName,
                    email: '',
                    phone: '',
                    allowEmail: false,
                    allowPhone: false,
                    emergencyContact: false,
                    publicVisible: false
                };
                
                currentOption.dataset.caregiverData = JSON.stringify(caregiverData);
                selectElement.appendChild(currentOption);
                selectElement.value = 'current';
                
                // Trigger change event
                const event = new Event('change');
                selectElement.dispatchEvent(event);
                
            } else {
                selectElement.value = 'none';
            }
            
            this._pendingCaregiverSelection = null;
        },

        /**
         * Handle caregiver selection change in edit form
         */
        handleEditCaregiverSelection: function(event) {
            const selectedOption = event.target.selectedOptions[0];
            const caregiverInfo = document.getElementById('claws-edit-caregiver-info');
            const caregiverDetails = document.getElementById('claws-edit-caregiver-details');
            const communicationDiv = document.getElementById('claws-edit-caregiver-communication');
            
            if (!selectedOption || !selectedOption.dataset.caregiverData) {
                // No caregiver selected or "none" selected
                caregiverInfo.style.display = 'none';
                communicationDiv.style.display = 'none';
                return;
            }
            
            try {
                const caregiver = JSON.parse(selectedOption.dataset.caregiverData);
                
                // Only show contact info if we have real data
                let contactHtml = `<div style="margin-bottom: 0.5rem;"><strong>Name:</strong> ${caregiver.name}</div>`;
                let hasContactInfo = false;
                
                if (caregiver.email && caregiver.email.trim() !== '') {
                    contactHtml += `<div style="margin-bottom: 0.5rem;"><strong>Email:</strong> <a href="mailto:${caregiver.email}">${caregiver.email}</a></div>`;
                    hasContactInfo = true;
                }
                
                if (caregiver.phone && caregiver.phone.trim() !== '') {
                    contactHtml += `<div style="margin-bottom: 0.5rem;"><strong>Phone:</strong> <a href="tel:${caregiver.phone}">${caregiver.phone}</a></div>`;
                    hasContactInfo = true;
                }
                
                if (caregiver.emergencyContact) {
                    contactHtml += `<div style="color: #dc2626; font-weight: 600; margin-top: 0.5rem;">✓ Available for emergency contact</div>`;
                }
                
                if (hasContactInfo || caregiver.emergencyContact) {
                    caregiverDetails.innerHTML = contactHtml;
                    caregiverInfo.style.display = 'block';
                } else {
                    caregiverDetails.innerHTML = '<div style="color: #6b7280; font-style: italic;">No additional contact information available</div>';
                    caregiverInfo.style.display = 'block';
                }
                
                // Show communication preferences only if they exist
                const allowEmailField = document.getElementById('claws-edit-allow-email');
                const allowPhoneField = document.getElementById('claws-edit-allow-phone');
                const emergencyContactField = document.getElementById('claws-edit-emergency-contact');
                const publicVisibleField = document.getElementById('claws-edit-public-visible');
                
                if (allowEmailField) allowEmailField.checked = caregiver.allowEmail || false;
                if (allowPhoneField) allowPhoneField.checked = caregiver.allowPhone || false;
                if (emergencyContactField) emergencyContactField.checked = caregiver.emergencyContact || false;
                if (publicVisibleField) publicVisibleField.checked = caregiver.publicVisible || false;
                
                communicationDiv.style.display = 'block';
                
            } catch (error) {
                caregiverInfo.style.display = 'none';
                communicationDiv.style.display = 'none';
            }
        },

        /**
         * Setup form event listeners
         */
        setupFormEventListeners: function() {
            // Auto-calculate total cats when individual counts change
            const countFields = ['claws-babies-count', 'claws-kittens-count', 'claws-juveniles-count', 'claws-adults-count'];
            countFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.addEventListener('input', this.updateTotalCatsCount.bind(this));
                }
            });
            
            // Geocoding when address changes
            const addressFields = ['claws-colony-street', 'claws-colony-city', 'claws-colony-state', 'claws-colony-zip'];
            addressFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.addEventListener('blur', this.attemptGeocoding.bind(this));
                }
            });
            
            // Handle caregiver selection changes
            const caregiverSelect = document.getElementById('claws-caregiver-select');
            if (caregiverSelect) {
                caregiverSelect.addEventListener('change', this.handleCaregiverSelection.bind(this));
            }
            
            // Load available caregivers
            this.loadAvailableCaregivers('claws-caregiver-select');
        },

        /**
         * Handle caregiver selection change in add form
         */
        handleCaregiverSelection: function(event) {
            const selectedOption = event.target.selectedOptions[0];
            const caregiverInfo = document.getElementById('claws-caregiver-info');
            const caregiverDetails = document.getElementById('claws-caregiver-details');
            const communicationDiv = document.getElementById('claws-caregiver-communication');
            
            if (!selectedOption || !selectedOption.dataset.caregiverData) {
                // No caregiver selected or "none" selected
                caregiverInfo.style.display = 'none';
                communicationDiv.style.display = 'none';
                return;
            }
            
            try {
                const caregiver = JSON.parse(selectedOption.dataset.caregiverData);
                
                // Show contact info if public visible is enabled
                if (caregiver.publicVisible) {
                    let contactHtml = `<div style="margin-bottom: 0.5rem;"><strong>Name:</strong> ${caregiver.name}</div>`;
                    
                    if (caregiver.allowEmail && caregiver.email) {
                        contactHtml += `<div style="margin-bottom: 0.5rem;"><strong>Email:</strong> <a href="mailto:${caregiver.email}">${caregiver.email}</a></div>`;
                    }
                    
                    if (caregiver.allowPhone && caregiver.phone) {
                        contactHtml += `<div style="margin-bottom: 0.5rem;"><strong>Phone:</strong> <a href="tel:${caregiver.phone}">${caregiver.phone}</a></div>`;
                    }
                    
                    if (caregiver.emergencyContact) {
                        contactHtml += `<div style="color: #dc2626; font-weight: 600; margin-top: 0.5rem;">✓ Available for emergency contact</div>`;
                    }
                    
                    caregiverDetails.innerHTML = contactHtml;
                    caregiverInfo.style.display = 'block';
                } else {
                    caregiverDetails.innerHTML = '<div style="color: #6b7280; font-style: italic;">Contact information is private</div>';
                    caregiverInfo.style.display = 'block';
                }
                
                // Show communication preferences
                document.getElementById('claws-allow-email').checked = caregiver.allowEmail;
                document.getElementById('claws-allow-phone').checked = caregiver.allowPhone;
                document.getElementById('claws-emergency-contact').checked = caregiver.emergencyContact;
                document.getElementById('claws-public-visible').checked = caregiver.publicVisible;
                
                communicationDiv.style.display = 'block';
                
            } catch (error) {
                caregiverInfo.style.display = 'none';
                communicationDiv.style.display = 'none';
            }
        },

        /**
         * Update total cats count automatically
         */
        updateTotalCatsCount: function() {
            const babies = parseInt(document.getElementById('claws-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-kittens-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-seniors-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-adults-count').value) || 0;
            
            const total = babies + kittens + adults + seniors;
            
            // Update a total display if it exists
            const totalDisplay = document.getElementById('claws-total-cats-display');
            if (totalDisplay) {
                totalDisplay.textContent = total;
            }
        },

        /**
         * Attempt geocoding when address fields are filled
         */
        attemptGeocoding: function() {
            const street = document.getElementById('claws-colony-street').value;
            const city = document.getElementById('claws-colony-city').value;
            const state = document.getElementById('claws-colony-state').value;
            const zip = document.getElementById('claws-colony-zip').value;
            
            if (street && city && state) {
                const address = `${street}, ${city}, ${state} ${zip}`.trim();
                this.geocodeAddress(address);
            }
        },

        /**
         * Geocode an address to get coordinates
         */
        geocodeAddress: async function(address) {
            try {
                const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}&limit=1`);
                const data = await response.json();
                
                if (data && data.length > 0) {
                    const result = data[0];
                    document.getElementById('claws-colony-lat').value = parseFloat(result.lat).toFixed(6);
                    document.getElementById('claws-colony-lng').value = parseFloat(result.lon).toFixed(6);
                }
            } catch (error) {
            }
        },

        /**
         * Populate colony form with existing data
         */
        populateColonyForm: function(colony) {
            // Basic info
            const nameField = document.getElementById('claws-colony-name');
            if (nameField) {
                nameField.value = colony.name || '';
            }
            
            // Set date - use colony date if available, otherwise today
            const dateField = document.getElementById('claws-colony-date');
            if (dateField) {
                if (colony.date) {
                    // If colony has a date, use it (convert if needed)
                    const colonyDate = new Date(colony.date);
                    dateField.value = colonyDate.toISOString().split('T')[0];
                } else {
                    // Otherwise use today
                    dateField.value = new Date().toISOString().split('T')[0];
                }
            }
            
            // Check if form fields exist
            const streetField = document.getElementById('claws-colony-street');
            const cityField = document.getElementById('claws-colony-city');
            const stateField = document.getElementById('claws-colony-state');
            const zipField = document.getElementById('claws-colony-zip');
            
            // Address fields - handle both individual fields and combined address
            if (colony.street || colony.city || colony.state || colony.zip) {
                // Use individual fields if available
                if (streetField) streetField.value = colony.street || '';
                if (cityField) cityField.value = colony.city || '';
                if (stateField) stateField.value = colony.state || '';
                if (zipField) zipField.value = colony.zip || '';
            } else if (colony.address) {
                // Parse combined address if individual fields are empty
                const addressParts = this.parseAddress(colony.address);
                if (streetField) streetField.value = addressParts.street || '';
                if (cityField) cityField.value = addressParts.city || '';
                if (stateField) stateField.value = addressParts.state || '';
                if (zipField) zipField.value = addressParts.zip || '';
            } else {
                // Clear fields if no address data
                if (streetField) streetField.value = '';
                if (cityField) cityField.value = '';
                if (stateField) stateField.value = '';
                if (zipField) zipField.value = '';
            }
            
            // Population counts
            const babiesField = document.getElementById('claws-babies-count');
            const kittensField = document.getElementById('claws-kittens-count');
            const seniorsField = document.getElementById('claws-seniors-count'); 
            const adultsField = document.getElementById('claws-adults-count');
            
            if (babiesField) {
                babiesField.value = colony.babies || 0;
            }
            if (kittensField) {
                kittensField.value = colony.kittens || 0;
            }
            if (seniorsField) {
                seniorsField.value = colony.seniors || 0;
            }
            if (adultsField) {
                adultsField.value = colony.adults || 0;
            }
            
            // Security assessments
            const feedingField = document.getElementById('claws-feeding-security');
            const shelterField = document.getElementById('claws-shelter-security');
            const waterField = document.getElementById('claws-water-security');
            
            if (feedingField) {
                feedingField.value = colony.foodSecurity || '';
            }
            if (shelterField) {
                shelterField.value = colony.safeLocation || '';
            }
            if (waterField) {
                waterField.value = colony.waterSecurity || '';
            }
            
            // Location
            const latField = document.getElementById('claws-colony-lat');
            const lngField = document.getElementById('claws-colony-lng');
            
            if (latField) {
                latField.value = colony.lat || '';
            }
            if (lngField) {
                lngField.value = colony.lng || '';
            }
            
            // TNR & Care Information
            const tippedEarsField = document.getElementById('claws-tipped-ears');
            const winterSheltersField = document.getElementById('claws-winter-shelters');
            const caregiverField = document.getElementById('claws-caregiver');
            
            if (tippedEarsField) {
                tippedEarsField.value = colony.tippedEars || 0;
            }
            if (winterSheltersField) {
                winterSheltersField.value = colony.winterShelters || 0;
            }
            if (caregiverField) {
                // Handle caregiver data - could be string or object/array
                let caregiverValue = '';
                if (colony.caregiver) {
                    caregiverValue = colony.caregiver;
                } else if (colony.caregivers && Array.isArray(colony.caregivers) && colony.caregivers.length > 0) {
                    // Extract name from first caregiver object
                    const firstCaregiver = colony.caregivers[0];
                    caregiverValue = firstCaregiver.name || firstCaregiver.displayName || firstCaregiver.userName || JSON.stringify(firstCaregiver);
                } else {
                }
                caregiverField.value = caregiverValue;
            }
            
            // Notes
            const notesField = document.getElementById('claws-colony-notes');
            if (notesField) {
                notesField.value = colony.notes || '';
            }
            
            // Store the colony for updates
            this.currentEditingColony = colony;
        },

        /**
         * Populate edit colony form with existing data
         */
        populateEditColonyForm: function(colony) {
            // Basic info
            const nameField = document.getElementById('claws-edit-colony-name');
            if (nameField) {
                nameField.value = colony.name || '';
            }
            
            // Populate effective date display
            const effectiveDateField = document.getElementById('claws-edit-effective-date');
            if (effectiveDateField) {
                // Use colony creation date (dateAdded) as the effective date
                const effectiveDate = colony.dateAdded ? new Date(colony.dateAdded) : new Date();
                const formattedDate = effectiveDate.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
                effectiveDateField.textContent = formattedDate;
            }
            
            // Set date - use colony date if available, otherwise today
            const dateField = document.getElementById('claws-edit-colony-date');
            if (dateField) {
                if (colony.date) {
                    const colonyDate = new Date(colony.date);
                    dateField.value = colonyDate.toISOString().split('T')[0];
                } else {
                    dateField.value = new Date().toISOString().split('T')[0];
                }
            }
            
            // Population counts
            const babiesField = document.getElementById('claws-edit-babies-count');
            const kittensField = document.getElementById('claws-edit-kittens-count');
            const adultsField = document.getElementById('claws-edit-adults-count');
            const seniorsField = document.getElementById('claws-edit-seniors-count');
            
            if (babiesField) {
                babiesField.value = colony.babies || 0;
            }
            if (kittensField) {
                kittensField.value = colony.kittens || 0;
            }
            if (seniorsField) {
                seniorsField.value = colony.seniors || 0;
            }
            if (adultsField) {
                adultsField.value = colony.adults || 0;
            }
            
            // Security assessments
            const feedingField = document.getElementById('claws-edit-feeding-security');
            const shelterField = document.getElementById('claws-edit-shelter-security');
            const waterField = document.getElementById('claws-edit-water-security');
            
            if (feedingField) {
                feedingField.value = colony.foodSecurity || '';
            }
            if (shelterField) {
                shelterField.value = colony.safeLocation || '';
            }
            if (waterField) {
                waterField.value = colony.waterSecurity || '';
            }
            
            // TNR & Care Information
            const tippedEarsField = document.getElementById('claws-edit-tipped-ears');
            const winterSheltersField = document.getElementById('claws-edit-winter-shelters');
            const caregiverSelect = document.getElementById('claws-edit-caregiver-select');
            
            if (tippedEarsField) {
                tippedEarsField.value = colony.tippedEars || 0;
            }
            if (winterSheltersField) {
                winterSheltersField.value = colony.winterShelters || 0;
            }
            
            // Handle caregiver selection - wait for dropdown to be populated first
            if (caregiverSelect) {
                
                // Try different possible caregiver property names
                const caregiverName = colony.caregiver || 
                                    (colony.caregivers && colony.caregivers[0] && colony.caregivers[0].name) ||
                                    colony.primaryCaregiver ||
                                    colony.caregiver_name ||
                                    (colony.caregivers && colony.caregivers[0]);
                
                const caregiverId = colony.caregiverId || 
                                  (colony.caregivers && colony.caregivers[0] && colony.caregivers[0].id) ||
                                  colony.caregiver_id;
                
                
                // IMMEDIATE FIX: If we have a caregiver ID, set it right now (like other persistent fields)
                if (caregiverId && caregiverId !== 'none') {
                    // First check if the option already exists
                    let optionExists = false;
                    for (let i = 0; i < caregiverSelect.options.length; i++) {
                        if (caregiverSelect.options[i].value == caregiverId) {
                            caregiverSelect.selectedIndex = i;
                            optionExists = true;
                            // Trigger the change event to show caregiver info
                            this.handleEditCaregiverSelection.call(this, { target: caregiverSelect });
                            break;
                        }
                    }
                    
                    // If option doesn't exist, create it now (like we do for feeding security static options)
                    if (!optionExists && caregiverName) {
                        const tempOption = document.createElement('option');
                        tempOption.value = caregiverId;
                        tempOption.textContent = caregiverName;
                        tempOption.selected = true;
                        // Add caregiver data for compatibility
                        tempOption.dataset.caregiverData = JSON.stringify({
                            id: caregiverId,
                            name: caregiverName,
                            email: '',
                            phone: ''
                        });
                        caregiverSelect.appendChild(tempOption);
                        // Trigger the change event to show caregiver info
                        this.handleEditCaregiverSelection.call(this, { target: caregiverSelect });
                    }
                }
                
                // Store caregiver selection for after dropdown is populated (as backup for when full list loads)
                this._pendingCaregiverSelection = {
                    caregiverName: caregiverName,
                    caregiverId: caregiverId,
                    caregivers: colony.caregivers,
                    selectElement: caregiverSelect
                };
                
            }
            
            // Notes
            const notesField = document.getElementById('claws-edit-colony-notes');
            if (notesField) {
                notesField.value = colony.notes || '';
            }
            
            // Display location information (read-only)
            const locationDisplay = document.getElementById('claws-edit-location-display');
            if (locationDisplay) {
                const addressParts = [];
                if (colony.street) addressParts.push(colony.street);
                if (colony.city) addressParts.push(colony.city);
                if (colony.state) addressParts.push(colony.state);
                if (colony.zip) addressParts.push(colony.zip);
                
                let addressText = '';
                if (addressParts.length > 0) {
                    addressText = addressParts.join(', ');
                } else if (colony.address && colony.address.trim()) {
                    addressText = colony.address.trim();
                } else {
                    addressText = 'Address not specified';
                }
                
                const coordsText = (colony.lat && colony.lng) 
                    ? `${parseFloat(colony.lat).toFixed(4)}, ${parseFloat(colony.lng).toFixed(4)}`
                    : 'Coordinates not available';
                
                locationDisplay.innerHTML = `
                    <div style="margin-bottom: 0.5rem;"><strong>Address:</strong> ${addressText}</div>
                    <div><strong>Coordinates:</strong> ${coordsText}</div>
                `;
            }
            
            // Store the colony for updates
            this.currentEditingColony = colony;
        },

        /**
         * Parse combined address into components
         */
        parseAddress: function(address) {
            const parts = address.split(',').map(part => part.trim());
            
            return {
                street: parts[0] || '',
                city: parts[1] || '',
                state: parts[2] ? parts[2].split(' ')[0] : '',
                zip: parts[2] ? parts[2].split(' ')[1] : ''
            };
        },

        /**
         * Validate edit form data
         */
        validateEditColonyForm: function() {
            const name = document.getElementById('claws-edit-colony-name').value.trim();
            
            
            if (!name) {
                this.showAlert('Colony name is required', 'error');
                return false;
            }
            
            // Check for duplicate names (excluding current editing colony)
            const existingColony = this.colonies.find(colony => 
                colony.name.toLowerCase() === name.toLowerCase() && 
                (!this.currentEditingColony || colony.id !== this.currentEditingColony.id)
            );
            
            
            if (existingColony) {
                this.showAlert('A colony with this name already exists', 'error');
                return false;
            }
            
            // Check required security fields for edit form
            const foodSecurity = document.getElementById('claws-edit-feeding-security').value;
            if (!foodSecurity) {
                this.showAlert('Feeding Security is required', 'error');
                return false;
            }
            
            const waterSecurity = document.getElementById('claws-edit-water-security').value;
            if (!waterSecurity) {
                this.showAlert('Water Security is required', 'error');
                return false;
            }
            
            const shelterSecurity = document.getElementById('claws-edit-shelter-security').value;
            if (!shelterSecurity) {
                this.showAlert('Shelter Security is required', 'error');
                return false;
            }
            
            return true;
        },

        /**
         * Collect edit form data
         */
        collectEditFormData: function() {
            const newborn = parseInt(document.getElementById('claws-edit-babies-count').value) || 0;
            const kitten = parseInt(document.getElementById('claws-edit-kittens-count').value) || 0;
            const cat = parseInt(document.getElementById('claws-edit-adults-count').value) || 0;
            const senior = parseInt(document.getElementById('claws-edit-seniors-count').value) || 0;
            
            // Get selected caregiver
            const caregiverSelect = document.getElementById('claws-edit-caregiver-select');
            const selectedCaregiverId = caregiverSelect ? caregiverSelect.value : null;
            let caregiverName = null;
            
            // Get caregiver name from the selected option
            if (caregiverSelect && selectedCaregiverId && selectedCaregiverId !== 'none') {
                const selectedOption = caregiverSelect.options[caregiverSelect.selectedIndex];
                caregiverName = selectedOption ? selectedOption.text : null;
            }
            
            // Get communication preferences
            const allowEmail = document.getElementById('claws-edit-allow-email') ? document.getElementById('claws-edit-allow-email').checked : false;
            const allowPhone = document.getElementById('claws-edit-allow-phone') ? document.getElementById('claws-edit-allow-phone').checked : false;
            const emergencyContact = document.getElementById('claws-edit-emergency-contact') ? document.getElementById('claws-edit-emergency-contact').checked : false;
            const publicVisible = document.getElementById('claws-edit-public-visible') ? document.getElementById('claws-edit-public-visible').checked : false;
            
            return {
                name: document.getElementById('claws-edit-colony-name').value.trim(),
                date: document.getElementById('claws-edit-colony-date').value,
                effectiveDate: document.getElementById('claws-edit-colony-date').value, // Backend expects this field
                newborn: newborn,
                kitten: kitten,
                cat: cat,
                senior: senior,
                cats: newborn + kitten + cat + senior,
                foodSecurity: document.getElementById('claws-edit-feeding-security').value,
                safeLocation: document.getElementById('claws-edit-shelter-security').value,
                waterSecurity: document.getElementById('claws-edit-water-security').value,
                tippedEars: parseInt(document.getElementById('claws-edit-tipped-ears').value) || 0,
                winterShelters: parseInt(document.getElementById('claws-edit-winter-shelters').value) || 0,
                caregiver: caregiverName,
                caregiverId: selectedCaregiverId && selectedCaregiverId !== 'none' ? selectedCaregiverId : null,
                caregiverCommunication: {
                    allowEmail: allowEmail,
                    allowPhone: allowPhone,
                    emergencyContact: emergencyContact,
                    publicVisible: publicVisible
                },
                notes: document.getElementById('claws-edit-colony-notes').value.trim(),
                // Preserve original location data - don't allow editing
                street: this.currentEditingColony ? this.currentEditingColony.street : '',
                city: this.currentEditingColony ? this.currentEditingColony.city : '',
                state: this.currentEditingColony ? this.currentEditingColony.state : '',
                zip: this.currentEditingColony ? this.currentEditingColony.zip : '',
                lat: this.currentEditingColony ? this.currentEditingColony.lat : null,
                lng: this.currentEditingColony ? this.currentEditingColony.lng : null
            };
        },

        /**
         * Validate form data
         */
        validateColonyForm: function() {
            const name = document.getElementById('claws-colony-name').value.trim();
            
            if (!name) {
                this.showAlert('Colony name is required', 'error');
                return false;
            }
            
            // Check for duplicate names (excluding current editing colony)
            const existingColony = this.colonies.find(colony => 
                colony.name.toLowerCase() === name.toLowerCase() && 
                (!this.currentEditingColony || colony.id !== this.currentEditingColony.id)
            );
            
            if (existingColony) {
                this.showAlert('A colony with this name already exists', 'error');
                return false;
            }
            
            // Check required address fields
            const street = document.getElementById('claws-colony-street').value.trim();
            const city = document.getElementById('claws-colony-city').value.trim();
            const state = document.getElementById('claws-colony-state').value.trim();
            const zip = document.getElementById('claws-colony-zip').value.trim();
            
            if (!street) {
                this.showAlert('Street Address is required', 'error');
                return false;
            }
            if (!city) {
                this.showAlert('City is required', 'error');
                return false;
            }
            if (!state) {
                this.showAlert('State is required', 'error');
                return false;
            }
            if (!zip) {
                this.showAlert('ZIP Code is required', 'error');
                return false;
            }
            
            // Check total cat count - must have at least one cat
            const babies = parseInt(document.getElementById('claws-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-kittens-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-adults-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-seniors-count').value) || 0;
            const totalCats = babies + kittens + adults + seniors;
            
            if (totalCats === 0) {
                this.showAlert('A colony must have at least one cat assigned to it', 'error');
                return false;
            }
            
            // Check required security fields (use correct JavaScript form IDs)
            const foodSecurity = document.getElementById('claws-feeding-security').value;
            if (!foodSecurity) {
                this.showAlert('Feeding Security is required', 'error');
                return false;
            }
            
            const waterSecurity = document.getElementById('claws-water-security').value;
            if (!waterSecurity) {
                this.showAlert('Water Security is required', 'error');
                return false;
            }
            
            const shelterSecurity = document.getElementById('claws-shelter-security').value;
            if (!shelterSecurity) {
                this.showAlert('Shelter Security is required', 'error');
                return false;
            }
            
            // Check required numeric fields
            const tippedEars = document.getElementById('claws-tipped-ears').value;
            if (tippedEars === '') {
                this.showAlert('Tipped Ears is required', 'error');
                return false;
            }
            
            const winterShelters = document.getElementById('claws-winter-shelters').value;
            if (winterShelters === '') {
                this.showAlert('Winter Shelters is required', 'error');
                return false;
            }
            
            return true;
        },

        /**
         * Collect form data
         */
        collectFormData: function() {
            const babies = parseInt(document.getElementById('claws-babies-count').value) || 0;
            const kittens = parseInt(document.getElementById('claws-kittens-count').value) || 0;
            const seniors = parseInt(document.getElementById('claws-seniors-count').value) || 0;
            const adults = parseInt(document.getElementById('claws-adults-count').value) || 0;
            
            // Get selected caregiver
            const caregiverSelect = document.getElementById('claws-caregiver-select');
            const selectedCaregiverId = caregiverSelect ? caregiverSelect.value : null;
            
            // Get communication preferences
            const allowEmail = document.getElementById('claws-allow-email') ? document.getElementById('claws-allow-email').checked : false;
            const allowPhone = document.getElementById('claws-allow-phone') ? document.getElementById('claws-allow-phone').checked : false;
            const emergencyContact = document.getElementById('claws-emergency-contact') ? document.getElementById('claws-emergency-contact').checked : false;
            const publicVisible = document.getElementById('claws-public-visible') ? document.getElementById('claws-public-visible').checked : false;
            
            return {
                name: document.getElementById('claws-colony-name').value.trim(),
                date: document.getElementById('claws-colony-date').value,
                street: document.getElementById('claws-colony-street').value.trim(),
                city: document.getElementById('claws-colony-city').value.trim(),
                state: document.getElementById('claws-colony-state').value.trim(),
                zip: document.getElementById('claws-colony-zip').value.trim(),
                babies: babies,
                kittens: kittens,
                seniors: seniors,
                adults: adults,
                cats: babies + kittens + adults + seniors,
                foodSecurity: document.getElementById('claws-feeding-security').value,
                safeLocation: document.getElementById('claws-shelter-security').value,
                waterSecurity: document.getElementById('claws-water-security').value,
                tippedEars: parseInt(document.getElementById('claws-tipped-ears').value) || 0,
                winterShelters: parseInt(document.getElementById('claws-winter-shelters').value) || 0,
                caregiverId: selectedCaregiverId && selectedCaregiverId !== 'none' ? selectedCaregiverId : null,
                caregiverCommunication: {
                    allowEmail: allowEmail,
                    allowPhone: allowPhone,
                    emergencyContact: emergencyContact,
                    publicVisible: publicVisible
                },
                lat: parseFloat(document.getElementById('claws-colony-lat').value) || null,
                lng: parseFloat(document.getElementById('claws-colony-lng').value) || null,
                notes: document.getElementById('claws-colony-notes').value.trim()
            };
        },

        /**
         * Save new colony
         */
        saveColony: async function() {
            if (!this.validateColonyForm()) {
                return;
            }
            
            const formData = this.collectFormData();
            
            try {
                const cacheBuster = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
                const response = await fetch(`${this.config.apiUrl}colony?_cb=${cacheBuster}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(formData)
                });
                
                if (response.ok) {
                    const newColony = await response.json();
                    const colonyId = newColony.id || newColony.ID;
                    
                    // Upload photos if any were selected
                    if (colonyId) {
                        const photosInput = document.getElementById('claws-colony-photos');
                        if (photosInput && photosInput.files && photosInput.files.length > 0) {
                            const photoResults = await this.uploadColonyPhotos(colonyId, photosInput.files);
                            if (photoResults.failed > 0) {
                                this.showAlert(`Colony saved! ${photoResults.success} photo(s) uploaded, ${photoResults.failed} failed.`, 'warning');
                            } else if (photoResults.success > 0) {
                                this.showAlert(`Colony saved successfully with ${photoResults.success} photo(s)!`, 'success');
                            } else {
                                this.showAlert('Colony saved successfully!', 'success');
                            }
                        } else {
                            this.showAlert('Colony saved successfully!', 'success');
                        }
                    } else {
                        this.showAlert('Colony saved successfully!', 'success');
                    }
                    
                    // Reload all colonies from server to ensure proper data formatting
                    await this.loadColonies();
                    this.hideAddColonyForm();
                } else {
                    throw new Error('Failed to save colony');
                }
            } catch (error) {
                this.showAlert('Failed to save colony. Please try again.', 'error');
            }
        },

        /**
         * Update existing colony using edit form
         */
        updateColonyFromEditForm: async function(colonyId) {
            // Prevent duplicate calls
            if (this._updating) {
                return;
            }
            this._updating = true;
            
            if (!this.validateEditColonyForm()) {
                this._updating = false;
                return;
            }
            
            const formData = this.collectEditFormData();
            
            try {
                
                const cacheBuster = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
                const apiUrl = `${this.config.apiUrl}colony/${colonyId}?_cb=${cacheBuster}`;
                const response = await fetch(apiUrl, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce || ''
                    },
                    body: JSON.stringify(formData)
                });
                
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // Upload photos if any were selected
                    const photosInput = document.getElementById('claws-edit-colony-photos');
                    if (photosInput && photosInput.files && photosInput.files.length > 0) {
                        const photoResults = await this.uploadColonyPhotos(colonyId, photosInput.files);
                        if (photoResults.failed > 0) {
                            this.showAlert(`Colony updated! ${photoResults.success} photo(s) uploaded, ${photoResults.failed} failed.`, 'warning');
                        } else if (photoResults.success > 0) {
                            this.showAlert(`Colony updated successfully with ${photoResults.success} photo(s)!`, 'success');
                        } else {
                            this.showAlert('Colony updated successfully!', 'success');
                        }
                    } else {
                        this.showAlert('Colony updated successfully!', 'success');
                    }
                    
                    // Reload all colonies from server to ensure proper data formatting
                    await this.loadColonies();
                    this.hideEditColonyForm();
                } else {
                    const errorText = await response.text();
                    throw new Error(`Failed to update colony: ${response.status} - ${errorText}`);
                }
            } catch (error) {
                this.showAlert(`Failed to update colony: ${error.message}`, 'error');
            } finally {
                // Reset the updating flag
                this._updating = false;
            }
        },

        /**
         * Update existing colony
         */
        updateColony: async function(colonyId) {
            if (!this.validateColonyForm()) {
                return;
            }
            
            const formData = this.collectFormData();
            
            try {
                const cacheBuster = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
                const response = await fetch(`${this.config.apiUrl}colony/${colonyId}?_cb=${cacheBuster}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(formData)
                });
                
                if (response.ok) {
                    const updatedColony = await response.json();
                    // Reload all colonies from server to ensure proper data formatting
                    await this.loadColonies();
                    this.hideAddColonyForm();
                    this.showAlert('Colony updated successfully!', 'success');
                } else {
                    throw new Error('Failed to update colony');
                }
            } catch (error) {
                this.showAlert('Failed to update colony. Please try again.', 'error');
            }
        },


        /**
         * Format date for user-friendly display
         */
        formatDateForDisplay: function(date) {
            const options = {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: true
            };
            return date.toLocaleDateString('en-US', options);
        },

        /**
         * Initialize interactive map for Add New Colony form
         */
        initializeAddColonyMap: function(retryCount = 0) {
            // Cleanup existing map first
            if (this._addColonyMap) {
                this._addColonyMap.remove();
                this._addColonyMap = null;
            }
            
            const mapContainer = document.getElementById('claws-add-colony-map');
            
            if (!mapContainer) {
                if (retryCount < 5) {
                    setTimeout(() => this.initializeAddColonyMap(retryCount + 1), 200);
                    return;
                }
                return;
            }
            
            // Check if Leaflet is available
            if (typeof L === 'undefined') {
                if (retryCount < 10) {
                    setTimeout(() => this.initializeAddColonyMap(retryCount + 1), 200);
                    return;
                }
                return;
            }
            
            // Clear any existing map content
            mapContainer.innerHTML = '';
            
            try {
                // Initialize map centered on Lebanon, VA (matching main map)
                const defaultLat = this.config.defaultLatitude || 36.900942; // Lebanon, VA
                const defaultLng = this.config.defaultLongitude || -82.080131; // Lebanon, VA
                
                const map = L.map('claws-add-colony-map').setView([defaultLat, defaultLng], 14);
                
                
                // Add tile layer with error handling
                const tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors',
                    maxZoom: 19,
                    timeout: 10000,
                    errorTileUrl: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMGYwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJzYW5zLXNlcmlmIiBmb250LXNpemU9IjE2IiBmaWxsPSIjOTk5IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+VGlsZSBub3QgYXZhaWxhYmxlPC90ZXh0Pjwvc3ZnPg=='
                }).addTo(map);
                
                // Variable to store the marker
                let locationMarker = null;
                
                
                // Handle map clicks to set location
                map.on('click', (e) => {
                    const lat = e.latlng.lat;
                    const lng = e.latlng.lng;
                    
                    
                    // Remove existing marker
                    if (locationMarker) {
                        map.removeLayer(locationMarker);
                    }
                    
                    // Add new marker
                    locationMarker = L.marker([lat, lng]).addTo(map);
                    
                    // Update coordinate inputs
                    const latInput = document.getElementById('claws-colony-lat');
                    const lngInput = document.getElementById('claws-colony-lng');
                    const coordsDisplay = document.getElementById('claws-selected-coordinates');
                    
                    if (latInput && lngInput && coordsDisplay) {
                        latInput.value = lat.toFixed(6);
                        lngInput.value = lng.toFixed(6);
                        coordsDisplay.textContent = `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
                        coordsDisplay.style.color = '#059669'; // Green color for selected
                    }
                });
                
                
                // Force map resize after initialization
                setTimeout(() => {
                    map.invalidateSize();
                }, 100);
                
                // Store map reference for cleanup
                this._addColonyMap = map;
                
                
            } catch (error) {
            }
        },

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

        /**
         * Create intake form modal - RESTORED ORIGINAL WITH PHOTO & AI
         */
        createIntakeFormModal: function() {
            const modal = document.createElement('div');
            modal.id = 'claws-intake-form-modal';
            modal.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; padding: 1rem;';
            
            modal.innerHTML = `
                <div style="background: white; border-radius: 1rem; width: 100%; max-width: 28rem; max-height: 90vh; overflow-y: auto;">
                    <div style="padding: 1rem;">
                        <!-- Modal Header -->
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">
                            <h2 style="font-size: 1.25rem; font-weight: bold; color: #1f2937; margin: 0;">New Cat Intake</h2>
                            <button onclick="CLAWSApp.hideIntakeForm()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; padding: 0.25rem; border-radius: 0.25rem;">×</button>
                        </div>
                        
                        <!-- Form Content -->
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            <!-- Date -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Date</label>
                                <input type="date" id="claws-intake-date" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;" value="${new Date().toISOString().split('T')[0]}" />
                            </div>
                            
                            <!-- Contact Information -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Contact Information</h3>
                                <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Name *</label>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                            <input type="text" id="claws-intake-contact-first-name" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="First Name" />
                                            <input type="text" id="claws-intake-contact-last-name" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="Last Name" />
                                        </div>
                                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                            <input type="checkbox" id="claws-intake-anonymous" style="margin: 0;" />
                                            Anonymous/Drop off
                                        </label>
                                    </div>
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Address *</label>
                                        <div style="display: grid; grid-template-columns: 1fr; gap: 0.75rem;">
                                            <div>
                                                <input type="text" id="claws-intake-street" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="Street Address" />
                                            </div>
                                            <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 0.5rem;">
                                                <input type="text" id="claws-intake-city" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="City" />
                                                <input type="text" id="claws-intake-state" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="State" />
                                                <input type="text" id="claws-intake-zip" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="Zip Code" />
                                            </div>
                                        </div>
                                        <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                            <input type="checkbox" id="claws-intake-dropoff" style="margin: 0;" />
                                            Drop Off
                                        </label>
                                    </div>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Phone Number *</label>
                                            <input type="tel" id="claws-intake-phone" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="(555) 123-4567" />
                                            <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                                <input type="checkbox" id="claws-intake-phone-unknown" style="margin: 0;" />
                                                Unknown
                                            </label>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Email Address *</label>
                                            <input type="email" id="claws-intake-email" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="email@example.com" />
                                            <label style="display: flex; align-items: center; gap: 0.5rem; font-size: 0.7rem; color: #6b7280; margin-top: 0.25rem;">
                                                <input type="checkbox" id="claws-intake-email-unknown" style="margin: 0;" />
                                                Unknown
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Cat Information -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Cat Information</h3>
                                <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Name *</label>
                                        <input type="text" id="claws-intake-cat-name" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="What do we call this cat?" />
                                    </div>
                                    
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Age *</label>
                                            <select id="claws-intake-age" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                                <option value="">Select age category</option>
                                                <option value="Newborn (0-8 weeks)">Newborn (0-8 weeks)</option>
                                                <option value="Kitten (2-5 months)">Kitten (2-5 months)</option>
                                                <option value="Cat (6 months to 8 years)">Cat (6 months to 8 years)</option>
                                                <option value="Senior (Older than 8 years)">Senior (Older than 8 years)</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Gender *</label>
                                            <select id="claws-intake-gender" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                                <option value="">Select gender</option>
                                                <option value="Male">Male</option>
                                                <option value="Female">Female</option>
                                                <option value="Unknown">Unknown</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem;">
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Coat *</label>
                                            <select id="claws-intake-coat" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                                <option value="">Select coat type</option>
                                                <option value="Short">Short</option>
                                                <option value="Medium">Medium</option>
                                                <option value="Long">Long</option>
                                                <option value="Hairless">Hairless</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Color *</label>
                                            <input type="text" id="claws-intake-color" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" placeholder="e.g., Orange tabby, Black and white" />
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Type *</label>
                                        <select id="claws-intake-type" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" onchange="CLAWSApp.handleIntakeTypeChange()">
                                            <option value="">Select cat type</option>
                                            <option value="Stray">Stray</option>
                                            <option value="Feral">Feral</option>
                                            <option value="Friendly/Socialized">Friendly/Socialized</option>
                                            <option value="Semi-feral">Semi-feral</option>
                                            <option value="Colony Cat">Colony Cat</option>
                                        </select>
                                    </div>
                                    
                                    <!-- Colony Assignment (shows when Colony Cat is selected) -->
                                    <div id="claws-colony-assignment-container" style="display: none;">
                                        <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.25rem;">Colony Assignment</label>
                                        <select id="claws-intake-colony" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;">
                                            <option value="">Select colony...</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Photo Upload -->
                            <div style="background: #f9fafb; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e5e7eb;">
                                <h3 style="font-weight: 500; color: #1f2937; margin: 0 0 0.75rem; font-size: 0.875rem;">Cat Photo (Optional)</h3>
                                <div>
                                    <label style="display: block; font-size: 0.75rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Upload Photo</label>
                                    <input type="file" id="claws-intake-photo" accept="image/jpeg,image/png,image/webp" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem; box-sizing: border-box;" onchange="CLAWSApp.handleIntakePhotoUpload(this)" />
                                    <div id="claws-intake-photo-preview" style="margin-top: 0.5rem; display: none;">
                                        <img id="claws-intake-photo-img" style="max-width: 100%; height: 100px; object-fit: cover; border-radius: 0.375rem; border: 1px solid #e5e7eb;" />
                                    </div>
                                    <button type="button" id="claws-ai-analyze-btn" onclick="CLAWSApp.analyzePhotoWithAI()" style="margin-top: 0.5rem; padding: 0.5rem 1rem; background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; border: none; border-radius: 0.375rem; font-size: 0.75rem; cursor: pointer; display: none;">
                                        🤖 AI Analyze Coat & Color
                                    </button>
                                    <div id="claws-ai-results" style="margin-top: 0.5rem; padding: 0.5rem; background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 0.375rem; font-size: 0.75rem; display: none;"></div>
                                    <p style="font-size: 0.625rem; color: #6b7280; margin: 0.25rem 0 0;">JPG, PNG, or WebP. Max 5MB. Upload a photo to enable AI coat analysis.</p>
                                </div>
                            </div>
                            
                            <!-- Notes -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Notes</label>
                                <textarea id="claws-intake-notes" rows="3" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem; resize: vertical; box-sizing: border-box;" placeholder="Any additional notes about this cat or situation..."></textarea>
                            </div>
                            
                            <!-- Form Buttons -->
                            <div style="display: flex; flex-direction: column; gap: 0.75rem; padding-top: 0.5rem;">
                                <div style="display: flex; gap: 0.75rem;">
                                    <button onclick="CLAWSApp.hideIntakeForm()" style="flex: 1; padding: 0.75rem; background: #f3f4f6; color: #374151; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">Cancel</button>
                                    <button onclick="CLAWSApp.saveIntake()" style="flex: 1; padding: 0.75rem; background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer;">Save Intake</button>
                                </div>
                                <button onclick="CLAWSApp.immediateDischarge()" style="width: 100%; padding: 0.75rem; background: linear-gradient(135deg, #f59e0b, #d97706); color: white; border: none; border-radius: 0.5rem; font-weight: 500; cursor: pointer; font-size: 0.875rem;">
                                    ⚡ Immediate Discharge
                                    <br><span style="font-size: 0.75rem; opacity: 0.9;">Save intake & go to discharge form</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            modal.style.display = 'flex';
            this.resetIntakeForm();
            this.populateColonyDropdownForIntake();
            
            // Setup photo preview
            this.setupPhotoPreview('claws-intake-photo', 'claws-intake-photo-preview', 'claws-intake-photo-img');
        },

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

        /**
         * Populate colony dropdown for intake form
         */
        populateColonyDropdownForIntake: function() {
            const dropdown = document.getElementById('claws-intake-colony');
            if (!dropdown) return;
            
            // Clear existing options (except the first "Select colony...")
            while (dropdown.children.length > 1) {
                dropdown.removeChild(dropdown.lastChild);
            }
            
            // Add colonies if available
            if (this.colonies && this.colonies.length > 0) {
                this.colonies.forEach(colony => {
                    const option = document.createElement('option');
                    option.value = colony.id;
                    option.textContent = colony.name;
                    dropdown.appendChild(option);
                });
            }
        },

        /**
         * Setup photo preview functionality
         */
        setupPhotoPreview: function(inputId, previewId, imgId) {
            const input = document.getElementById(inputId);
            const preview = document.getElementById(previewId);
            const img = document.getElementById(imgId);
            const aiButton = document.getElementById('claws-ai-analyze-btn');
            
            if (!input || !preview || !img) return;
            
            input.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        img.src = e.target.result;
                        preview.style.display = 'block';
                        if (aiButton) {
                            aiButton.style.display = 'block';
                        }
                    };
                    reader.readAsDataURL(file);
                }
            });
        },

        /**
         * Handle colony photos change (multiple photos)
         */
        handleColonyPhotosChange: function(input) {
            if (!input.files || input.files.length === 0) {
                return;
            }
            
            // Determine which preview container to use
            const isEditForm = input.id === 'claws-edit-colony-photos';
            const previewContainer = document.getElementById(isEditForm ? 'claws-edit-colony-photos-preview' : 'claws-colony-photos-preview');
            
            if (!previewContainer) {
                return;
            }
            
            // Clear existing previews
            previewContainer.innerHTML = '';
            previewContainer.style.display = 'none';
            
            // Validate and show previews for each file
            const files = Array.from(input.files);
            let validFiles = [];
            
            files.forEach((file, index) => {
                // Validate file type
                if (!file.type.match('image/(jpeg|png|webp)')) {
                    this.showAlert(`File "${file.name}" is not a valid image format. Only JPG, PNG, and WebP are allowed.`, 'error');
                    return;
                }
                
                // Validate file size (5MB max)
                if (file.size > 5 * 1024 * 1024) {
                    this.showAlert(`File "${file.name}" is too large. Maximum size is 5MB.`, 'error');
                    return;
                }
                
                validFiles.push(file);
                
                // Create preview
                const reader = new FileReader();
                reader.onload = (e) => {
                    const previewDiv = document.createElement('div');
                    previewDiv.style.cssText = 'position: relative; border-radius: 0.5rem; overflow: hidden; border: 2px solid #e5e7eb;';
                    
                    previewDiv.innerHTML = `
                        <img src="${e.target.result}" style="width: 100%; height: 100px; object-fit: cover; display: block;" />
                        <button type="button" onclick="this.parentElement.remove(); CLAWSApp.updateColonyPhotosInput();" style="position: absolute; top: 0.25rem; right: 0.25rem; background: rgba(239, 68, 68, 0.9); color: white; border: none; border-radius: 50%; width: 24px; height: 24px; cursor: pointer; font-size: 0.875rem; line-height: 1; display: flex; align-items: center; justify-content: center;">×</button>
                        <div style="position: absolute; bottom: 0; left: 0; right: 0; background: rgba(0, 0, 0, 0.6); color: white; padding: 0.25rem; font-size: 0.625rem; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${file.name}</div>
                    `;
                    
                    previewContainer.appendChild(previewDiv);
                    if (previewContainer.children.length > 0) {
                        previewContainer.style.display = 'grid';
                    }
                };
                reader.readAsDataURL(file);
            });
            
            // Update the input to only include valid files
            if (validFiles.length !== files.length) {
                const dataTransfer = new DataTransfer();
                validFiles.forEach(file => dataTransfer.items.add(file));
                input.files = dataTransfer.files;
            }
        },
        
        /**
         * Update colony photos input after removing a preview
         */
        updateColonyPhotosInput: function() {
            // This function is called when a preview is removed
            // We need to rebuild the file list without the removed file
            const addInput = document.getElementById('claws-colony-photos');
            const editInput = document.getElementById('claws-edit-colony-photos');
            const addPreview = document.getElementById('claws-colony-photos-preview');
            const editPreview = document.getElementById('claws-edit-colony-photos-preview');
            
            // Handle add form
            if (addInput && addPreview) {
                if (addPreview.children.length === 0) {
                    addPreview.style.display = 'none';
                    addInput.value = '';
                } else {
                    // Rebuild file list from remaining previews
                    const dataTransfer = new DataTransfer();
                    const existingFiles = Array.from(addInput.files || []);
                    const remainingPreviews = Array.from(addPreview.children);
                    
                    // Match files to previews (simplified - just keep all files for now)
                    // The browser handles this when we remove from DOM
                }
            }
            
            // Handle edit form
            if (editInput && editPreview) {
                if (editPreview.children.length === 0) {
                    editPreview.style.display = 'none';
                    editInput.value = '';
                }
            }
        },
        
        /**
         * Handle intake photo upload
         */
        handleIntakePhotoUpload: function(input) {
            const file = input.files[0];
            if (!file) return;
            
            // Validate file type
            const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                this.showAlert('Please select a JPG, PNG, or WebP image file.', 'error');
                input.value = '';
                return;
            }
            
            // Validate file size (5MB limit)
            if (file.size > 5 * 1024 * 1024) {
                this.showAlert('Image file must be smaller than 5MB.', 'error');
                input.value = '';
                return;
            }
            
            // Show preview
            const preview = document.getElementById('claws-intake-photo-preview');
            const img = document.getElementById('claws-intake-photo-img');
            const aiButton = document.getElementById('claws-ai-analyze-btn');
            
            if (preview && img) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    img.src = e.target.result;
                    preview.style.display = 'block';
                    if (aiButton) {
                        aiButton.style.display = 'block';
                    }
                };
                reader.readAsDataURL(file);
            }
        },

        /**
         * Handle intake type change (show/hide colony assignment)
         */
        handleIntakeTypeChange: function() {
            const typeSelect = document.getElementById('claws-intake-type');
            const colonyContainer = document.getElementById('claws-colony-assignment-container');
            
            if (!typeSelect || !colonyContainer) return;
            
            if (typeSelect.value === 'Colony Cat') {
                colonyContainer.style.display = 'block';
            } else {
                colonyContainer.style.display = 'none';
            }
        },

        /**
         * Analyze photo with AI
         */
        analyzePhotoWithAI: function() {
            const fileInput = document.getElementById('claws-intake-photo');
            const resultsDiv = document.getElementById('claws-ai-results');
            const aiButton = document.getElementById('claws-ai-analyze-btn');
            
            if (!fileInput.files[0] || !resultsDiv) {
                this.showAlert('Please upload a photo first.', 'error');
                return;
            }
            
            // Show loading state
            if (aiButton) {
                aiButton.textContent = '🤖 Analyzing...';
                aiButton.disabled = true;
            }
            
            // Simulate AI analysis (replace with actual AI integration)
            setTimeout(() => {
                const mockResults = {
                    coat: 'Domestic Short Hair',
                    color: 'Orange tabby with white markings',
                    confidence: 85
                };
                
                resultsDiv.innerHTML = `
                    <div style="font-weight: 600; color: #0369a1; margin-bottom: 0.5rem;">AI Analysis Results (${mockResults.confidence}% confidence):</div>
                    <div style="margin-bottom: 0.25rem;"><strong>Coat:</strong> ${mockResults.coat}</div>
                    <div style="margin-bottom: 0.5rem;"><strong>Color:</strong> ${mockResults.color}</div>
                    <button onclick="CLAWSApp.applyAIResults()" style="padding: 0.25rem 0.5rem; background: #0ea5e9; color: white; border: none; border-radius: 0.25rem; font-size: 0.625rem; cursor: pointer;">Apply to Form</button>
                `;
                resultsDiv.style.display = 'block';
                
                // Reset button
                if (aiButton) {
                    aiButton.textContent = '🤖 AI Analyze Coat & Color';
                    aiButton.disabled = false;
                }
            }, 2000);
        },

        /**
         * Apply AI results to form fields
         */
        applyAIResults: function() {
            const coatSelect = document.getElementById('claws-intake-coat');
            const colorInput = document.getElementById('claws-intake-color');
            
            if (coatSelect) {
                coatSelect.value = 'Domestic Short Hair';
            }
            
            if (colorInput) {
                colorInput.value = 'Orange tabby with white markings';
            }
            
            this.showAlert('AI analysis applied to form fields!', 'success');
        },

        /**
         * Reset intake form
         */
        resetIntakeForm: function() {
            const form = document.getElementById('claws-intake-form');
            if (form) {
                // Reset basic form fields
                const inputs = form.querySelectorAll('input, select, textarea');
                inputs.forEach(input => {
                    if (input.type === 'checkbox') {
                        input.checked = false;
                    } else {
                        input.value = '';
                    }
                });
                
                // Set today's date
                const dateField = document.getElementById('claws-intake-date');
                if (dateField) {
                    dateField.value = new Date().toISOString().split('T')[0];
                }
                
                // Hide AI results and photo preview
                const aiResults = document.getElementById('claws-ai-results');
                const photoPreview = document.getElementById('claws-intake-photo-preview');
                const aiButton = document.getElementById('claws-ai-analyze-btn');
                
                if (aiResults) aiResults.style.display = 'none';
                if (photoPreview) photoPreview.style.display = 'none';
                if (aiButton) aiButton.style.display = 'none';
            }
        },

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

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

        /**
         * Upload multiple colony photos
         */
        uploadColonyPhotos: async function(colonyId, files) {
            if (!files || files.length === 0) {
                return { success: 0, failed: 0 };
            }
            
            const results = { success: 0, failed: 0 };
            const fileArray = Array.from(files);
            
            // Upload each photo sequentially to avoid overwhelming the server
            for (const file of fileArray) {
                // Validate file size (5MB max)
                if (file.size > 5 * 1024 * 1024) {
                    results.failed++;
                    continue;
                }
                
                // Validate file type
                if (!file.type.match('image/(jpeg|png|webp)')) {
                    results.failed++;
                    continue;
                }
                
                const formData = new FormData();
                formData.append('photo', file);
                
                try {
                    const response = await fetch(this.config.apiUrl + 'colony/' + colonyId + '/photo', {
                        method: 'POST',
                        headers: {
                            'X-WP-Nonce': this.config.nonce
                        },
                        body: formData
                    });
                    
                    if (response.ok) {
                        results.success++;
                    } else {
                        results.failed++;
                    }
                } catch (error) {
                    results.failed++;
                }
            }
            
            return results;
        },
        
        /**
         * Upload intake photo
         */
        uploadIntakePhoto: async function(intakeId) {
            const photoInput = document.getElementById('claws-intake-photo');
            if (!photoInput || !photoInput.files || !photoInput.files[0]) {
                return true; // No photo to upload is fine
            }
            
            const formData = new FormData();
            formData.append('photo', photoInput.files[0]);
            formData.append('intake_id', intakeId);
            
            try {
                const response = await fetch(this.config.apiUrl + 'intake/' + intakeId + '/photo', {
                    method: 'POST',
                    headers: {
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: formData
                });
                
                return response.ok;
            } catch (error) {
                return false;
            }
        },

        /**
         * Save intake (original button functionality)
         */
        saveIntake: async function() {
            // Use the standardized data collection method
            const intakeData = this.collectIntakeFormData();
            if (!intakeData) {
                this.showAlert('Please fill in all required fields.', 'error');
                return;
            }
            
            this.showLoading('Saving intake record...');
            
            try {
                const response = await fetch(this.config.apiUrl + 'intake', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce
                    },
                    body: JSON.stringify(intakeData)
                });
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // Upload photo if one was selected
                    const photoResult = await this.uploadIntakePhoto(result.id);
                    if (photoResult === false) {
                        this.showAlert('Intake saved, but photo upload failed. You can add the photo later.', 'warning');
                    } else {
                        this.showAlert('Intake record saved successfully!', 'success');
                    }
                    
                    // Close the modal
                    this.hideIntakeForm();
                    
                    // Reload intake data
                    this.loadIntakeData();
                } else {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
            } catch (error) {
                this.showAlert('Failed to save intake record. Please try again.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Immediate discharge (yellow button)
         */
        immediateDischarge: async function() {
            
            try {
                // Collect intake data first
                const intakeData = this.collectIntakeFormData();
                if (!intakeData) {
                    // Check specific validation failure
                    const type = document.getElementById('claws-intake-type')?.value;
                    if (type === 'Colony Cat' && this.hasColonyAccess()) {
                        const colonyId = document.getElementById('claws-intake-colony')?.value;
                        if (!colonyId) {
                            this.showAlert('Please select a colony assignment for Colony Cat type.', 'error');
                            return;
                        }
                    }
                    this.showAlert('Please fill in all required intake fields first.', 'error');
                    return;
                }
                
                this.showLoading('Saving intake record...');
                
                // Save the intake record first
                const intakeResult = await this.saveIntakeData(intakeData);
                if (!intakeResult.success && !intakeResult.id) {
                    throw new Error('Failed to save intake record');
                }
                
                // Upload photo if one was selected
                if (intakeResult.id) {
                    await this.uploadIntakePhoto(intakeResult.id);
                }
                
                // Close intake modal
                this.hideIntakeForm();
                
                this.showLoading('Opening discharge form...');
                
                // Switch to discharge tab and show discharge form
                this.switchTab('discharge');
                
                // Small delay to let tab switch complete
                setTimeout(() => {
                    this.hideLoading();
                    this.showAlert('Intake saved! Now completing discharge form...', 'success');
                    // Show discharge form with the intake ID and cat name pre-populated
                    if (typeof this.showDischargeForm === 'function') {
                        const catName = intakeData.cat_name || intakeData.name;
                        this.showDischargeForm(intakeResult.id || intakeResult.data?.id, catName);
                        // Extra safety: force hide loading after form is shown
                        setTimeout(() => {
                            this.hideLoading();
                        }, 100);
                    } else {
                        this.showAlert('Discharge form will be implemented next.', 'info');
                    }
                }, 500);
                
                // Reload intake data
                this.loadIntakeData();
                
            } catch (error) {
                this.showAlert('Failed to process immediate discharge. Please try again.', 'error');
                this.hideLoading();
            }
        },

        /**
         * Show discharge form
         */
        showDischargeForm: function(intakeId, catName) {
            
            // Check if modal already exists
            const modal = document.getElementById('claws-discharge-form-modal');
            if (modal) {
                modal.style.display = 'flex';
                this.resetDischargeForm();
                this.populateCatDropdown(catName);
                return;
            } else {
                this.createDischargeFormModal(catName);
            }
        },

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

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

                            <!-- Outcome -->
                            <div>
                                <label style="display: block; font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.5rem;">Outcome</label>
                                <select id="claws-discharge-outcome" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.5rem; font-size: 0.875rem;">
                                    <option value="">Select outcome...</option>
                                    <option value="Adoption">Adoption</option>
                                    <option value="Transfer">Transfer</option>
                                    <option value="Died">Died</option>
                                    <option value="Euthanasia">Euthanasia</option>
                                    <option value="TNR">TNR (Trap, Neuter, Release)</option>
                                    <option value="Returned to Owner">Returned to Owner</option>
                                    <option value="Escaped">Escaped</option>
                                    <option value="Foster to Adopt">Foster to Adopt</option>
                                </select>
                            </div>

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

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

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

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

        /**
         * Populate cat dropdown with active intakes
         */
        populateCatDropdown: function(preSelectedCat) {
            const dropdown = document.getElementById('claws-discharge-cat');
            if (!dropdown) return;
            
            // Clear existing options (keep first placeholder option)
            dropdown.innerHTML = '<option value="">Choose a cat...</option>';
            
            if (this.intakeRecords && this.intakeRecords.length > 0) {
                // Filter to active cats only (not already discharged)
                const activeCats = this.intakeRecords.filter(record => 
                    !record.discharged && (!record.status || record.status === 'active')
                );
                
                activeCats.forEach(record => {
                    const catName = record.cat_name || record.name || 'Unknown Cat';
                    const option = document.createElement('option');
                    option.value = catName;
                    option.textContent = catName;
                    dropdown.appendChild(option);
                });
                
                // Pre-select the specified cat if provided
                if (preSelectedCat) {
                    dropdown.value = preSelectedCat;
                }
                
            } else {
                const option = document.createElement('option');
                option.value = '';
                option.textContent = 'No active cats found';
                option.disabled = true;
                dropdown.appendChild(option);
            }
        },

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

            // Validation
            if (!dischargeData.discharge_date) {
                this.showAlert('Please select a date.', 'error');
                return;
            }
            
            if (!dischargeData.cat_name) {
                this.showAlert('Please select a cat.', 'error');
                return;
            }
            
            if (!dischargeData.outcome) {
                this.showAlert('Please select an outcome.', 'error');
                return;
            }

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

            try {
                const timestamp = new Date().getTime();
                const response = await fetch(this.config.apiUrl + 'discharge', {
                    method: 'POST',
                    credentials: 'include',
                    cache: 'no-cache',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': this.config.nonce,
                        'Cache-Control': 'no-cache, no-store, must-revalidate'
                    },
                    body: JSON.stringify(dischargeData)
                });

                if (response.ok) {
                    const result = await response.json();
                    this.showAlert('Discharge record saved successfully!', 'success');
                    this.hideDischargeForm();
                    
                    // Refresh intake data to show updated status
                    if (typeof this.loadIntakeData === 'function') {
                        this.loadIntakeData();
                    } else if (window.CLAWSApp && typeof window.CLAWSApp.loadIntakeData === 'function') {
                        window.CLAWSApp.loadIntakeData();
                    }
                } else {
                    const error = await response.json();
                    this.showAlert(error.message || 'Failed to save discharge record.', 'error');
                }
            } catch (error) {
                this.showAlert('An error occurred while saving the discharge record.', 'error');
            } finally {
                this.hideLoading();
            }
        },

        /**
         * Show loading indicator
         */
        showLoading: function(message = 'Loading...') {
            const loadingDiv = document.createElement('div');
            loadingDiv.id = 'claws-loading-indicator';
            loadingDiv.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.7);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10001;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            `;
            
            loadingDiv.innerHTML = `
                <div style="background: white; padding: 2rem; border-radius: 1rem; text-align: center; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);">
                    <div style="width: 3rem; height: 3rem; border: 3px solid #e5e7eb; border-top: 3px solid #3b82f6; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 1rem;"></div>
                    <p style="margin: 0; color: #374151; font-weight: 500;">${message}</p>
                </div>
                <style>
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                </style>
            `;
            
            document.body.appendChild(loadingDiv);
        },

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

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

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


    });

})();