
// console.log('[Dynamic chart JS loaded]');
/**
 * Global Chart.js instance registry to properly manage chart instances
 * This helps ensure we don't have conflicts when charts are reinitialized
 */
window.unlockChartRegistry = window.unlockChartRegistry || {};

/**
 * Global initialization function that can be called when Chart.js is loaded dynamically
 * This ensures charts are initialized even if Chart.js loads after the page
 */
window.unlockChartInit = function () {
    $('.unlock-chart-container').each(function () {
        var $container = $(this);
        var chartId = $container.find('canvas').attr('id');

        if (!chartId || $container.data('initialized')) {
            return;
        }

        // Mark as initialized to prevent duplicate initialization
        $container.data('initialized', true);

        var settings = $container.data('settings');
        if (!settings) {
            return;
        }

        var canvas = document.getElementById(chartId);
        if (!canvas) {
            return;
        }

        // Ensure we destroy any existing chart
        safelyDestroyChart(chartId, canvas);

        // Create chart with proper data structure
        try {
            window.unlockChartRegistry[chartId] = new Chart(canvas, {
                type: settings.type,
                data: {
                    labels: settings.labels,
                    datasets: settings.datasets
                },
                options: settings.options || {}
            });
            console.log('Chart initialized:', chartId);
        } catch (e) {
            console.error('Error creating chart:', e);
        }
    });
};

/**
 * Helper function to safely destroy a chart instance
 * @param {string} chartId - The ID of the chart to destroy
 * @param {HTMLElement} canvasElement - The canvas DOM element
 */
function safelyDestroyChart(chartId, canvasElement) {
    // Method 1: Try to get the chart by canvas element using Chart.js API
    if (typeof Chart !== 'undefined' && typeof Chart.getChart === 'function') {
        try {
            var existingChart = Chart.getChart(canvasElement);
            if (existingChart) {
                existingChart.destroy();
                console.log('Chart destroyed via Chart.getChart');
            }
        } catch (e) {
            console.log('Error using Chart.getChart:', e);
        }
    }

    // Method 2: Check our custom registry
    if (window.unlockChartRegistry && window.unlockChartRegistry[chartId]) {
        try {
            window.unlockChartRegistry[chartId].destroy();
            console.log('Chart destroyed via registry');
        } catch (e) {
            console.log('Error destroying chart from registry:', e);
        }
        delete window.unlockChartRegistry[chartId];
    }

    // Method 3: Last resort - clear any Chart.js internal references to this canvas
    if (typeof Chart !== 'undefined' && Chart.instances) {
        Object.keys(Chart.instances).forEach(function (instanceId) {
            try {
                var instance = Chart.instances[instanceId];
                if (instance && instance.canvas && instance.canvas.id === chartId) {
                    instance.destroy();
                    console.log('Chart destroyed via Chart.instances');
                }
            } catch (e) {
                console.log('Error cleaning up Chart.instances:', e);
            }
        });
    }
}

/**
 * Handles the dynamic chart initialization and updates
 */
var DynamicChartHandler = function ($scope, $) {
    // Find the chart container in this specific widget scope
    var $chartContainer = $scope.find('.unlock-chart-container');
    if ($chartContainer.length === 0) {
        return;
    }

    // Get chart settings and canvas element
    var settings = $chartContainer.data('settings');
    var chartCanvas = $scope.find('canvas');

    // Exit if no canvas or settings found
    if (chartCanvas.length === 0 || !settings) {
        return;
    }

    // Check if we're in Elementor editor mode
    var isEditorMode = typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode;

    // Get canvas ID or create one if it doesn't exist
    var chartId = chartCanvas.attr('id');
    if (!chartId) {
        chartId = 'unlock-chart-' + Math.random().toString(36).substring(2, 10);
        chartCanvas.attr('id', chartId);
    }

    // In editor mode, always allow re-initialization; otherwise check if already initialized
    if (!isEditorMode && $chartContainer.data('initialized')) {
        return;
    }

    // Mark as initialized to prevent duplicate initialization
    $chartContainer.data('initialized', true);

    // Ensure we have a clean canvas by destroying any existing charts
    safelyDestroyChart(chartId, chartCanvas[0]);

    // Create a new canvas element to replace the existing one
    // This is the most reliable way to ensure Chart.js doesn't have any references
    var newCanvas = document.createElement('canvas');
    newCanvas.id = chartId;
    newCanvas.width = chartCanvas[0].width || 400;
    newCanvas.height = chartCanvas[0].height || 300;
    chartCanvas[0].parentNode.replaceChild(newCanvas, chartCanvas[0]);

    // Check if Chart.js is loaded
    if (typeof Chart === 'undefined') {
        console.warn('Chart.js is not loaded yet. Chart will be initialized once Chart.js is available.');
        return;
    }

    // Small delay to ensure DOM is updated
    setTimeout(function () {
        try {
            // Create new chart instance on the fresh canvas
            window.unlockChartRegistry[chartId] = new Chart(newCanvas, {
                type: settings.type,
                data: {
                    labels: settings.labels,
                    datasets: settings.datasets
                },
                options: settings.options || {}
            });
            console.log('Chart initialized in Elementor:', chartId);
        } catch (e) {
            console.error('Error creating chart:', e);
        }
    }, 20);
};

// Handle window resize events to make charts responsive
var resizeTimer;
$(window).on('resize', function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function () {
        if (window.unlockChartRegistry) {
            // Update all registered charts on window resize
            Object.keys(window.unlockChartRegistry).forEach(function (chartId) {
                try {
                    if (window.unlockChartRegistry[chartId] && typeof window.unlockChartRegistry[chartId].resize === 'function') {
                        window.unlockChartRegistry[chartId].resize();
                    }
                } catch (e) {
                    console.log('Error resizing chart:', e);
                }
            });
        }
    }, 250);
});

$(window).on('elementor/frontend/init', function () {
    elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-dynamic-chart.default', DynamicChartHandler);
    
    // Handle editor preview mode
    if (elementorFrontend.isEditMode) {
        // Initialize charts in editor preview when widget is rendered
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function ($scope) {
            var $chartContainers = $scope.find('.unlock-chart-container');
            if ($chartContainers.length) {
                setTimeout(function() {
                    // Find the widget scope for each chart container
                    $chartContainers.each(function() {
                        var $container = $(this);
                        var $widgetScope = $container.closest('.elementor-widget-unlockafe-dynamic-chart');
                        if ($widgetScope.length) {
                            DynamicChartHandler($widgetScope, $);
                        }
                    });
                }, 150);
            }
        });
        
        // Also handle preview refresh
        $(window).on('elementor:preview:loaded', function() {
            setTimeout(function() {
                if (typeof Chart !== 'undefined') {
                    window.unlockChartInit();
                }
            }, 300);
        });
    }
});

// Initialize any charts on the page when document is ready
$(document).ready(function () {
    // Check if Chart.js is loaded
    if (typeof Chart !== 'undefined') {
        window.unlockChartInit();
    } else {
        console.warn('Chart.js not loaded yet. Charts will be initialized when Chart.js loads.');
    }
    
    // Also initialize in editor mode after a delay
    if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
        // Multiple attempts to initialize in editor mode
        var initAttempts = 0;
        var maxAttempts = 10;
        
        var tryInit = function() {
            initAttempts++;
            if (typeof Chart !== 'undefined') {
                window.unlockChartInit();
                // Also manually trigger for each widget
                $('.elementor-widget-unlockafe-dynamic-chart').each(function() {
                    var $scope = $(this);
                    DynamicChartHandler($scope, $);
                });
            } else if (initAttempts < maxAttempts) {
                setTimeout(tryInit, 200);
            }
        };
        
        setTimeout(tryInit, 300);
        setTimeout(tryInit, 600);
        setTimeout(tryInit, 1000);
    }
});

// Additional initialization for editor mode when scripts load late
if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
    // Listen for Chart.js loading
    var chartJsCheck = setInterval(function() {
        if (typeof Chart !== 'undefined') {
            clearInterval(chartJsCheck);
            setTimeout(function() {
                window.unlockChartInit();
                $('.elementor-widget-unlockafe-dynamic-chart').each(function() {
                    var $scope = $(this);
                    DynamicChartHandler($scope, $);
                });
            }, 100);
        }
    }, 100);
    
    // Stop checking after 10 seconds
    setTimeout(function() {
        clearInterval(chartJsCheck);
    }, 10000);
}
