(function () {
	function applyContrast(isDarkImage) {
		var body = document.body;
		var text = isDarkImage ? '#f8f8f8' : '#171717';
		var accent = isDarkImage ? '#d4e4f8' : '#2f4f75';

		body.classList.remove('maca-hold-contrast-light', 'maca-hold-contrast-dark');
		body.classList.add(isDarkImage ? 'maca-hold-contrast-light' : 'maca-hold-contrast-dark');
		body.style.setProperty('--maca-hold-text', text);
		body.style.setProperty('--maca-hold-accent', accent);
	}

	function detectContrast(imageUrl, callback) {
		var image = new Image();
		image.decoding = 'async';

		image.onload = function () {
			var canvas = document.createElement('canvas');
			var size = 32;
			canvas.width = size;
			canvas.height = size;

			var context = canvas.getContext('2d');
			if (!context) {
				return;
			}

			context.drawImage(image, 0, 0, size, size);
			var pixels = context.getImageData(0, 0, size, size).data;
			var total = 0;
			var count = 0;

			for (var index = 0; index < pixels.length; index += 4) {
				if (pixels[index + 3] < 40) {
					continue;
				}

				total += (0.299 * pixels[index]) + (0.587 * pixels[index + 1]) + (0.114 * pixels[index + 2]);
				count++;
			}

			if (!count) {
				return;
			}

			callback((total / count) < 140);
		};

		image.src = imageUrl;
	}

	var body = document.body;
	if (!body || !body.classList.contains('maca-hold-has-bg-image')) {
		return;
	}

	var imageUrl = body.getAttribute('data-maca-hold-bg-url');
	if (!imageUrl) {
		return;
	}

	detectContrast(imageUrl, applyContrast);
}());
