(function (window, document) {
	'use strict';

	function getConfig(header) {
		var globalConfig = window.titaniumSuiteHeaderConfig || {};

		return {
			storageKey: header.getAttribute('data-tsh-storage-key') || globalConfig.storageKey || 'titaniumSuiteDarkMode',
			extraDarkClass: header.getAttribute('data-tsh-extra-dark-class') || globalConfig.extraDarkClass || ''
		};
	}

	function readState(storageKey) {
		try {
			return window.localStorage.getItem(storageKey) === '1';
		} catch (error) {
			return false;
		}
	}

	function saveState(storageKey, enabled) {
		try {
			window.localStorage.setItem(storageKey, enabled ? '1' : '0');
		} catch (error) {
		}
	}

	function applyState(enabled, extraDarkClass) {
		document.documentElement.classList.toggle('titanium-suite-admin-dark', enabled);
		if (extraDarkClass) {
			document.documentElement.classList.toggle(extraDarkClass, enabled);
		}
	}

	function syncToggles(storageKey, enabled) {
		var headers = document.querySelectorAll('.titanium-suite-header');

		headers.forEach(function (header) {
			var config = getConfig(header);
			var input = header.querySelector('.titanium-suite-header__dark-input');

			if (input && config.storageKey === storageKey) {
				input.checked = enabled;
			}
		});
	}

	function initializeHeader(header) {
		var input = header.querySelector('.titanium-suite-header__dark-input');
		var config = getConfig(header);
		var enabled;

		if (!input) {
			return;
		}

		enabled = readState(config.storageKey);
		input.checked = enabled;
		applyState(enabled, config.extraDarkClass);

		input.addEventListener('change', function () {
			enabled = input.checked;
			applyState(enabled, config.extraDarkClass);
			saveState(config.storageKey, enabled);
			syncToggles(config.storageKey, enabled);
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		document.querySelectorAll('.titanium-suite-header').forEach(initializeHeader);
	});
}(window, document));
