/**
 * Apply ready-made Login Page Customizer layout presets to the settings form.
 */
(function () {
	'use strict';

	function getRoot(fromEl) {
		if (typeof window.__wppsGetLoginCustomizorRoot === 'function') {
			return window.__wppsGetLoginCustomizorRoot(fromEl);
		}
		return document.querySelector('.wpps-login-customizor-page') || document;
	}

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

	function setFieldValue(container, key, value) {
		if (!container || key == null) 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);
		});

		if (key === 'form_alignment' || key === 'split_form_form_alignment' || key === 'logo_alignment') {
			var hidden = container.querySelector('input[data-setting-key="' + key + '"]');
			var group = hidden ? hidden.closest('.wpps-alignment-icons') : null;
			if (group) {
				group.querySelectorAll('.wpps-alignment-btn').forEach(function (btn) {
					btn.classList.toggle('is-active', btn.getAttribute('data-alignment') === strVal);
				});
			}
		}

		if (key === 'button_normal_bg_type' || key === 'button_hover_bg_type') {
			var hiddenBtn = container.querySelector('input[data-setting-key="' + key + '"]');
			var btnGroup = hiddenBtn ? hiddenBtn.closest('.wpps-bg-type-icons') : null;
			if (btnGroup) {
				btnGroup.querySelectorAll('.wpps-bg-type-btn').forEach(function (btn) {
					btn.classList.toggle('is-active', btn.getAttribute('data-bg-type') === strVal);
				});
				var btnReset = btnGroup.querySelector('.wpps-bg-type-reset');
				if (btnReset) {
					btnReset.classList.toggle('wpps-reset-hidden', strVal === '');
				}
			}
			var btnTable = container.querySelector('.wpps-button-normal-table');
			if (btnTable && key === 'button_normal_bg_type') {
				btnTable.classList.remove('wpps-button-normal-bg-type-color', 'wpps-button-normal-bg-type-gradient');
				if (strVal) {
					btnTable.classList.add('wpps-button-normal-bg-type-' + strVal);
				}
			}
		}

		if (key === 'classic_bg_type' || key === 'split_form_bg_type' || key === 'split_empty_bg_type') {
			var hiddenBg = container.querySelector('input[data-setting-key="' + key + '"]');
			var iconGroup = hiddenBg ? hiddenBg.closest('.wpps-bg-type-icons') : null;
			if (iconGroup) {
				iconGroup.querySelectorAll('.wpps-bg-type-btn').forEach(function (btn) {
					btn.classList.toggle('is-active', btn.getAttribute('data-bg-type') === strVal);
				});
				var resetBtn = iconGroup.querySelector('.wpps-bg-type-reset');
				if (resetBtn) {
					resetBtn.classList.toggle('wpps-reset-hidden', strVal === '');
				}
			}
			var table = container.querySelector('.wpps-login-customizor-table');
			if (table && key === 'classic_bg_type') {
				table.className = table.className.replace(/wpps-classic-bg-type-\S+/g, '').trim();
				if (strVal) {
					table.classList.add('wpps-classic-bg-type-' + strVal);
				}
			}
			if (typeof window.syncSplitPanelBgRows === 'function') {
				window.syncSplitPanelBgRows(container);
			}
		}

		if (key.indexOf('_gradient_color') !== -1 || key.indexOf('color') !== -1) {
			fields.forEach(function (field) {
				if (field.type === 'color') {
					var hexInputs = container.querySelectorAll('[data-color-input="' + field.id + '"]');
					if (field.value) {
						hexInputs.forEach(function (hex) {
							hex.value = field.value;
							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) {
						return;
					}
					if (/^#/.test(strVal)) {
						colorPicker.value = strVal.length > 7 ? strVal.substring(0, 7) : strVal;
					} else if (strVal === '' && key === 'button_hover_text_color') {
						var normalHex = container.querySelector('.wpps-color-code-input[data-setting-key="button_normal_text_color"]');
						var mirror = (normalHex && /^#/.test(normalHex.value)) ? normalHex.value : '#ffffff';
						colorPicker.value = mirror.length > 7 ? mirror.substring(0, 7) : mirror;
					} else if (strVal === '' && key === 'button_normal_text_color') {
						colorPicker.value = '#ffffff';
					}
				}
			});
		}
	}

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

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

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

		if (!preset.button_hover_text_color && preset.button_normal_text_color) {
			setFieldValue(container, 'button_hover_text_color', preset.button_normal_text_color);
		}

		var templateSelect = container.querySelector('select[data-setting-key="template_type"]');
		if (templateSelect) {
			var table = templateSelect.closest('.wpps-login-customizor-table');
			if (table) {
				var val = templateSelect.value;
				if (val === 'split-layout') {
					table.classList.add('wpps-template-type-split-layout');
					table.classList.remove('wpps-template-type-classic-centered');
				} else {
					table.classList.remove('wpps-template-type-split-layout');
					table.classList.add('wpps-template-type-classic-centered');
				}
			}
		}

		var editorId = (window.wppsLpcModuleId || 'login-page-customizor') + '_split_empty_content';
		var content = preset.split_empty_content;
		if (content !== undefined) {
			var ta = document.getElementById(editorId);
			if (ta) {
				ta.value = content;
				dispatchChange(ta);
				if (window.tinymce && typeof window.tinymce.get === 'function') {
					var ed = window.tinymce.get(editorId);
					if (ed) ed.setContent(content);
				}
			}
		}

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

		var addContentCb = container.querySelector('.wpps-split-empty-add-content-toggle');
		if (addContentCb) {
			var editorRow = addContentCb.closest('.wpps-split-empty-inner-table')
				? addContentCb.closest('.wpps-split-empty-inner-table').querySelector('.wpps-split-empty-editor-row')
				: null;
			if (editorRow) {
				editorRow.style.display = addContentCb.checked ? '' : 'none';
			}
			if (addContentCb.checked && typeof window.__wppsInitSplitEmptyEditorOnce === 'function') {
				setTimeout(function () { window.__wppsInitSplitEmptyEditorOnce(container); }, 250);
			}
		}

		container.querySelectorAll('.wpps-lpc-layout-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="layout_preset"]');
		if (hiddenPreset) {
			hiddenPreset.value = presetId;
			dispatchChange(hiddenPreset);
		}

		filterPresetCards(container, templateSelect ? templateSelect.value : 'classic-centered');

		return true;
	}

	function filterPresetCards(container, templateType) {
		var group = templateType === 'split-layout' ? 'split' : 'classic';
		container.querySelectorAll('.wpps-lpc-layout-preset').forEach(function (card) {
			var cardGroup = card.getAttribute('data-preset-group');
			var show = cardGroup === 'default' || cardGroup === group;
			card.classList.toggle('is-hidden', !show);
		});
	}

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

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

		var templateSelect = container.querySelector('select[data-setting-key="template_type"]');
		if (templateSelect) {
			templateSelect.addEventListener('change', function () {
				filterPresetCards(container, templateSelect.value);
			});
			filterPresetCards(container, templateSelect.value);
		}

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

	window.wppsApplyLpcLayoutPreset = applyPreset;
	window.wppsInitLpcLayoutPresets = initLayoutPresets;

	document.addEventListener('DOMContentLoaded', function () {
		var page = document.querySelector('.wpps-login-customizor-page');
		if (page) initLayoutPresets(page);
	});
})();
