/**
 * Apply ready-made Coming Soon & Maintenance page presets to the settings form.
 */
(function () {
	'use strict';

	var SKIP_KEYS = {
		bypass_token: true,
		fetch_secret: true,
		bg_image_id: true,
	};

	var PRESERVE_KEYS = {
		enabled: true,
		use_existing_page: true,
		existing_page_url: true,
		page_title: true,
		logo_id: true,
		logo_url: true,
		logo_source: true,
		subscribe_consent_text: true,
		exclude_urls: true,
		exclude_woocommerce: true,
		allowed_roles: true,
		allowed_user_ids: true,
	};

	function getRoot(fromEl) {
		return (fromEl && fromEl.closest('.wpps-csm-page')) || document.querySelector('.wpps-csm-page') || document;
	}

	function dispatchChange(el) {
		if (!el) return;
		el.dispatchEvent(new Event('input', { bubbles: true }));
		el.dispatchEvent(new Event('change', { bubbles: true }));
	}

	function syncOverlayControls(container, key, strVal) {
		if (key.indexOf('overlay_opacity') === -1) return;
		container.querySelectorAll('[data-setting-key="' + key + '"].wpps-bg-overlay-opacity-num').forEach(function (numInput) {
			var td = numInput.closest('td');
			var range = td ? td.querySelector('.wpps-bg-overlay-opacity') : null;
			if (range) range.value = strVal;
		});
	}

	function syncColorFields(container, key, strVal) {
		if (key.indexOf('color') === -1) return;
		container.querySelectorAll('[data-setting-key="' + key + '"]').forEach(function (field) {
			if (field.type === 'color') {
				container.querySelectorAll('[data-color-input="' + field.id + '"]').forEach(function (hex) {
					if (/^#/.test(strVal)) {
						hex.value = strVal.length > 7 ? strVal.substring(0, 7) : strVal;
						dispatchChange(hex);
					}
				});
			}
			if (field.classList && field.classList.contains('wpps-color-code-input')) {
				var colorId = field.getAttribute('data-color-input');
				var colorPicker = colorId ? document.getElementById(colorId) : null;
				if (colorPicker && /^#/.test(strVal)) {
					colorPicker.value = strVal.length > 7 ? strVal.substring(0, 7) : strVal;
				} else if (colorPicker && strVal === '') {
					colorPicker.value = '#ffffff';
				}
			}
		});
	}

	function setFieldValue(container, key, value) {
		if (!container || key == null || SKIP_KEYS[key] || PRESERVE_KEYS[key]) return;
		var strVal = value === null || value === undefined ? '' : String(value);
		var fields = container.querySelectorAll('[data-setting-key="' + key + '"]');
		if (!fields.length) return;

		fields.forEach(function (field) {
			if (field.type === 'checkbox') {
				field.checked = (strVal === '1' || strVal === 'true' || strVal === true);
			} else if (field.type === 'radio') {
				field.checked = (field.value === strVal);
			} else {
				field.value = strVal;
			}
			dispatchChange(field);
		});

		syncColorFields(container, key, strVal);
		syncOverlayControls(container, key, strVal);
	}

	function shouldApplyPresetKey(key, preset) {
		if (SKIP_KEYS[key] || PRESERVE_KEYS[key]) return false;
		if (key === 'heading' || key === 'description' || key === 'social_links') return false;
		if (key === 'bg_image_url' && !(preset.bg_type === 'image' && preset.bg_image_url)) return false;
		return true;
	}

	function updateBgPreviewFromForm() {
		var mid = window.wppsCsmModuleId || 'coming-soon-maintenance';
		var preview = document.getElementById(mid + '_bg_preview');
		var removeBtn = document.getElementById(mid + '_remove_bg');
		var idField = document.getElementById(mid + '_bg_image_id');
		var urlField = document.getElementById(mid + '_bg_image_url');
		if (!preview) return;

		var url = '';
		if (idField && idField.value && idField.value !== '0') {
			var img = preview.querySelector('img');
			url = img ? img.getAttribute('src') : '';
		}
		if (!url && urlField && urlField.value) {
			url = urlField.value;
		}

		if (url) {
			preview.innerHTML = '<img src="' + url.replace(/"/g, '&quot;') + '" alt="" style="max-width:100%;max-height:120px;object-fit:contain;">';
			if (removeBtn) removeBtn.style.display = '';
		} else {
			preview.innerHTML = '<span style="color:#999;">' + (window.wppsCsmNoImageText || 'No image') + '</span>';
			if (removeBtn) removeBtn.style.display = 'none';
		}
	}

	function updateBgPreview(container, preset) {
		var mid = window.wppsCsmModuleId || 'coming-soon-maintenance';
		var urlField = document.getElementById(mid + '_bg_image_url');
		var idField = document.getElementById(mid + '_bg_image_id');

		if (preset.bg_type === 'image' && preset.bg_image_url) {
			if (urlField) {
				urlField.value = preset.bg_image_url;
				dispatchChange(urlField);
			}
			if (idField) {
				idField.value = '0';
				dispatchChange(idField);
			}
			updateBgPreviewFromForm();
			return;
		}

		updateBgPreviewFromForm();
	}

	function updateLogoPreviewFromForm() {
		var mid = window.wppsCsmModuleId || 'coming-soon-maintenance';
		var preview = document.getElementById(mid + '_logo_preview');
		var removeBtn = document.getElementById(mid + '_remove_logo');
		var idField = document.getElementById(mid + '_logo_id');
		var urlField = document.getElementById(mid + '_logo_url');
		if (!preview) return;

		var url = '';
		if (urlField && urlField.value) {
			url = urlField.value;
		} else if (idField && idField.value && idField.value !== '0') {
			var img = preview.querySelector('img');
			url = img ? img.getAttribute('src') : '';
		}

		if (url) {
			var width = typeof window.wppsCsmGetLogoPreviewMaxWidth === 'function'
				? window.wppsCsmGetLogoPreviewMaxWidth()
				: 180;
			preview.innerHTML = '<img src="' + url.replace(/"/g, '&quot;') + '" alt="" style="max-width:' + width + 'px;height:auto;border:1px solid #ddd;padding:4px;border-radius:4px;">';
			if (removeBtn) removeBtn.style.display = '';
		} else if (!idField || !idField.value || idField.value === '0') {
			preview.innerHTML = '';
			if (removeBtn) removeBtn.style.display = 'none';
		}
	}

	function applySocialLinks(container, links) {
		if (typeof window.wppsCsmApplySocialLinks === 'function') {
			window.wppsCsmApplySocialLinks(links || []);
			return;
		}

		var mid = window.wppsCsmModuleId || 'coming-soon-maintenance';
		var hidden = document.getElementById(mid + '_social_links');
		if (hidden) {
			hidden.value = JSON.stringify(Array.isArray(links) ? links : []);
			dispatchChange(hidden);
		}
	}

	function applyEditors(container, preset) {
		var mid = window.wppsCsmModuleId || 'coming-soon-maintenance';
		['heading', 'description'].forEach(function (key) {
			if (preset[key] === undefined) return;
			var content = String(preset[key]);
			var ta = document.getElementById(mid + '_' + key);
			if (ta) {
				ta.value = content;
				dispatchChange(ta);
			}
			if (window.tinymce && typeof window.tinymce.get === 'function') {
				var ed = window.tinymce.get(mid + '_' + key);
				if (ed) {
					ed.setContent(content);
				}
			}
		});
	}

	function applyCodeEditor(container, preset) {
		if (preset.custom_css === undefined) return;
		var mid = window.wppsCsmModuleId || 'coming-soon-maintenance';
		var css = String(preset.custom_css || '');
		var ta = document.getElementById(mid + '_custom_css');
		if (ta) {
			ta.value = css;
			dispatchChange(ta);
		}
		if (window.wppsCsmCodeEditors && Array.isArray(window.wppsCsmCodeEditors)) {
			window.wppsCsmCodeEditors.forEach(function (ed) {
				if (ed && ed.codemirror && ed.codemirror.getTextArea() && ed.codemirror.getTextArea().id === mid + '_custom_css') {
					ed.codemirror.setValue(css);
				}
			});
		}
	}

	function applyPatternSelection(container, pattern) {
		if (!pattern) return;
		container.querySelectorAll('.wpps-csm-pattern-option').forEach(function (option) {
			var input = option.querySelector('input[data-setting-key="bg_pattern"]');
			var isMatch = input && input.value === pattern;
			option.classList.toggle('is-selected', isMatch);
			if (input) input.checked = isMatch;
		});
	}

	function filterPresetCards(container, mode) {
		var group = mode === 'maintenance' ? 'maintenance' : 'coming_soon';
		container.querySelectorAll('.wpps-csm-page-preset').forEach(function (card) {
			var cardGroup = card.getAttribute('data-preset-group');
			var show = cardGroup === 'default' || cardGroup === group;
			card.classList.toggle('is-hidden', !show);
		});
	}

	function showPresetNotice(container, presetName) {
		var wrap = container.querySelector('.wp-powersuite-settings--csm') || container.querySelector('.wp-powersuite-settings');
		if (!wrap) return;
		var existing = wrap.querySelector('.wpps-csm-preset-notice');
		if (existing) existing.remove();
		var notice = document.createElement('div');
		notice.className = 'notice notice-info is-dismissible wpps-csm-preset-notice';
		notice.innerHTML = '<p><strong>' + presetName + '</strong> — ' + (window.wppsCsmPresetAppliedText || 'Template applied. Your logo and enabled status are unchanged — click Save Settings to keep changes.') + '</p>';
		wrap.insertBefore(notice, wrap.firstChild);
		setTimeout(function () {
			if (notice.parentNode) notice.remove();
		}, 8000);
	}

	function applyPreset(presetId, triggerEl) {
		var presets = window.wppsCsmPagePresets || {};
		var preset = presets[presetId];
		if (!preset) return false;

		var container = getRoot(triggerEl);
		if (!container) return false;

		Object.keys(preset).forEach(function (key) {
			if (!shouldApplyPresetKey(key, preset)) return;
			setFieldValue(container, key, preset[key]);
		});

		applyEditors(container, preset);
		applySocialLinks(container, preset.social_links);
		applyCodeEditor(container, preset);
		applyPatternSelection(container, preset.bg_pattern);

		if (typeof window.wppsCsmToggleBgType === 'function' && preset.bg_type) {
			window.wppsCsmToggleBgType(preset.bg_type);
		}

		if (typeof window.wppsCsmToggleLogo === 'function') {
			window.wppsCsmToggleLogo();
		}

		if (typeof window.wppsCsmToggleLogoSource === 'function') {
			window.wppsCsmToggleLogoSource();
		}

		if (typeof window.wppsCsmToggleMode === 'function') {
			window.wppsCsmToggleMode();
		}

		updateBgPreview(container, preset);
		updateLogoPreviewFromForm();

		container.querySelectorAll('.wpps-csm-page-preset').forEach(function (card) {
			var active = card.getAttribute('data-preset-id') === presetId;
			card.classList.toggle('is-active', active);
			card.setAttribute('aria-pressed', active ? 'true' : 'false');
		});

		var hiddenPreset = container.querySelector('input[data-setting-key="page_preset"]');
		if (hiddenPreset) {
			hiddenPreset.value = presetId;
			dispatchChange(hiddenPreset);
		}

		var modeInput = container.querySelector('input[name="mode"]:checked');
		filterPresetCards(container, modeInput ? modeInput.value : 'coming_soon');

		var card = triggerEl && triggerEl.closest ? triggerEl.closest('.wpps-csm-page-preset') : null;
		var presetName = card ? (card.querySelector('.wpps-csm-page-preset__name') || {}).textContent : '';
		if (presetName) showPresetNotice(container, presetName.trim());

		return true;
	}

	function initPagePresets(container) {
		if (!container || container.getAttribute('data-wpps-csm-presets-init')) return;
		container.setAttribute('data-wpps-csm-presets-init', '1');

		container.addEventListener('click', function (ev) {
			var card = ev.target.closest('.wpps-csm-page-preset');
			if (!card || card.classList.contains('is-hidden')) return;
			ev.preventDefault();
			var presetId = card.getAttribute('data-preset-id');
			if (presetId) applyPreset(presetId, card);
		});

		container.querySelectorAll('input[name="mode"]').forEach(function (input) {
			input.addEventListener('change', function () {
				filterPresetCards(container, input.value);
			});
		});

		var modeInput = container.querySelector('input[name="mode"]:checked');
		filterPresetCards(container, modeInput ? modeInput.value : 'coming_soon');

		var current = container.querySelector('input[data-setting-key="page_preset"]');
		if (current && current.value) {
			container.querySelectorAll('.wpps-csm-page-preset[data-preset-id="' + current.value + '"]').forEach(function (card) {
				card.classList.add('is-active');
				card.setAttribute('aria-pressed', 'true');
			});
		}
	}

	window.wppsApplyCsmPagePreset = applyPreset;
	window.wppsInitCsmPagePresets = initPagePresets;
	window.wppsFilterCsmPagePresets = filterPresetCards;
	window.wppsCsmUpdateBgPreviewFromForm = updateBgPreviewFromForm;
	window.wppsCsmUpdateLogoPreviewFromForm = updateLogoPreviewFromForm;

	function bootPresets() {
		var page = document.querySelector('.wpps-csm-page');
		if (page) initPagePresets(page);
	}

	document.addEventListener('DOMContentLoaded', bootPresets);
	document.addEventListener('wppsCsmAdminReady', bootPresets);
})();
