/**
 * CLAWS Charts Module
 * Handles all chart functionality including pie charts, line charts, and data visualizations
 */

(function() {
    'use strict';

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

        /**
         * Update pie chart
         */
        updatePieChart: function() {
            const canvas = document.getElementById('claws-colony-pie-chart');
            
            if (!canvas) {
                this.createPieChartContainer();
                return;
            }
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart if it exists
            if (this.colonyChart) {
                this.colonyChart.destroy();
                this.colonyChart = null;
            }
            
            // Prepare data for pie chart
            const chartData = [];
            const labels = [];
            const backgroundColors = [];
            
            this.colonies.forEach((colony, index) => {
                if (colony.cats && colony.cats > 0) {
                    chartData.push(colony.cats);
                    labels.push(colony.name);
                    backgroundColors.push(this.getChartColor(index));
                }
            });
            
            if (chartData.length === 0) {
                // No data to display
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No colony data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            try {
                // Create new pie chart
                this.colonyChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: chartData,
                            backgroundColor: backgroundColors,
                            borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                            borderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
                
                // Force chart to resize to container after creation
                // Wait 500ms to ensure container is visible and has dimensions
                setTimeout(() => {
                    if (this.colonyChart) {
                        this.colonyChart.resize();
                    }
                }, 500);
                
            } catch (error) {
                (window.CLAWSApp&&window.CLAWSApp._debugMode)&&console.error('Chart creation failed:', error);
            }
            
            // Update legend
            this.updateChartLegend(chartData);
        },

        /**
         * Create pie chart container
         */
        createPieChartContainer: function() {
            const colonyContent = document.getElementById(CLAWS_CONSTANTS.ELEMENT_IDS.COLONY_CONTENT);
            if (!colonyContent) return;
            
            const pieChartHTML = `
                <div style="background: white; border-radius: 1rem; padding: 1.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; margin: 1rem;">
                    <h3 style="font-weight: 600; color: #1f2937; margin: 0 0 1rem; font-size: 0.875rem; text-align: center;">Colony Size Distribution</h3>
                    <div style="position: relative; height: 250px; display: flex; align-items: center; justify-content: center;">
                        <canvas id="claws-colony-pie-chart" width="400" height="250"></canvas>
                    </div>
                    <div id="claws-chart-legend" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 0.5rem; margin-top: 1rem;"></div>
                </div>
            `;
            
            // Check if chart already exists
            const existingPieChart = document.getElementById('claws-colony-pie-chart');
            if (!existingPieChart) {
                colonyContent.insertAdjacentHTML('beforeend', pieChartHTML);
                
                // Initialize the chart after container is created
                setTimeout(() => this.updatePieChart(), 100);
            }
        },


        /**
         * Update chart legend
         */
        updateChartLegend: function(chartData) {
            const legendContainer = document.getElementById('claws-chart-legend');
            if (!legendContainer) return;
            
            legendContainer.innerHTML = '';
            
            this.colonies.forEach((colony, index) => {
                if (colony.cats && colony.cats > 0) {
                    const legendItem = document.createElement('div');
                    legendItem.style.cssText = `
                        display: flex;
                        align-items: center;
                        gap: 0.5rem;
                        font-size: 0.75rem;
                        color: #374151;
                    `;
                    
                    legendItem.innerHTML = `
                        <div style="width: 12px; height: 12px; background: ${this.getChartColor(index)}; border-radius: 2px;"></div>
                        <span>${colony.name} (${colony.cats})</span>
                    `;
                    
                    legendContainer.appendChild(legendItem);
                }
            });
        },


        /**
         * Update intake charts
         */
        updateIntakeCharts: function() {
            this.updateIntakeTypeChart();
            this.updateIntakeGenderChart();
            this.updateIntakeAgeChart();
        },

        /**
         * Update intake type chart
         */
        updateIntakeTypeChart: function() {
            const canvas = document.getElementById('claws-intake-type-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.intakeTypeChart) {
                this.intakeTypeChart.destroy();
                this.intakeTypeChart = null;
            }
            
            // Prepare data
            const typeCounts = {};
            this.intakeRecords.forEach(record => {
                const type = record.intakeType || 'Unknown';
                typeCounts[type] = (typeCounts[type] || 0) + 1;
            });
            
            const labels = Object.keys(typeCounts);
            const data = Object.values(typeCounts);
            const colors = labels.map((_, index) => this.getChartColor(index));
            
            if (data.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No intake data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            // Create chart
            this.intakeTypeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update intake gender chart
         */
        updateIntakeGenderChart: function() {
            const canvas = document.getElementById('claws-intake-gender-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.intakeGenderChart) {
                this.intakeGenderChart.destroy();
                this.intakeGenderChart = null;
            }
            
            // Prepare data
            const genderCounts = {};
            this.intakeRecords.forEach(record => {
                const gender = record.gender || 'Unknown';
                genderCounts[gender] = (genderCounts[gender] || 0) + 1;
            });
            
            const labels = Object.keys(genderCounts);
            const data = Object.values(genderCounts);
            const colors = labels.map((_, index) => this.getChartColor(index));
            
            if (data.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No intake data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            // Create chart
            this.intakeGenderChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update intake age chart
         */
        updateIntakeAgeChart: function() {
            const canvas = document.getElementById('claws-intake-age-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.intakeAgeChart) {
                this.intakeAgeChart.destroy();
                this.intakeAgeChart = null;
            }
            
            // Prepare data
            const ageCounts = {};
            this.intakeRecords.forEach(record => {
                const age = record.age || 'Unknown';
                ageCounts[age] = (ageCounts[age] || 0) + 1;
            });
            
            const labels = Object.keys(ageCounts);
            const data = Object.values(ageCounts);
            const colors = labels.map((_, index) => this.getChartColor(index));
            
            if (data.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No intake data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            // Create chart
            this.intakeAgeChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update discharge charts
         */
        updateDischargeCharts: function() {
            this.updateDischargeOutcomeChart();
            this.updateMyDischargeGenderChart();
            this.updateMyDischargeOutcomeChart();
            this.updateMyDischargeAgeChart();
            this.updateMyDischargeTypeChart();
            this.updateAllDischargeGenderChart();
            this.updateAllDischargeOutcomeChart();
            this.updateAllDischargeAgeChart();
            this.updateAllDischargeTypeChart();
        },

        /**
         * Update discharge outcome chart
         */
        updateDischargeOutcomeChart: function() {
            const canvas = document.getElementById('claws-discharge-outcome-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.dischargeOutcomeChart) {
                this.dischargeOutcomeChart.destroy();
                this.dischargeOutcomeChart = null;
            }
            
            // Prepare data
            const outcomeCounts = {};
            this.dischargeRecords.forEach(record => {
                const outcome = record.dischargeType || 'Unknown';
                outcomeCounts[outcome] = (outcomeCounts[outcome] || 0) + 1;
            });
            
            const labels = Object.keys(outcomeCounts);
            const data = Object.values(outcomeCounts);
            const colors = labels.map((_, index) => this.getChartColor(index));
            
            if (data.length === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No discharge data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            // Create chart
            this.dischargeOutcomeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update My Discharge Gender Chart
         */
        updateMyDischargeGenderChart: function() {
            const canvas = document.getElementById('claws-my-discharge-gender-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.myDischargeGenderChart) {
                this.myDischargeGenderChart.destroy();
                this.myDischargeGenderChart = null;
            }
            
            // Get user's discharges only
            const myDischarges = this.dischargeRecords.filter(record => 
                record.author_id == clawsData.userId || record.user_id == clawsData.userId
            );
            
            // Count by gender - cross-reference with intake records for gender data
            const genderCounts = {
                'Male': 0,
                'Female': 0,
                'Unknown': 0
            };
            
            myDischarges.forEach(record => {
                let gender = 'Unknown';
                
                // Find corresponding intake record by cat name
                const catName = (record.cat_name || '').toLowerCase().trim();
                if (catName && this.intakeRecords) {
                    const intakeRecord = this.intakeRecords.find(intake => 
                        (intake.cat_name || intake.name || '').toLowerCase().trim() === catName
                    );
                    if (intakeRecord) {
                        gender = intakeRecord.gender || 'Unknown';
                    }
                }
                
                if (gender in genderCounts) {
                    genderCounts[gender]++;
                } else {
                    genderCounts['Unknown']++;
                }
            });
            
            const labels = Object.keys(genderCounts).filter(key => genderCounts[key] > 0);
            const data = labels.map(key => genderCounts[key]);
            const colors = ['#3b82f6', '#ec4899', '#6b7280']; // Blue for male, pink for female, gray for unknown
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.myDischargeGenderChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update My Discharge Outcome Chart
         */
        updateMyDischargeOutcomeChart: function() {
            const canvas = document.getElementById('claws-my-discharge-outcome-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.myDischargeOutcomeChart) {
                this.myDischargeOutcomeChart.destroy();
                this.myDischargeOutcomeChart = null;
            }
            
            // Get user's discharges only
            const myDischarges = this.dischargeRecords.filter(record => 
                record.author_id == clawsData.userId || record.user_id == clawsData.userId
            );
            
            // Count by outcome
            const outcomeCounts = {};
            myDischarges.forEach(record => {
                const outcome = record.outcome || 'Unknown';
                outcomeCounts[outcome] = (outcomeCounts[outcome] || 0) + 1;
            });
            
            const labels = Object.keys(outcomeCounts);
            const data = Object.values(outcomeCounts);
            const colors = labels.map((_, index) => this.getChartColor(index));
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.myDischargeOutcomeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update All Discharge Gender Chart (Authors+ only)
         */
        updateAllDischargeGenderChart: function() {
            const canvas = document.getElementById('claws-all-discharge-gender-chart');
            if (!canvas) return; // Canvas won't exist for non-privileged users
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.allDischargeGenderChart) {
                this.allDischargeGenderChart.destroy();
                this.allDischargeGenderChart = null;
            }
            
            // Count by gender for ALL discharges - cross-reference with intake records
            const genderCounts = {
                'Male': 0,
                'Female': 0,
                'Unknown': 0
            };
            
            this.dischargeRecords.forEach(record => {
                let gender = 'Unknown';
                
                // Find corresponding intake record by cat name
                const catName = (record.cat_name || '').toLowerCase().trim();
                if (catName && this.intakeRecords) {
                    const intakeRecord = this.intakeRecords.find(intake => 
                        (intake.cat_name || intake.name || '').toLowerCase().trim() === catName
                    );
                    if (intakeRecord) {
                        gender = intakeRecord.gender || 'Unknown';
                    }
                }
                
                if (gender in genderCounts) {
                    genderCounts[gender]++;
                } else {
                    genderCounts['Unknown']++;
                }
            });
            
            const labels = Object.keys(genderCounts).filter(key => genderCounts[key] > 0);
            const data = labels.map(key => genderCounts[key]);
            const colors = ['#3b82f6', '#ec4899', '#6b7280']; // Blue for male, pink for female, gray for unknown
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.allDischargeGenderChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update All Discharge Outcome Chart (Authors+ only)
         */
        updateAllDischargeOutcomeChart: function() {
            const canvas = document.getElementById('claws-all-discharge-outcome-chart');
            if (!canvas) return; // Canvas won't exist for non-privileged users
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.allDischargeOutcomeChart) {
                this.allDischargeOutcomeChart.destroy();
                this.allDischargeOutcomeChart = null;
            }
            
            // Count by outcome for ALL discharges
            const outcomeCounts = {};
            this.dischargeRecords.forEach(record => {
                const outcome = record.outcome || 'Unknown';
                outcomeCounts[outcome] = (outcomeCounts[outcome] || 0) + 1;
            });
            
            const labels = Object.keys(outcomeCounts);
            const data = Object.values(outcomeCounts);
            const colors = labels.map((_, index) => this.getChartColor(index));
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.allDischargeOutcomeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update My Discharge Age Chart
         */
        updateMyDischargeAgeChart: function() {
            const canvas = document.getElementById('claws-my-discharge-age-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.myDischargeAgeChart) {
                this.myDischargeAgeChart.destroy();
                this.myDischargeAgeChart = null;
            }
            
            // Get user's discharges only
            const myDischarges = this.dischargeRecords.filter(record => 
                record.author_id == clawsData.userId || record.user_id == clawsData.userId
            );
            
            // Count by age - cross-reference with intake records for age data
            const ageCounts = {
                'Newborn (0-8 weeks)': 0,
                'Kitten (2-5 months)': 0,
                'Young Adult (6 months-2 years)': 0,
                'Adult (2-8 years)': 0,
                'Senior (8+ years)': 0,
                'Unknown': 0
            };
            
            myDischarges.forEach(record => {
                let age = 'Unknown';
                
                // Find corresponding intake record by cat name
                const catName = (record.cat_name || '').toLowerCase().trim();
                if (catName && this.intakeRecords) {
                    const intakeRecord = this.intakeRecords.find(intake => 
                        (intake.cat_name || intake.name || '').toLowerCase().trim() === catName
                    );
                    if (intakeRecord) {
                        age = intakeRecord.age || 'Unknown';
                    }
                }
                
                if (age in ageCounts) {
                    ageCounts[age]++;
                } else {
                    ageCounts['Unknown']++;
                }
            });
            
            const labels = Object.keys(ageCounts).filter(key => ageCounts[key] > 0);
            const data = labels.map(key => ageCounts[key]);
            const colors = ['#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ef4444', '#6b7280'];
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.myDischargeAgeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels.map(label => label.replace(/\(.*\)/, '').trim()), // Shorten labels for display
                    datasets: [{
                        data: data,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update My Discharge Type Chart
         */
        updateMyDischargeTypeChart: function() {
            const canvas = document.getElementById('claws-my-discharge-type-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.myDischargeTypeChart) {
                this.myDischargeTypeChart.destroy();
                this.myDischargeTypeChart = null;
            }
            
            // Get user's discharges only
            const myDischarges = this.dischargeRecords.filter(record => 
                record.author_id == clawsData.userId || record.user_id == clawsData.userId
            );
            
            // Count by type - cross-reference with intake records for type data
            const typeCounts = {
                'Stray': 0,
                'Semi-feral': 0,
                'Feral': 0,
                'Friendly/Socialized': 0,
                'Unknown': 0
            };
            
            myDischarges.forEach(record => {
                let type = 'Unknown';
                
                // Find corresponding intake record by cat name
                const catName = (record.cat_name || '').toLowerCase().trim();
                if (catName && this.intakeRecords) {
                    const intakeRecord = this.intakeRecords.find(intake => 
                        (intake.cat_name || intake.name || '').toLowerCase().trim() === catName
                    );
                    if (intakeRecord) {
                        type = intakeRecord.type || 'Unknown';
                    }
                }
                
                if (type in typeCounts) {
                    typeCounts[type]++;
                } else {
                    typeCounts['Unknown']++;
                }
            });
            
            const labels = Object.keys(typeCounts).filter(key => typeCounts[key] > 0);
            const data = labels.map(key => typeCounts[key]);
            const colors = ['#f59e0b', '#10b981', '#ef4444', '#3b82f6', '#6b7280'];
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.myDischargeTypeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update All Discharge Age Chart (Admin only)
         */
        updateAllDischargeAgeChart: function() {
            const canvas = document.getElementById('claws-all-discharge-age-chart');
            if (!canvas) return; // Canvas won't exist for non-privileged users
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.allDischargeAgeChart) {
                this.allDischargeAgeChart.destroy();
                this.allDischargeAgeChart = null;
            }
            
            // Use all discharge records
            const allDischarges = this.dischargeRecords;
            
            // Count by age - cross-reference with intake records for age data
            const ageCounts = {
                'Newborn (0-8 weeks)': 0,
                'Kitten (2-5 months)': 0,
                'Young Adult (6 months-2 years)': 0,
                'Adult (2-8 years)': 0,
                'Senior (8+ years)': 0,
                'Unknown': 0
            };
            
            allDischarges.forEach(record => {
                let age = 'Unknown';
                
                // Find corresponding intake record by cat name
                const catName = (record.cat_name || '').toLowerCase().trim();
                if (catName && this.intakeRecords) {
                    const intakeRecord = this.intakeRecords.find(intake => 
                        (intake.cat_name || intake.name || '').toLowerCase().trim() === catName
                    );
                    if (intakeRecord) {
                        age = intakeRecord.age || 'Unknown';
                    }
                }
                
                if (age in ageCounts) {
                    ageCounts[age]++;
                } else {
                    ageCounts['Unknown']++;
                }
            });
            
            const labels = Object.keys(ageCounts).filter(key => ageCounts[key] > 0);
            const data = labels.map(key => ageCounts[key]);
            const colors = ['#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ef4444', '#6b7280'];
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.allDischargeAgeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels.map(label => label.replace(/\(.*\)/, '').trim()), // Shorten labels for display
                    datasets: [{
                        data: data,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Update All Discharge Type Chart (Admin only)
         */
        updateAllDischargeTypeChart: function() {
            const canvas = document.getElementById('claws-all-discharge-type-chart');
            if (!canvas) return; // Canvas won't exist for non-privileged users
            
            const ctx = canvas.getContext('2d');
            
            // Destroy existing chart
            if (this.allDischargeTypeChart) {
                this.allDischargeTypeChart.destroy();
                this.allDischargeTypeChart = null;
            }
            
            // Use all discharge records
            const allDischarges = this.dischargeRecords;
            
            // Count by type - cross-reference with intake records for type data
            const typeCounts = {
                'Stray': 0,
                'Semi-feral': 0,
                'Feral': 0,
                'Friendly/Socialized': 0,
                'Unknown': 0
            };
            
            allDischarges.forEach(record => {
                let type = 'Unknown';
                
                // Find corresponding intake record by cat name
                const catName = (record.cat_name || '').toLowerCase().trim();
                if (catName && this.intakeRecords) {
                    const intakeRecord = this.intakeRecords.find(intake => 
                        (intake.cat_name || intake.name || '').toLowerCase().trim() === catName
                    );
                    if (intakeRecord) {
                        type = intakeRecord.type || 'Unknown';
                    }
                }
                
                if (type in typeCounts) {
                    typeCounts[type]++;
                } else {
                    typeCounts['Unknown']++;
                }
            });
            
            const labels = Object.keys(typeCounts).filter(key => typeCounts[key] > 0);
            const data = labels.map(key => typeCounts[key]);
            const colors = ['#f59e0b', '#10b981', '#ef4444', '#3b82f6', '#6b7280'];
            
            if (data.length === 0 || data.reduce((a, b) => a + b, 0) === 0) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.font = '14px Arial';
                ctx.fillStyle = CLAWS_CONSTANTS.COLORS.GRAY_600;
                ctx.textAlign = 'center';
                ctx.fillText('No data available', canvas.width / 2, canvas.height / 2);
                return;
            }
            
            this.allDischargeTypeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: CLAWS_CONSTANTS.COLORS.WHITE,
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true
                            }
                        }
                    }
                }
            });
        },

        /**
         * Destroy all charts (cleanup function)
         */
        destroyAllCharts: function() {
            const charts = [
                'colonyChart', 'intakeTypeChart', 
                'intakeGenderChart', 'intakeAgeChart', 'dischargeOutcomeChart',
                'myDischargeGenderChart', 'myDischargeOutcomeChart', 'myDischargeAgeChart', 'myDischargeTypeChart',
                'allDischargeGenderChart', 'allDischargeOutcomeChart', 'allDischargeAgeChart', 'allDischargeTypeChart',
                'neonateChart', 'babyChart', 'feedingChart', 'dailyLogChart', 'neonateWeightChart'
            ];
            
            charts.forEach(chartName => {
                if (this[chartName]) {
                    this[chartName].destroy();
                    this[chartName] = null;
                }
            });
        }

    });

})();