(function () {
	function copyText(value) {
		if (navigator.clipboard && window.isSecureContext) {
			return navigator.clipboard.writeText(value);
		}

		var textarea = document.createElement('textarea');
		textarea.value = value;
		textarea.setAttribute('readonly', '');
		textarea.style.position = 'absolute';
		textarea.style.left = '-9999px';
		document.body.appendChild(textarea);
		textarea.select();

		try {
			document.execCommand('copy');
		} finally {
			document.body.removeChild(textarea);
		}

		return Promise.resolve();
	}

	function setBackgroundStatus(message, type) {
		var status = document.getElementById('maca_hold_background_status');
		if (!status) {
			return;
		}

		status.textContent = message || '';
		status.classList.remove('is-error', 'is-success', 'is-pending');

		if (type) {
			status.classList.add('is-' + type);
		}
	}

	function saveBackground(value) {
		if (!window.macaHoldAdmin || !window.macaHoldAdmin.ajaxUrl) {
			return Promise.resolve();
		}

		setBackgroundStatus(window.macaHoldAdmin.backgroundSaving, 'pending');

		var body = new URLSearchParams();
		body.set('action', 'maca_hold_set_background');
		body.set('nonce', window.macaHoldAdmin.nonce);
		body.set('background_image', value);

		return fetch(window.macaHoldAdmin.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			},
			body: body.toString(),
		})
			.then(function (response) {
				return response.json();
			})
			.then(function (payload) {
				if (!payload || !payload.success) {
					throw new Error((payload && payload.data && payload.data.message) || window.macaHoldAdmin.backgroundSaveError);
				}

				setBackgroundStatus(payload.data.message || window.macaHoldAdmin.backgroundSaved, 'success');
			})
			.catch(function () {
				setBackgroundStatus(window.macaHoldAdmin.backgroundSaveError, 'error');
			});
	}

	document.addEventListener('change', function (event) {
		var input = event.target;

		if (!input || input.name !== 'background_image' || input.type !== 'radio') {
			return;
		}

		saveBackground(input.value);
	});

	document.addEventListener('click', function (event) {
		var button = event.target.closest('[data-copy-target]');
		if (!button) {
			return;
		}

		var targetId = button.getAttribute('data-copy-target');
		var field = document.getElementById(targetId);
		if (!field) {
			return;
		}

		copyText(field.value).then(function () {
			var original = button.textContent;
			var copiedLabel = window.macaHoldAdmin.copiedLabel;
			button.textContent = copiedLabel;
			window.setTimeout(function () {
				button.textContent = original;
			}, 1500);
		});
	});

	function initLinkRows() {
		var body = document.getElementById('maca_hold_links_body');
		var addButton = document.getElementById('maca_hold_add_link');
		var template = document.getElementById('maca_hold_link_row_template');

		if (!body || !addButton || !template) {
			return;
		}

		var maxLinks = parseInt(window.macaHoldAdmin && window.macaHoldAdmin.maxLinks, 10) || 5;

		function getRows() {
			return body.querySelectorAll('.maca-hold-link-row');
		}

		function reindexLinkRows() {
			var rows = getRows();

			rows.forEach(function (row, index) {
				var label = row.querySelector('input[type="text"]');
				var url = row.querySelector('input[type="url"]');
				var newTab = row.querySelector('input[type="checkbox"]');
				var removeButton = row.querySelector('.maca-hold-remove-link');

				if (label) {
					label.name = 'links[' + index + '][label]';
				}

				if (url) {
					url.name = 'links[' + index + '][url]';
				}

				if (newTab) {
					newTab.name = 'links[' + index + '][new_tab]';
				}

				if (removeButton) {
					removeButton.hidden = rows.length <= 1;
				}
			});

			addButton.disabled = rows.length >= maxLinks;
		}

		addButton.addEventListener('click', function () {
			if (getRows().length >= maxLinks) {
				return;
			}

			var row = template.content.firstElementChild.cloneNode(true);
			body.appendChild(row);
			reindexLinkRows();

			var label = row.querySelector('input[type="text"]');
			if (label) {
				label.focus();
			}
		});

		body.addEventListener('click', function (event) {
			var removeButton = event.target.closest('.maca-hold-remove-link');
			if (!removeButton || removeButton.hidden) {
				return;
			}

			var row = removeButton.closest('.maca-hold-link-row');
			if (!row || getRows().length <= 1) {
				return;
			}

			row.remove();
			reindexLinkRows();
		});

		reindexLinkRows();
	}

	initLinkRows();

	function setMaintenanceFeedback(message, type) {
		var feedback = document.getElementById('maca_hold_maintenance_toggle_feedback');
		if (!feedback) {
			return;
		}

		if (!message) {
			feedback.hidden = true;
			feedback.textContent = '';
			feedback.classList.remove('is-success', 'is-error');
			return;
		}

		feedback.hidden = false;
		feedback.textContent = message;
		feedback.classList.remove('is-success', 'is-error');

		if (type) {
			feedback.classList.add('is-' + type);
		}
	}

	function updateMaintenanceToggleUi(enabled, statusText) {
		var card = document.getElementById('maca_hold_maintenance_toggle_card');
		var status = document.getElementById('maca_hold_maintenance_toggle_status');
		var hiddenField = document.getElementById('maca_hold_enabled_field');

		if (card) {
			card.classList.toggle('is-active', !!enabled);
			card.classList.toggle('is-inactive', !enabled);
		}

		if (status && statusText) {
			status.textContent = statusText;
		}

		if (hiddenField) {
			hiddenField.value = enabled ? '1' : '0';
		}
	}

	function updateMaintenanceToggleCardState(isActive, statusText) {
		var card = document.getElementById('maca_hold_maintenance_toggle_card');
		var status = document.getElementById('maca_hold_maintenance_toggle_status');

		if (card) {
			card.classList.toggle('is-active', !!isActive);
			card.classList.toggle('is-inactive', !isActive);
		}

		if (status && statusText) {
			status.textContent = statusText;
		}
	}

	function updateAdminBarLamp(maintenanceVisible, statusText) {
		var node = document.getElementById('wp-admin-bar-maca-hold-status');
		if (!node) {
			return;
		}

		var lamp = node.querySelector('.maca-hold-lamp');
		var state = node.querySelector('.maca-hold-admin-bar-state');
		var link = node.querySelector('.ab-item');

		if (lamp) {
			lamp.classList.remove('maca-hold-lamp--on', 'maca-hold-lamp--off');
			lamp.classList.add(maintenanceVisible ? 'maca-hold-lamp--on' : 'maca-hold-lamp--off');
		}

		if (state && statusText) {
			state.textContent = statusText;
		}

		node.classList.remove('maca-hold-admin-bar-active', 'maca-hold-admin-bar-inactive');
		node.classList.add(maintenanceVisible ? 'maca-hold-admin-bar-active' : 'maca-hold-admin-bar-inactive');

		if (link && statusText) {
			link.setAttribute('title', statusText);
		}
	}

	function initMaintenanceSwitch() {
		var toggle = document.getElementById('maca_hold_maintenance_switch');
		if (!toggle || !window.macaHoldAdmin || !window.macaHoldAdmin.ajaxUrl) {
			return;
		}

		var card = document.getElementById('maca_hold_maintenance_toggle_card');
		var scheduleControlled = card && card.getAttribute('data-schedule-controlled') === '1';

		if (scheduleControlled) {
			return;
		}

		toggle.addEventListener('change', function () {
			var turningOn = toggle.checked;
			var confirmMessages = window.macaHoldAdmin.toggleConfirm || {};
			var confirmMessage = turningOn ? confirmMessages.enable : confirmMessages.disable;

			if (!confirmMessage) {
				confirmMessage = turningOn
					? 'Activate maintenance mode?'
					: 'Deactivate maintenance mode?';
			}

			if (!window.confirm(confirmMessage)) {
				toggle.checked = !turningOn;
				return;
			}

			toggle.disabled = true;
			setMaintenanceFeedback('', '');

			var body = new URLSearchParams();
			body.set('action', 'maca_hold_toggle_maintenance');
			body.set('nonce', window.macaHoldAdmin.nonce);
			body.set('enabled', turningOn ? '1' : '0');

			fetch(window.macaHoldAdmin.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				},
				body: body.toString(),
			})
				.then(function (response) {
					return response.json();
				})
				.then(function (payload) {
					if (!payload || !payload.success) {
						throw new Error(
							(payload && payload.data && payload.data.message) || window.macaHoldAdmin.toggleError
						);
					}

					var data = payload.data || {};
					var enabled = typeof data.enabled === 'boolean' ? data.enabled : !!data.is_active;
					var maintenanceVisible = typeof data.maintenance_visible === 'boolean'
						? data.maintenance_visible
						: !!data.is_active;
					toggle.checked = enabled;
					updateMaintenanceToggleUi(enabled, '');
					updateMaintenanceToggleCardState(maintenanceVisible, data.status_text || '');
					updateAdminBarLamp(
						maintenanceVisible,
						data.admin_bar_status || (maintenanceVisible
							? (window.macaHoldAdmin.maintenanceActiveLabel || 'Maintenance active')
							: (window.macaHoldAdmin.sitePublicLabel || 'Site public'))
					);
					setMaintenanceFeedback(data.message || '', 'success');
				})
				.catch(function (error) {
					toggle.checked = !turningOn;
					setMaintenanceFeedback(
						(error && error.message) || window.macaHoldAdmin.toggleError,
						'error'
					);
				})
				.finally(function () {
					toggle.disabled = false;
				});
		});
	}

	initMaintenanceSwitch();
}());
