/* global WPSH_SETTINGS_I18N */
(function () {
				const i18nConfig = window.WPSH_SETTINGS_I18N || {};
				const defaultLanguage = String(i18nConfig.defaultLanguage || 'de');
				const settingsOptionKey = String(i18nConfig.settingsOptionKey || 'wpsh_settings');
				const languageSelect = document.getElementById('wpsh-ui-language-select');
				const autoToggle = document.getElementById('wpsh-auto-mode-toggle');
				const loginToggle = document.getElementById('wpsh-login-toggle');
				const modeSelect = document.getElementById('wpsh-mode-select');
				const modeCell = modeSelect ? modeSelect.closest('.wpsh-mode-cell') : null;
				const modeBadge = document.querySelector('.wpsh-mode-badge');
				const autoStats = document.querySelector('.wpsh-auto-stats');
				const securePlusToggle = document.getElementById('wpsh-secure-plus-toggle');
				const secureMethodsWrap = document.getElementById('wpsh-secure-methods');
				const ajaxRestToggle = document.getElementById('wpsh-ajax-rest-toggle');
				const autoEndpointToggle = document.getElementById('wpsh-auto-endpoint-toggle');
				const DRAFT_KEY = 'wpsh-settings-draft';
				const form = document.querySelector('.wpsh-settings form');
				const restoreDraft = () => {
					if (!form) {
						return;
					}
					let raw = '';
					try {
						raw = sessionStorage.getItem(DRAFT_KEY) || '';
					} catch (e) {
						return;
					}
					if (!raw) {
						return;
					}
					let draft = null;
					try {
						draft = JSON.parse(raw);
					} catch (e) {
						draft = null;
					}
					if (!draft || typeof draft !== 'object') {
						return;
					}
					const esc = (window.CSS && typeof window.CSS.escape === 'function')
						? window.CSS.escape.bind(window.CSS)
						: function (value) { return String(value).replace(/["\\]/g, '\\$&'); };
					Object.keys(draft).forEach((name) => {
						const value = draft[name];
						const fields = form.querySelectorAll('[name="' + esc(name) + '"]');
						fields.forEach((field) => {
							if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement || field instanceof HTMLSelectElement)) {
								return;
							}
							if (field.type === 'checkbox' || field.type === 'radio') {
								field.checked = Array.isArray(value) ? value.includes(field.value) : value === field.value || value === true;
								return;
							}
							field.value = Array.isArray(value) ? String(value[0] || '') : String(value ?? '');
						});
					});
					try {
						sessionStorage.removeItem(DRAFT_KEY);
					} catch (e) {
						// no-op
					}
				};
				const storeDraft = () => {
					if (!form) {
						return;
					}
					const draft = {};
					form.querySelectorAll('input, textarea, select').forEach((field) => {
						if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement || field instanceof HTMLSelectElement)) {
							return;
						}
						if (!field.name || field.name === settingsOptionKey + '[ui_language]') {
							return;
						}
						if (field.type === 'checkbox') {
							if (!draft[field.name]) {
								draft[field.name] = [];
							}
							if (field.checked) {
								draft[field.name].push(field.value || '1');
							}
							return;
						}
						if (field.type === 'radio') {
							if (field.checked) {
								draft[field.name] = field.value;
							}
							return;
						}
						draft[field.name] = field.value;
					});
					try {
						sessionStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
					} catch (e) {
						// no-op
					}
				};

				window.wpshSettingsLangChange = function (language) {
					const lang = String(language || i18nConfig.currentLanguage || defaultLanguage);
					storeDraft();
					const url = new URL(window.location.href);
					url.searchParams.set('wpsh_set_ui_language', lang);
					url.searchParams.set('wpsh_lang_nonce', String(i18nConfig.langNonce || ''));
					window.location.assign(url.toString());
				};

				restoreDraft();
				const applySecurePlusMasterToChildren = () => {
					if (!securePlusToggle || !secureMethodsWrap) {
						return;
					}
					const shouldCheck = securePlusToggle.checked && !securePlusToggle.disabled;
					secureMethodsWrap.querySelectorAll('input[type="checkbox"]').forEach((el) => {
						el.checked = shouldCheck;
					});
				};
				const i18nNodes = [
					['.wpsh-settings-header h1', 'title'],
					['.wpsh-settings-header p', 'subtitle'],
					['.wpsh-settings-toolbar .wpsh-toolbar-field > span', 'ui_language'],
					['.wpsh-settings-panel:nth-of-type(1) h2', 'section_protection'],
					['.wpsh-settings-panel:nth-of-type(2) h2', 'section_difficulty'],
					['.wpsh-settings-panel:nth-of-type(3) h2', 'section_security'],
					['.wpsh-row-protect-login th .wpsh-help-label', 'protect_login'],
					['#wpsh-login-toggle + span', 'active'],
					['.wpsh-login-js-warning', 'login_js_required_warning'],
					['.wpsh-login-dependent-row th .wpsh-help-label', 'login_lockout_title'],
					['.wpsh-login-dependent-row .wpsh-inline-field:nth-of-type(1) > span', 'login_lockout_attempts_label'],
					['.wpsh-login-dependent-row .wpsh-inline-field:nth-of-type(2) > span', 'login_lockout_minutes_label'],
					['.wpsh-login-dependent-row .description', 'login_lockout_help'],
					['.wpsh-row-protect-comments th .wpsh-help-label', 'protect_comments'],
					['.wpsh-row-protect-comments .wpsh-toggle span', 'active'],
					['.wpsh-row-protect-contact th .wpsh-help-label', 'protect_contact'],
					['.wpsh-row-protect-contact .wpsh-toggle span', 'active_contact'],
					['.wpsh-row-protect-woo th .wpsh-help-label', 'protect_woo'],
					['.wpsh-row-protect-woo .wpsh-toggle span', 'active_pro'],
					['.wpsh-row-protect-generic th .wpsh-help-label', 'protect_generic'],
					['.wpsh-row-protect-generic .wpsh-toggle span', 'active'],
					['.wpsh-row-protect-generic td .description:nth-of-type(1)', 'generic_help'],
					['.wpsh-row-protect-generic td .description:nth-of-type(2)', 'generic_examples'],
					['.wpsh-row-mode th', 'mode'],
					['.wpsh-row-mode .wpsh-mode-note', () => (autoToggle && autoToggle.checked ? 'mode_locked_auto' : 'mode_manual_note')],
					['.wpsh-row-auto-level th .wpsh-help-label', 'auto_level_title'],
					['#wpsh-auto-mode-toggle + span', 'auto_level_toggle'],
					['.wpsh-row-token-validity th .wpsh-help-label', 'token_validity_title'],
					['.wpsh-row-token-validity td .description', 'token_validity_help'],
					['.wpsh-row-logging th', 'logging'],
					['.wpsh-row-logging .wpsh-toggle span', 'active'],
					['.wpsh-row-stats-weekly-email th', 'stats_weekly_email'],
					['.wpsh-row-stats-weekly-email .wpsh-toggle span', 'stats_weekly_email_help'],
					['.wpsh-row-progressive-login th .wpsh-help-label', 'progressive_login'],
					['.wpsh-row-progressive-login .wpsh-toggle span', 'progressive_login_help'],
					['.wpsh-row-progressive-login .description', 'progressive_login_note'],
					['.wpsh-row-secure-plus th', 'secure_plus'],
					['#wpsh-secure-plus-toggle + span', 'secure_plus_help'],
					['.wpsh-row-secure-plus > td > .description', 'secure_plus_pool_hint'],
					['.wpsh-row-geo-stats th .wpsh-help-label', 'geo_stats_title'],
					['.wpsh-row-geo-stats .wpsh-toggle:nth-of-type(1) span', 'geo_stats_toggle'],
					['.wpsh-row-geo-stats .description:nth-of-type(1)', 'geo_stats_help'],
					['.wpsh-row-geo-stats .wpsh-toggle:nth-of-type(2) span', 'geo_map_toggle'],
					['.wpsh-row-geo-stats .description:nth-of-type(2)', 'geo_map_help'],
					['.wpsh-row-trusted-ips th', 'trusted_ips'],
					['.wpsh-row-trusted-ips .description', 'trusted_ips_help'],
					['.wpsh-row-ajax-rest-master th .wpsh-help-label', 'ajax_rest_master_title'],
					['#wpsh-ajax-rest-toggle + span', 'ajax_rest_master_toggle'],
					['.wpsh-row-ajax-rest-master .description', 'ajax_rest_master_help'],
					['.wpsh-row-ajax-rest-auto th .wpsh-help-label', 'ajax_rest_auto_title'],
					['#wpsh-auto-endpoint-toggle + span', 'ajax_rest_auto_toggle'],
					['.wpsh-row-ajax-rest-auto .description', 'ajax_rest_auto_help'],
					['.wpsh-row-ajax-actions th .wpsh-help-label', 'ajax_actions_title'],
					['.wpsh-row-ajax-actions .description', 'ajax_actions_help'],
					['.wpsh-row-rest-routes th .wpsh-help-label', 'rest_routes_title'],
					['.wpsh-row-rest-routes .description', 'rest_routes_help'],
					['.wpsh-row-ajax-rest-excludes th .wpsh-help-label', 'ajax_rest_excludes_title'],
					['.wpsh-row-ajax-rest-excludes .description', 'ajax_rest_excludes_help'],
					['.wpsh-settings .submit input[type="submit"]', 'save_changes'],
				];
				const i18nTitleNodes = [
					['.wpsh-row-protect-login .wpsh-help-tip', 'protect_login_tip'],
					['.wpsh-login-dependent-row .wpsh-help-tip', 'login_lockout_tip'],
					['.wpsh-row-protect-comments .wpsh-help-tip', 'protect_comments_tip'],
					['.wpsh-row-protect-contact .wpsh-help-tip', 'protect_contact_tip'],
					['.wpsh-row-protect-woo .wpsh-help-tip', 'protect_woo_tip'],
					['.wpsh-row-protect-generic .wpsh-help-tip', 'protect_generic_tip'],
					['.wpsh-row-auto-level .wpsh-help-tip', 'auto_level_tip'],
					['.wpsh-row-token-validity .wpsh-help-tip', 'token_validity_tip'],
					['.wpsh-row-progressive-login .wpsh-help-tip', 'progressive_login_tip'],
					['.wpsh-row-geo-stats .wpsh-help-tip', 'geo_stats_tip'],
					['.wpsh-row-ajax-rest-master .wpsh-help-tip', 'ajax_rest_master_tip'],
					['.wpsh-row-ajax-rest-auto .wpsh-help-tip', 'ajax_rest_auto_tip'],
					['.wpsh-row-ajax-actions .wpsh-help-tip', 'ajax_actions_tip'],
					['.wpsh-row-rest-routes .wpsh-help-tip', 'rest_routes_tip'],
					['.wpsh-row-ajax-rest-excludes .wpsh-help-tip', 'ajax_rest_excludes_tip'],
				];
				const setNodeTextSafely = (node, value) => {
					if (!(node instanceof Element)) {
						return;
					}
					if (node.classList.contains('wpsh-help-label') || node.querySelector('.wpsh-pro-ribbon') || node.querySelector('.wpsh-help-tip')) {
						let textNode = null;
						for (const child of node.childNodes) {
							if (child.nodeType === Node.TEXT_NODE) {
								textNode = child;
								break;
							}
						}
						if (textNode) {
							textNode.nodeValue = ' ' + value + ' ';
						} else {
							node.prepend(document.createTextNode(' ' + value + ' '));
						}
						return;
					}
					node.textContent = value;
				};
				const applyLanguage = (language) => {
					if (!i18nConfig || !i18nConfig.textsByLanguage) {
						return;
					}
					const fallbackLanguage = i18nConfig.defaultLanguage || 'de';
					const texts = i18nConfig.textsByLanguage[language] || i18nConfig.textsByLanguage[fallbackLanguage] || {};
					const fallbackTexts = i18nConfig.textsByLanguage[fallbackLanguage] || {};
					i18nNodes.forEach(([selector, key]) => {
						let node = null;
						try {
							node = document.querySelector(selector);
						} catch (e) {
							return;
						}
						if (!node) {
							return;
						}
						const resolvedKey = typeof key === 'function' ? key() : key;
						const value = texts[resolvedKey] || fallbackTexts[resolvedKey];
						if (typeof value === 'string') {
							if (node.tagName === 'INPUT' && node.getAttribute('type') === 'submit') {
								node.value = value;
							} else {
								setNodeTextSafely(node, value);
							}
						}
					});
					i18nTitleNodes.forEach(([selector, key]) => {
						let node = null;
						try {
							node = document.querySelector(selector);
						} catch (e) {
							return;
						}
						if (!node) {
							return;
						}
						const value = texts[key] || fallbackTexts[key];
						if (typeof value === 'string') {
							node.setAttribute('title', value);
						}
					});
					document.querySelectorAll('#wpsh-secure-methods .wpsh-secure-method').forEach((row) => {
						const input = row.querySelector('input[type="checkbox"]');
						if (!input) {
							return;
						}
						const rawName = input.getAttribute('name') || '';
						const match = rawName.match(/\[secure_plus_methods\]\[([^\]]+)\]/);
						if (!match) {
							return;
						}
						const key = match[1];
						const labelNode = row.querySelector('.wpsh-secure-method__label');
						const descNode = row.querySelector('.wpsh-secure-method__description');
						const labelKey = 'secure_method_' + key;
						const descKey = labelKey + '_desc';
						if (labelNode) {
							labelNode.textContent = texts[labelKey] || fallbackTexts[labelKey] || labelNode.textContent;
						}
						if (descNode) {
							descNode.textContent = texts[descKey] || fallbackTexts[descKey] || descNode.textContent;
						}
					});
					if (modeSelect) {
						const selectedMode = modeSelect.value;
						const labels = {
							relaxed: texts.mode_relaxed || fallbackTexts.mode_relaxed,
							balanced: texts.mode_balanced || fallbackTexts.mode_balanced,
							strict: texts.mode_strict || fallbackTexts.mode_strict,
						};
						Array.from(modeSelect.options).forEach((opt) => {
							const v = opt.value;
							if (labels[v]) {
								opt.textContent = labels[v];
							}
						});
						modeSelect.value = selectedMode;
					}
				};
				const persistLanguage = (language) => {
					if (!i18nConfig || !i18nConfig.ajaxUrl || !i18nConfig.nonce) {
						return;
					}
					const body = new URLSearchParams();
					body.set('action', 'wpsh_set_ui_language');
					body.set('_ajax_nonce', i18nConfig.nonce);
					body.set('ui_language', language);
					if (typeof fetch === 'function') {
						fetch(i18nConfig.ajaxUrl, {
							method: 'POST',
							credentials: 'same-origin',
							headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
							body: body.toString(),
						}).catch(() => {});
						return;
					}
					if (window.jQuery && typeof window.jQuery.post === 'function') {
						window.jQuery.post(i18nConfig.ajaxUrl, body.toString()).fail(() => {});
					}
				};
				if (!window.wpshSettingsLangChange) {
					window.wpshSettingsLangChange = (selectedLanguage) => {
						const lang = selectedLanguage || (languageSelect ? languageSelect.value : (i18nConfig ? i18nConfig.defaultLanguage : 'de'));
						try {
							applyLanguage(lang);
						} catch (e) {
							// Keep form usable even if one translation target fails.
						}
						try {
							persistLanguage(lang);
						} catch (e) {
							// Ignore persistence errors in UI.
						}
					};
				}
				const sync = () => {
					if (autoToggle && modeSelect) {
						const locked = autoToggle.checked;
						modeSelect.disabled = locked;
						if (modeCell) {
							modeCell.classList.toggle('is-auto', locked);
						}
						if (modeBadge) {
							modeBadge.classList.toggle('is-inactive', !locked);
						}
						if (autoStats) {
							autoStats.classList.toggle('is-inactive', !locked);
						}
					}

					if (loginToggle) {
						const loginEnabled = loginToggle.checked && !loginToggle.disabled;
						document.querySelectorAll('.wpsh-login-dependent-input').forEach((el) => {
							el.disabled = !loginEnabled;
						});
						document.querySelectorAll('.wpsh-login-dependent-row').forEach((el) => {
							el.classList.toggle('is-inactive', !loginEnabled);
						});
						const loginLockoutFields = document.getElementById('wpsh-login-lockout-fields');
						if (loginLockoutFields) {
							loginLockoutFields.classList.toggle('is-inactive', !loginEnabled);
						}
					}

					if (securePlusToggle && secureMethodsWrap) {
						const allowMethods = securePlusToggle.checked && !securePlusToggle.disabled;
						const methodInputs = secureMethodsWrap.querySelectorAll('input[type="checkbox"]');
						const methodRows = secureMethodsWrap.querySelectorAll('.wpsh-secure-method');
						secureMethodsWrap.classList.toggle('is-inactive', !allowMethods);
						methodInputs.forEach((el) => {
							el.disabled = !allowMethods;
						});
						methodRows.forEach((el) => {
							el.classList.toggle('is-disabled', !allowMethods);
						});
					}

					if (ajaxRestToggle) {
						const ajaxRestEnabled = ajaxRestToggle.checked && !ajaxRestToggle.disabled;
						document.querySelectorAll('.wpsh-ajax-rest-child-row').forEach((el) => {
							el.classList.toggle('is-hidden', !ajaxRestEnabled);
						});
						if (autoEndpointToggle) {
							autoEndpointToggle.disabled = !ajaxRestEnabled;
						}
						document.querySelectorAll('.wpsh-auto-endpoint-dependent').forEach((el) => {
							el.disabled = !ajaxRestEnabled;
						});
						document.querySelectorAll('.wpsh-dependent-row').forEach((el) => {
							el.classList.toggle('is-inactive', !ajaxRestEnabled);
						});
					}
				};
				if (autoToggle) {
					autoToggle.addEventListener('change', sync);
				}
				if (loginToggle) {
					loginToggle.addEventListener('change', sync);
				}
				if (securePlusToggle) {
					securePlusToggle.addEventListener('change', () => {
						applySecurePlusMasterToChildren();
						sync();
					});
					securePlusToggle.addEventListener('input', () => {
						applySecurePlusMasterToChildren();
						sync();
					});
				}
				if (ajaxRestToggle) {
					ajaxRestToggle.addEventListener('change', sync);
				}
				if (languageSelect) {
					languageSelect.addEventListener('change', () => {
						window.wpshSettingsLangChange(languageSelect.value);
					});
				}
				applyLanguage(languageSelect ? languageSelect.value : (i18nConfig.currentLanguage || defaultLanguage));
				sync();
			})();

