(function () {
    'use strict';

    var config = window.PodcastmakerAudioAnalyticsAdmin || {};
    var __ = window.wp && window.wp.i18n ? window.wp.i18n.__ : function (text) { return text; };

    function getQuadrantColor(point, medianPlays, medianCompletion) {
        var highPlays = point.plays >= medianPlays;
        var highCompletion = point.completion >= medianCompletion;

        if (highPlays && highCompletion) {
            return 'rgba(34, 113, 177, 0.85)';
        }
        if (!highPlays && highCompletion) {
            return 'rgba(0, 163, 42, 0.85)';
        }
        if (highPlays && !highCompletion) {
            return 'rgba(219, 166, 23, 0.85)';
        }

        return 'rgba(195, 196, 199, 0.95)';
    }

    function buildTrendChart() {
        var canvas = document.getElementById('podcastmaker-audio-trend-chart');
        if (!canvas || !config.trend || !Array.isArray(config.trend.labels)) {
            return;
        }

        new Chart(canvas.getContext('2d'), {
            type: 'line',
            data: {
                labels: config.trend.labels,
                datasets: [{
                    data: config.trend.values || [],
                    borderColor: '#2271b1',
                    backgroundColor: 'rgba(34, 113, 177, 0.08)',
                    borderWidth: 2,
                    pointRadius: 3,
                    pointHoverRadius: 5,
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return ' ' + context.label + ': ' + context.parsed.y + ' ' + __('plays', 'quikvox-ai');
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            maxTicksLimit: 10,
                            font: {
                                size: 11
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            font: {
                                size: 11
                            }
                        }
                    }
                }
            }
        });
    }

    function buildHourChart() {
        var canvas = document.getElementById('podcastmaker-audio-hour-chart');
        if (!canvas || !config.hours || !Array.isArray(config.hours.labels)) {
            return;
        }

        var peakHours = Array.isArray(config.hours.peakHours) ? config.hours.peakHours : [];
        new Chart(canvas.getContext('2d'), {
            type: 'bar',
            data: {
                labels: config.hours.labels,
                datasets: [{
                    data: config.hours.values || [],
                    backgroundColor: (config.hours.values || []).map(function (_, index) {
                        return peakHours.indexOf(index) !== -1 ? '#2271b1' : 'rgba(34, 113, 177, 0.35)';
                    }),
                    borderRadius: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return ' ' + context.label + ': ' + context.parsed.y + ' ' + __('plays', 'quikvox-ai');
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            maxTicksLimit: 8,
                            font: {
                                size: 10
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            font: {
                                size: 11
                            }
                        }
                    }
                }
            }
        });
    }

    function buildScatterChart() {
        var canvas = document.getElementById('podcastmaker-audio-voice-scatter');
        if (!canvas || !config.voiceScatter || !Array.isArray(config.voiceScatter.points) || !config.voiceScatter.points.length) {
            return;
        }

        var medianPlays = Number(config.voiceScatter.medianPlays || 0);
        var medianCompletion = Number(config.voiceScatter.medianCompletion || 0);
        var labelsToShow = Array.isArray(config.voiceScatter.labelsToShow) ? config.voiceScatter.labelsToShow : [];
        var points = config.voiceScatter.points;

        var quadrantPlugin = {
            id: 'podcastmakerQuadrants',
            afterDraw: function (chart) {
                var area = chart.chartArea;
                var scales = chart.scales;
                if (!area || !scales.x || !scales.y) {
                    return;
                }

                var ctx = chart.ctx;
                var xPixel = scales.x.getPixelForValue(medianPlays);
                var yPixel = scales.y.getPixelForValue(medianCompletion);

                ctx.save();
                ctx.strokeStyle = 'rgba(100, 100, 105, 0.25)';
                ctx.lineWidth = 1;
                ctx.setLineDash([4, 4]);

                ctx.beginPath();
                ctx.moveTo(xPixel, area.top);
                ctx.lineTo(xPixel, area.bottom);
                ctx.stroke();

                ctx.beginPath();
                ctx.moveTo(area.left, yPixel);
                ctx.lineTo(area.right, yPixel);
                ctx.stroke();

                ctx.setLineDash([]);
                ctx.font = '10px sans-serif';
                ctx.fillStyle = 'rgba(100, 100, 105, 0.6)';
                ctx.fillText(__('Top', 'quikvox-ai'), xPixel + 6, area.top + 14);
                ctx.fillText(__('Hidden Gem', 'quikvox-ai'), area.left + 4, area.top + 14);
                ctx.fillText(__('Needs Work', 'quikvox-ai'), xPixel + 6, area.bottom - 6);
                ctx.fillText(__('Low Data', 'quikvox-ai'), area.left + 4, area.bottom - 6);
                ctx.restore();
            }
        };

        var labelPlugin = {
            id: 'podcastmakerVoiceLabels',
            afterDatasetsDraw: function (chart) {
                var dataset = chart.data.datasets[0];
                if (!dataset) {
                    return;
                }

                var ctx = chart.ctx;
                var scales = chart.scales;
                ctx.save();
                ctx.font = '10px sans-serif';
                ctx.textAlign = 'left';
                ctx.textBaseline = 'bottom';

                dataset.data.forEach(function (point, index) {
                    if (labelsToShow.indexOf(point.name) === -1) {
                        return;
                    }

                    var x = scales.x.getPixelForValue(point.x);
                    var y = scales.y.getPixelForValue(point.y);
                    ctx.fillStyle = getQuadrantColor(points[index], medianPlays, medianCompletion);
                    ctx.fillText(point.name, x + 5, y - 2);
                });

                ctx.restore();
            }
        };

        new Chart(canvas.getContext('2d'), {
            type: 'scatter',
            plugins: [quadrantPlugin, labelPlugin],
            data: {
                datasets: [{
                    data: points.map(function (point) {
                        return {
                            x: point.plays,
                            y: point.completion,
                            name: point.name,
                            avgPlayRate: point.avgPlayRate
                        };
                    }),
                    backgroundColor: points.map(function (point) {
                        return getQuadrantColor(point, medianPlays, medianCompletion);
                    }),
                    pointRadius: points.map(function (point) {
                        return Math.max(5, Math.sqrt(point.plays) * 0.9);
                    }),
                    pointHoverRadius: points.map(function (point) {
                        return Math.max(7, Math.sqrt(point.plays) * 1.1);
                    })
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                var raw = context.raw;
                                return [
                                    ' ' + raw.name,
                                    ' ' + __('Plays', 'quikvox-ai') + ': ' + raw.x,
                                    ' ' + __('Completion (%)', 'quikvox-ai') + ': ' + raw.y + '%',
                                    ' ' + __('Avg. Play Rate', 'quikvox-ai') + ': ' + raw.avgPlayRate + '%'
                                ];
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: __('Plays', 'quikvox-ai'),
                            font: {
                                size: 11
                            }
                        },
                        ticks: {
                            font: {
                                size: 10
                            }
                        }
                    },
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: __('Completion (%)', 'quikvox-ai'),
                            font: {
                                size: 11
                            }
                        },
                        ticks: {
                            callback: function (value) {
                                return value + '%';
                            },
                            font: {
                                size: 10
                            }
                        }
                    }
                }
            }
        });
    }

    if (typeof window.Chart !== 'function') {
        return;
    }

    buildTrendChart();
    buildHourChart();
    buildScatterChart();
})();
