/* global window */
(function (window) {
	'use strict';

	const app = window.MailDoctorAdminApp;

	if (!app) {
		return;
	}

	app.register(() => {
		const palette = {
			accent: '#2271b1',
			danger: '#d63638',
			success: '#1d7a1d',
			warning: '#8a4b1f',
			muted: '#e0e0e0',
		};

		const targetMap = {
			delivery: {
				canvas: '#mail-doctor-delivery-chart',
				center: '[data-field="deliveryCenter"]',
			},
			queue: {
				canvas: '#mail-doctor-queue-chart',
				center: '[data-field="queueCenter"]',
			},
		};

		function setCenter(key, text) {
			const target = targetMap[key];
			if (!target || !target.center) {
				return;
			}

			const el = document.querySelector(target.center);
			if (el) {
				el.textContent = text || '—';
			}
		}

		function drawDonut(canvas, segments) {
			if (!canvas || !canvas.getContext) return;

			const ctx = canvas.getContext('2d');
			if (!ctx) return;

			const ratio = Math.max(window.devicePixelRatio || 1, 2); // keep min 2 for smooth circle
			const rect = canvas.getBoundingClientRect();
			const measuredSize = rect.width && rect.height ? Math.round(Math.min(rect.width, rect.height)) : 0;

			let size =
				measuredSize ||
				Number(canvas.dataset.baseSize) ||
				Number(canvas.getAttribute('width')) ||
				Number(canvas.getAttribute('height')) ||
				160;

			if (measuredSize && Math.abs(measuredSize - size) > 1) {
				size = measuredSize;
			}

			canvas.dataset.baseSize = String(size);

			// Keep a small padding so the stroke never clips against canvas edges.
			const padding = 2;
			const ringWidth = Math.min(Math.max(size * 0.18, 8), Math.max(size / 2 - padding, 2));
			const radius = Math.max(size / 2 - padding - ringWidth / 2, ringWidth);
			const innerRadius = Math.max(radius - ringWidth, 0);

			canvas.width = Math.round(size * ratio);
			canvas.height = Math.round(size * ratio);
			canvas.style.width = `${size}px`;
			canvas.style.height = `${size}px`;

			// Clear in device pixels
			ctx.setTransform(1, 0, 0, 1, 0, 0);
			ctx.clearRect(0, 0, canvas.width, canvas.height);

			// Draw with correct center (CSS px mapped to device px)
			ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
			ctx.translate(size / 2, size / 2);

			// Optional extra smoothing
			ctx.lineJoin = 'round';
			ctx.lineCap = 'round';

			// Base ring
			ctx.beginPath();
			ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
			ctx.strokeStyle = palette.muted;
			ctx.lineWidth = ringWidth;
			ctx.stroke();

			const total = segments.reduce((sum, s) => sum + Math.max(Number(s.value) || 0, 0), 0);
			if (total <= 0) return;

			const fullCircle = Math.PI * 2;
			const epsilon = 0.001;
			let start = -Math.PI / 2;

			segments.forEach((segment) => {
				const value = Math.max(Number(segment.value) || 0, 0);
				if (value <= 0) return;

				let angle = (value / total) * fullCircle;
				if (angle >= fullCircle) angle = fullCircle - epsilon;

				ctx.beginPath();
				ctx.arc(0, 0, radius, start, start + angle, false);
				ctx.strokeStyle = segment.color || palette.muted;
				ctx.lineWidth = ringWidth;
				ctx.stroke();

				start += angle;
			});
		}

		const chartsService = {
			palette,
			update(key, segments, options) {
				const target = targetMap[key];
				if (!target) {
					return;
				}

				const canvas = document.querySelector(target.canvas);
				const safeSegments = Array.isArray(segments) ? segments : [];
				const centerText = options && options.centerText ? String(options.centerText) : '—';

				drawDonut(canvas, safeSegments);
				setCenter(key, centerText);
			},
		};

		app.provide('charts', chartsService);
		app.registerService('charts', chartsService);
	});
})(window);
