(function ($) {
    'use strict';

    const SifencyCharts = function ($scope, $) {
        const $canvas = $scope.find('.sifency-chart-canvas');
        if (!$canvas.length) return;

        let settings = {};
        try {
            const raw = $canvas.data('chart-settings');
            if (raw) settings = raw;
        } catch (e) { console.error('Chart Config Error', e); return; }

        const ctx = $canvas[0].getContext('2d');
        const primaryColor = settings.colors[0];
        const secondaryColor = settings.colors[1];


        async function getData() {
            if (settings.source === 'manual') {
                return settings.manual_data;
            } else if (settings.source === 'csv' || settings.source === 'gsheet') {
                try {
                    const response = await fetch(settings.url);
                    const text = await response.text();
                    return parseCSV(text);
                } catch (e) { console.error('CSV Fetch Error', e); return null; }
            } else if (settings.source === 'json') {
                try {
                    const response = await fetch(settings.url);
                    return await response.json();
                } catch (e) { return null; }
            }
        }

        function parseCSV(csv) {
            const lines = csv.split('\n');
            const labels = [];
            const data = [];
            lines.forEach((line, index) => {
                // if(index === 0) return;
                const parts = line.split(',');
                if (parts.length >= 2) {
                    labels.push(parts[0]);
                    data.push(parseFloat(parts[1]));
                }
            });
            return {
                labels: labels,
                datasets: [{ label: 'Data', data: data }]
            };
        }


        getData().then(chartData => {
            if (!chartData) return;

            let bgColors = chartData.datasets[0].backgroundColor || primaryColor;
            let borderColors = primaryColor;
            let borderWidth = 2;

            if (settings.style === 'gradient') {
                const gradient = ctx.createLinearGradient(0, 0, 0, 400);
                gradient.addColorStop(0, primaryColor);
                gradient.addColorStop(1, secondaryColor); // Fade out or secondary
                bgColors = gradient;
                if (settings.type === 'line' && settings.fill) {
                    const fillGrad = ctx.createLinearGradient(0, 0, 0, 400);
                    fillGrad.addColorStop(0, hexToRgba(primaryColor, 0.5));
                    fillGrad.addColorStop(1, hexToRgba(primaryColor, 0));
                    bgColors = fillGrad;
                }
            }

            if (settings.style === 'neon') {
                borderWidth = 3;
                Chart.defaults.color = '#eee';
                Chart.defaults.borderColor = '#333';
            }

            if (settings.style === 'glass') {
                bgColors = hexToRgba(primaryColor, 0.4);
                borderColors = hexToRgba(primaryColor, 0.8);
            }

            chartData.datasets[0].backgroundColor = bgColors;
            chartData.datasets[0].borderColor = borderColors;
            chartData.datasets[0].borderWidth = borderWidth;
            chartData.datasets[0].fill = settings.fill;
            chartData.datasets[0].tension = settings.tension;

            if (['pie', 'doughnut', 'polarArea'].includes(settings.type) && !Array.isArray(bgColors)) {
                const count = chartData.labels.length;
                const autoColors = [];
                for (let i = 0; i < count; i++) {
                    autoColors.push(i % 2 === 0 ? primaryColor : secondaryColor);
                }
                if (settings.source !== 'manual') chartData.datasets[0].backgroundColor = autoColors;
            }

            new Chart(ctx, {
                type: settings.type,
                data: chartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: { duration: settings.duration },
                    plugins: {
                        legend: { display: settings.legend },
                    },
                    scales: {
                        x: { display: settings.grid && !['pie', 'doughnut', 'polarArea'].includes(settings.type) },
                        y: { display: settings.grid && !['pie', 'doughnut', 'polarArea'].includes(settings.type), beginAtZero: true }
                    }
                }
            });
        });

        function hexToRgba(hex, alpha) {
            const r = parseInt(hex.slice(1, 3), 16);
            const g = parseInt(hex.slice(3, 5), 16);
            const b = parseInt(hex.slice(5, 7), 16);
            return `rgba(${r}, ${g}, ${b}, ${alpha})`;
        }
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-advanced-charts.default', SifencyCharts);
    });

})(jQuery);