(function (global) {
	'use strict';

	var TASK_ACCENT_PALETTE = [
		'#e11d48',
		'#2563eb',
		'#16a34a',
		'#9333ea',
		'#ea580c',
		'#0891b2',
		'#ca8a04',
		'#db2777',
		'#4f46e5',
		'#059669',
		'#dc2626',
		'#0d9488',
		'#7c3aed',
		'#d97706',
		'#0284c7',
		'#be123c',
		'#65a30d',
		'#c026d3',
		'#0369a1',
		'#b45309',
		'#15803d',
		'#7e22ce',
		'#c2410c',
		'#1d4ed8'
	];

	var weekColorMaps = {};

	function defaultCompare(a, b) {
		return String(a && a.id || '').localeCompare(String(b && b.id || ''));
	}

	function buildColorMapForTasks(tasks, compareFn) {
		var map = {};
		var seen = {};
		var ordered = Array.isArray(tasks) ? tasks.slice() : [];

		ordered.sort(typeof compareFn === 'function' ? compareFn : defaultCompare);

		var colorIndex = 0;

		ordered.forEach(function (task) {
			if (!task || task.id == null || task.id === '' || seen[task.id]) {
				return;
			}

			seen[task.id] = true;
			map[task.id] = colorIndex % TASK_ACCENT_PALETTE.length;
			colorIndex += 1;
		});

		return map;
	}

	function normalizeWeekOffset(weekOffset) {
		var value = parseInt(weekOffset, 10);
		return Number.isFinite(value) ? value : 0;
	}

	function weekMapKey(weekOffset) {
		return String(normalizeWeekOffset(weekOffset));
	}

	function syncWeekTaskMaps(weekTasksByOffset, compareFn) {
		weekColorMaps = {};

		if (!weekTasksByOffset || typeof weekTasksByOffset !== 'object') {
			return weekColorMaps;
		}

		Object.keys(weekTasksByOffset).forEach(function (offsetKey) {
			weekColorMaps[offsetKey] = buildColorMapForTasks(weekTasksByOffset[offsetKey], compareFn);
		});

		return weekColorMaps;
	}

	function getTaskAccentColor(taskId, weekOffset) {
		if (taskId == null || taskId === '') {
			return TASK_ACCENT_PALETTE[0];
		}

		var map = weekColorMaps[weekMapKey(weekOffset)] || {};
		var paletteIndex = map[taskId];

		if (!Number.isFinite(paletteIndex)) {
			return TASK_ACCENT_PALETTE[0];
		}

		return TASK_ACCENT_PALETTE[paletteIndex];
	}

	function applyTaskAccentColor(card, taskId, weekOffset) {
		if (!card) {
			return TASK_ACCENT_PALETTE[0];
		}

		var color = getTaskAccentColor(taskId, weekOffset);
		card.style.setProperty('--task-accent-color', color);
		card.dataset.taskAccent = color;
		return color;
	}

	function applySegmentLinkColor(link, taskId, weekOffset) {
		if (!link) {
			return TASK_ACCENT_PALETTE[0];
		}

		var color = getTaskAccentColor(taskId, weekOffset);
		link.style.setProperty('--segment-link-color', color);
		return color;
	}

	global.LogisticaPlaneacionTaskColors = {
		syncWeekTaskMaps: syncWeekTaskMaps,
		getTaskAccentColor: getTaskAccentColor,
		applyTaskAccentColor: applyTaskAccentColor,
		applySegmentLinkColor: applySegmentLinkColor,
		palette: TASK_ACCENT_PALETTE.slice()
	};
}(window));
