/**
 * TrustLens Chargeback Monitor — trend chart + backfill progress.
 *
 * @since 1.2.1
 */
/* global TrustLensChartTheme */
(function ($) {
	'use strict';

	var config = window.TrustLensChargeback || { trend: [], nonce: '', i18n: {} };

	function formatStatus(template, d) {
		return template
			.replace('%processed', d.processed)
			.replace('%updated', d.updated)
			.replace('%remaining', d.remaining);
	}

	function renderChart() {
		var canvas = document.getElementById('wstl-chargeback-trend');
		if (!canvas || typeof Chart === 'undefined' || typeof TrustLensChartTheme === 'undefined') {
			return;
		}
		var theme  = TrustLensChartTheme;
		var colors = theme.COLORS;
		theme.applyDefaults();
		Chart.register(theme.noDataPlugin);

		var ctx2d  = canvas.getContext('2d');
		var labels = config.trend.map(function (b) { return b.month; });
		var data   = config.trend.map(function (b) { return (b.ratio * 100).toFixed(3); });

		new Chart(ctx2d, {
			type: 'line',
			data: {
				labels: labels,
				datasets: [theme.lineDataset({
					label:    'Chargeback Ratio %',
					data:     data,
					color:    colors.emerald,
					ctx:      ctx2d,
					topAlpha: 0.18
				})]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				plugins: { legend: { display: false } },
				scales: {
					y: {
						beginAtZero: true,
						ticks: { callback: function (v) { return v + '%'; } }
					},
					x: { grid: { display: false } }
				}
			}
		});
	}

	function runBackfill() {
		var $btn      = $('#wstl-chargeback-backfill-start');
		var $progress = $('#wstl-chargeback-backfill-progress');
		$btn.prop('disabled', true);

		function step() {
			$.post(window.ajaxurl, {
				action: 'wstl_chargeback_backfill_step',
				nonce:  config.nonce
			}, function (resp) {
				if (!resp || !resp.success) {
					$progress.text(config.i18n.error || 'Error.');
					$btn.prop('disabled', false);
					return;
				}
				var d = resp.data;
				$progress.text(formatStatus(config.i18n.status || '', d));
				if (d.remaining > 0) {
					step();
				} else {
					$progress.text(config.i18n.complete || 'Complete.');
					$btn.prop('disabled', false);
				}
			}).fail(function () {
				$progress.text(config.i18n.failed || 'Failed.');
				$btn.prop('disabled', false);
			});
		}

		step();
	}

	$(function () {
		renderChart();
		$('#wstl-chargeback-backfill-start').on('click', runBackfill);
	});
}(jQuery));
