jQuery(function($) {
	'use strict';

	var config = window.wppsSettings || {};
	var strings = config.strings || {};
	var ajaxurl = config.ajaxUrl || '';
	var nonce = config.nonce || '';
	var baseUrl = config.baseUrl || '';

	function showFeedback($btn, message, ok) {
		var $fb = $('<span class="wpps-settings-feedback"></span>');
		$fb.css('color', ok ? '#008a20' : '#b32d2e').text(message || (ok ? strings.done || 'Done' : strings.failed || 'Failed'));
		$btn.siblings('.wpps-settings-feedback').remove();
		$btn.before($fb);
		setTimeout(function() { $fb.remove(); }, 3500);
	}

	function showNotice(message, type) {
		var noticeType = type === 'success' ? 'success' : 'error';
		var $wrap = $('.wp-powersuite-settings').first();
		if (!$wrap.length) {
			return;
		}
		$wrap.find('.wpps-settings-inline-notice').remove();
		var $notice = $(
			'<div class="notice notice-' + noticeType + ' is-dismissible wpps-settings-inline-notice">' +
			'<p></p>' +
			'<button type="button" class="notice-dismiss"><span class="screen-reader-text">' + (strings.dismiss || 'Dismiss') + '</span></button>' +
			'</div>'
		);
		$notice.find('p').text(message);
		$notice.find('.notice-dismiss').on('click', function() {
			$notice.remove();
		});
		$wrap.prepend($notice);
	}

	function ensureConfirmOverlay() {
		var $overlay = $('#wpps-settings-confirm-overlay');
		if ($overlay.length) {
			return $overlay;
		}
		$overlay = $(
			'<div id="wpps-settings-confirm-overlay" class="wpps-settings-confirm-overlay" style="display:none;">' +
			'<div class="wpps-settings-confirm-dialog" role="dialog" aria-modal="true" aria-labelledby="wpps-settings-confirm-message">' +
			'<p id="wpps-settings-confirm-message" class="wpps-settings-confirm-message"></p>' +
			'<div class="wpps-settings-confirm-input-wrap" style="display:none;">' +
			'<p class="wpps-settings-confirm-hint"></p>' +
			'<input type="text" class="regular-text wpps-settings-confirm-input" autocomplete="off" spellcheck="false" />' +
			'</div>' +
			'<div class="wpps-settings-confirm-actions">' +
			'<button type="button" class="button button-primary wpps-settings-confirm-yes"></button>' +
			'<button type="button" class="button wpps-settings-confirm-no"></button>' +
			'</div></div></div>'
		);
		$('body').append($overlay);
		return $overlay;
	}

	function confirmAction(message) {
		return new Promise(function(resolve) {
			var $overlay = ensureConfirmOverlay();
			$overlay.find('.wpps-settings-confirm-message').text(message);
			$overlay.find('.wpps-settings-confirm-yes').text(strings.confirm || 'Confirm');
			$overlay.find('.wpps-settings-confirm-no').text(strings.cancel || 'Cancel');
			$overlay.find('.wpps-settings-confirm-input-wrap').hide();
			$overlay.find('.wpps-settings-confirm-input').val('');

			function cleanup(result) {
				$overlay.hide();
				$overlay.find('.wpps-settings-confirm-yes, .wpps-settings-confirm-no').off('click.wppsConfirm');
				$overlay.find('.wpps-settings-confirm-input').off('keydown.wppsConfirm');
				resolve(result);
			}

			$overlay.find('.wpps-settings-confirm-yes').off('click.wppsConfirm').on('click.wppsConfirm', function() {
				cleanup(true);
			});
			$overlay.find('.wpps-settings-confirm-no').off('click.wppsConfirm').on('click.wppsConfirm', function() {
				cleanup(false);
			});
			$overlay.show();
		});
	}

	function confirmTypedAction(message, requiredPhrase, promptText) {
		return new Promise(function(resolve) {
			var $overlay = ensureConfirmOverlay();
			var required = (requiredPhrase || '').trim();
			$overlay.find('.wpps-settings-confirm-message').text(message);
			$overlay.find('.wpps-settings-confirm-hint').text(promptText || '');
			$overlay.find('.wpps-settings-confirm-input-wrap').show();
			$overlay.find('.wpps-settings-confirm-input').val('').attr('aria-label', strings.clearAllTypeLabel || 'Confirmation');
			$overlay.find('.wpps-settings-confirm-yes').text(strings.confirm || 'Confirm');
			$overlay.find('.wpps-settings-confirm-no').text(strings.cancel || 'Cancel');

			function cleanup(result) {
				$overlay.hide();
				$overlay.find('.wpps-settings-confirm-yes, .wpps-settings-confirm-no').off('click.wppsConfirm');
				$overlay.find('.wpps-settings-confirm-input').off('keydown.wppsConfirm input.wppsConfirm');
				resolve(result);
			}

			function submitTypedConfirm() {
				var typed = ($overlay.find('.wpps-settings-confirm-input').val() || '').trim();
				if (typed !== required) {
					showNotice(strings.clearAllTypeMismatch || 'Confirmation text did not match.', 'error');
					return;
				}
				cleanup(true);
			}

			$overlay.find('.wpps-settings-confirm-yes').off('click.wppsConfirm').on('click.wppsConfirm', submitTypedConfirm);
			$overlay.find('.wpps-settings-confirm-no').off('click.wppsConfirm').on('click.wppsConfirm', function() {
				cleanup(false);
			});
			$overlay.find('.wpps-settings-confirm-input').off('keydown.wppsConfirm').on('keydown.wppsConfirm', function(e) {
				if (e.key === 'Enter') {
					e.preventDefault();
					submitTypedConfirm();
				}
			});
			$overlay.show();
			$overlay.find('.wpps-settings-confirm-input').trigger('focus');
		});
	}

	function getSettingsTabFromUrl() {
		var tab = (new URLSearchParams(window.location.search)).get('tab');
		if (tab === 'configurations' || tab === 'white-label' || tab === 'ai-connections') {
			return tab;
		}
		return 'general';
	}

	function buildSettingsTabUrl(tab) {
		var url = new URL(window.location.href);
		if (tab === 'general') {
			url.searchParams.delete('tab');
		} else {
			url.searchParams.set('tab', tab);
		}
		return url.toString();
	}

	function activateSettingsTab(tab, historyMode) {
		if (tab === 'white-label' && config.whiteLabel && !config.whiteLabel.mediaReady) {
			window.location.href = buildSettingsTabUrl('white-label');
			return;
		}

		$('.wpps-settings-tab').removeClass('is-active').attr('aria-selected', 'false');
		$('.wpps-settings-tab[data-tab="' + tab + '"]').addClass('is-active').attr('aria-selected', 'true');
		$('.wpps-settings-panel').hide();
		$('.wpps-settings-panel[data-panel="' + tab + '"]').show();

		if (historyMode === 'push') {
			history.pushState({ wppsSettingsTab: tab }, '', buildSettingsTabUrl(tab));
		} else if (historyMode === 'replace') {
			history.replaceState({ wppsSettingsTab: tab }, '', buildSettingsTabUrl(tab));
		}
	}

	$('.wpps-settings-tab').on('click', function() {
		var tab = $(this).data('tab');
		if ($(this).hasClass('is-active')) {
			return;
		}
		activateSettingsTab(tab, 'push');
	});

	window.addEventListener('popstate', function() {
		var tab = (history.state && history.state.wppsSettingsTab) || getSettingsTabFromUrl();
		activateSettingsTab(tab, false);
	});

	activateSettingsTab(getSettingsTabFromUrl(), 'replace');

	function collectWhiteLabelPayload() {
		return {
			enabled: $('#wpps-white-label-enabled').is(':checked') ? 1 : 0,
			plugin_name: ($('#wpps-white-label-plugin-name').val() || '').trim(),
			plugin_short_name: ($('#wpps-white-label-plugin-short-name').val() || '').trim(),
			plugin_description: ($('#wpps-white-label-plugin-description').val() || '').trim(),
			menu_title: ($('#wpps-white-label-menu-title').val() || '').trim(),
			dashboard_title: ($('#wpps-white-label-dashboard-title').val() || '').trim(),
			company_name: ($('#wpps-white-label-company-name').val() || '').trim(),
			plugin_author: ($('#wpps-white-label-plugin-author').val() || '').trim(),
			plugin_author_uri: ($('#wpps-white-label-plugin-author-uri').val() || '').trim(),
			website_url: ($('#wpps-white-label-website-url').val() || '').trim(),
			support_url: ($('#wpps-white-label-support-url').val() || '').trim(),
			documentation_url: ($('#wpps-white-label-documentation-url').val() || '').trim(),
			logo_attachment_id: parseInt($('#wpps-white-label-logo-id').val(), 10) || 0,
			menu_icon_attachment_id: parseInt($('#wpps-white-label-menu-icon-id').val(), 10) || 0,
			hide_powered_by: $('#wpps-white-label-hide-powered-by').is(':checked') ? 1 : 0,
			hide_license_menu: $('#wpps-white-label-hide-license').is(':checked') ? 1 : 0,
			hide_white_label_settings: $('#wpps-white-label-hide-settings').is(':checked') ? 1 : 0,
			hide_external_links: $('#wpps-white-label-hide-external').is(':checked') ? 1 : 0
		};
	}

	var whiteLabelConfig = config.whiteLabel || {};
	var whiteLabelDefaults = {
		pluginName: whiteLabelConfig.defaultPluginName || 'Site Toolkit by WP PowerSuite',
		pluginDescription: whiteLabelConfig.defaultPluginDescription || '',
		iconUrl: whiteLabelConfig.defaultIconUrl || ''
	};
	var whiteLabelMedia = {
		logoUrl: whiteLabelConfig.logoUrl || '',
		menuIconUrl: whiteLabelConfig.menuIconUrl || ''
	};
	var mediaFrameCache = {};

	function previewValue(value, fallback) {
		var trimmed = (value || '').trim();
		return trimmed !== '' ? trimmed : fallback;
	}

	function previewIconEl(url, size, dashicon) {
		if (url) {
			return $('<img>', { src: url, alt: '', width: size, height: size });
		}
		return $('<span>', {
			'class': 'dashicons ' + (dashicon || 'dashicons-admin-plugins'),
			'aria-hidden': 'true'
		});
	}

	function setMediaBox($box, url, size, dashicon) {
		var iconClass = dashicon || 'dashicons-format-image';
		if (url) {
			$box.removeAttr('data-empty').empty().append(
				$('<img>', { src: url, alt: '', width: size, height: size })
			);
		} else {
			$box.attr('data-empty', '1').empty().append(
				$('<span>', {
					'class': 'wpps-white-label-media__placeholder dashicons ' + iconClass,
					'aria-hidden': 'true'
				})
			);
		}
	}

	function setWhiteLabelPreview($preview, $removeBtn, url, size, dashicon) {
		setMediaBox($preview, url, size, dashicon);
		if (url) {
			$removeBtn.show();
		} else {
			$removeBtn.hide();
		}
	}

	function resolveMenuIconUrl() {
		return whiteLabelMedia.menuIconUrl || whiteLabelMedia.logoUrl || whiteLabelDefaults.iconUrl || '';
	}

	function resolveLogoUrl() {
		return whiteLabelMedia.logoUrl || whiteLabelDefaults.iconUrl || '';
	}

	function updateWhiteLabelPreview() {
		var pluginName = previewValue($('#wpps-white-label-plugin-name').val(), whiteLabelDefaults.pluginName);
		var menuTitle = previewValue($('#wpps-white-label-menu-title').val(), pluginName);
		var description = previewValue($('#wpps-white-label-plugin-description').val(), whiteLabelDefaults.pluginDescription);
		var author = ($('#wpps-white-label-plugin-author').val() || '').trim();
		var menuIcon = resolveMenuIconUrl();
		var logo = resolveLogoUrl();

		$('#wpps-white-label-preview-menu-title').text(menuTitle);
		$('#wpps-white-label-preview-hero-title').text(pluginName);
		$('#wpps-white-label-preview-plugin-name').text(pluginName);
		$('#wpps-white-label-preview-hero-tagline').text(description);
		$('#wpps-white-label-preview-plugin-description').text(description);
		$('#wpps-white-label-preview-menu-icon').empty().append(previewIconEl(menuIcon, 20, 'dashicons-admin-plugins'));
		$('#wpps-white-label-preview-hero-icon').empty().append(previewIconEl(logo, 28, 'dashicons-admin-plugins'));

		var $author = $('#wpps-white-label-preview-plugin-author');
		if (author) {
			$author.text((strings.authorBy || 'By %s').replace('%s', author)).show();
		} else {
			$author.hide().text('');
		}
	}

	function ensureMediaLibrary() {
		if (typeof wp !== 'undefined' && wp.media) {
			return true;
		}
		if (!whiteLabelConfig.mediaReady) {
			if (whiteLabelConfig.standalonePage) {
				window.location.reload();
			} else {
				window.location.href = buildSettingsTabUrl('white-label');
			}
			return false;
		}
		showNotice(strings.mediaUnavailable || 'Media library is unavailable.', 'error');
		return false;
	}

	function openMediaFrame(key, title, onSelect) {
		if (!ensureMediaLibrary()) {
			return;
		}
		if (!mediaFrameCache[key]) {
			mediaFrameCache[key] = wp.media({
				title: title,
				button: { text: strings.selectImage || 'Use image' },
				library: { type: 'image' },
				multiple: false
			});
			mediaFrameCache[key].on('select', function() {
				var attachment = mediaFrameCache[key].state().get('selection').first().toJSON();
				onSelect(attachment);
			});
		}
		mediaFrameCache[key].open();
	}

	$('.wpps-white-label-field, #wpps-white-label-enabled').on('input change', updateWhiteLabelPreview);
	updateWhiteLabelPreview();

	$('#wpps-white-label-logo-select').on('click', function() {
		openMediaFrame('logo', strings.logoTitle || 'Select logo', function(attachment) {
			$('#wpps-white-label-logo-id').val(attachment.id);
			whiteLabelMedia.logoUrl = attachment.url || '';
			setWhiteLabelPreview($('#wpps-white-label-logo-preview'), $('#wpps-white-label-logo-remove'), attachment.url, 56, 'dashicons-format-image');
			updateWhiteLabelPreview();
		});
	});

	$('#wpps-white-label-logo-remove').on('click', function() {
		$('#wpps-white-label-logo-id').val('0');
		whiteLabelMedia.logoUrl = '';
		setWhiteLabelPreview($('#wpps-white-label-logo-preview'), $(this), '', 56, 'dashicons-format-image');
		updateWhiteLabelPreview();
	});

	$('#wpps-white-label-menu-icon-select').on('click', function() {
		openMediaFrame('menuIcon', strings.menuIconTitle || 'Select menu icon', function(attachment) {
			$('#wpps-white-label-menu-icon-id').val(attachment.id);
			whiteLabelMedia.menuIconUrl = attachment.url || '';
			setWhiteLabelPreview($('#wpps-white-label-menu-icon-preview'), $('#wpps-white-label-menu-icon-remove'), attachment.url, 56, 'dashicons-admin-plugins');
			updateWhiteLabelPreview();
		});
	});

	$('#wpps-white-label-menu-icon-remove').on('click', function() {
		$('#wpps-white-label-menu-icon-id').val('0');
		whiteLabelMedia.menuIconUrl = '';
		setWhiteLabelPreview($('#wpps-white-label-menu-icon-preview'), $(this), '', 56, 'dashicons-admin-plugins');
		updateWhiteLabelPreview();
	});

	$('#wpps-white-label-save').on('click', function() {
		var $btn = $(this);
		var hasAgency = config.whiteLabel && config.whiteLabel.hasAgencyLicense;
		if ($('#wpps-white-label-enabled').is(':checked') && !hasAgency) {
			showNotice(strings.agencyRequired || 'An Agency license is required to enable white-label branding.', 'error');
			return;
		}
		$btn.prop('disabled', true).addClass('is-busy');
		$.post(ajaxurl, {
			action: 'wp_powersuite_save_white_label',
			nonce: nonce,
			white_label: collectWhiteLabelPayload()
		}).done(function(res) {
			if (res.success) {
				if (res.data) {
					if (res.data.logoUrl) {
						whiteLabelMedia.logoUrl = res.data.logoUrl;
					}
					if (res.data.menuIconUrl) {
						whiteLabelMedia.menuIconUrl = res.data.menuIconUrl;
					}
					if (res.data.whiteLabelDirectUrl) {
						$('#wpps-white-label-settings-direct-url').val(res.data.whiteLabelDirectUrl);
					}
					if (res.data.licenseDirectUrl) {
						$('#wpps-white-label-license-direct-url').val(res.data.licenseDirectUrl);
					}
					if (res.data.hideWhiteLabelTab && !whiteLabelConfig.standalonePage) {
						showNotice(res.data.message || strings.brandingSaved || strings.saved, 'success');
						window.setTimeout(function() {
							window.location.href = res.data.whiteLabelDirectUrl || whiteLabelConfig.directUrls.whiteLabel;
						}, 900);
						return;
					}
				}
				updateWhiteLabelPreview();
				showNotice(res.data && res.data.message ? res.data.message : (strings.brandingSaved || strings.saved), 'success');
				showFeedback($btn, strings.saved, true);
			} else {
				showNotice(res.data && res.data.message ? res.data.message : strings.saveFailed, 'error');
			}
		}).fail(function() {
			showNotice(strings.requestFailed, 'error');
		}).always(function() {
			$btn.prop('disabled', false).removeClass('is-busy');
		});
	});

	$('#wpps-white-label-reset').on('click', function() {
		var $btn = $(this);
		confirmAction(strings.resetWhiteLabelConfirm || 'Reset all white-label fields to defaults?').then(function(ok) {
			if (!ok) {
				return;
			}
			$btn.prop('disabled', true).addClass('is-busy');
			$.post(ajaxurl, {
				action: 'wp_powersuite_reset_white_label',
				nonce: nonce
			}).done(function(res) {
				if (res.success) {
					showNotice(res.data && res.data.message ? res.data.message : (strings.whiteLabelReset || strings.saved), 'success');
					window.location.reload();
				} else {
					showNotice(res.data && res.data.message ? res.data.message : strings.saveFailed, 'error');
				}
			}).fail(function() {
				showNotice(strings.requestFailed, 'error');
			}).always(function() {
				$btn.prop('disabled', false).removeClass('is-busy');
			});
		});
	});

	$('.wpps-white-label-hide-toggle').on('change', function() {
		var $cb = $(this);
		if (!$cb.is(':checked')) {
			return;
		}
		var msg = $cb.data('confirmMessage') || '';
		$cb.prop('checked', false);
		confirmAction(msg).then(function(ok) {
			if (ok) {
				$cb.prop('checked', true);
			}
		});
	});

	$(document).on('click', '.wpps-white-label-copy-url', function() {
		var targetId = $(this).data('copyTarget');
		var $input = $('#' + targetId);
		if (!$input.length) {
			return;
		}
		var value = $input.val() || '';
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(value).then(function() {
				showNotice(strings.linkCopied || 'Link copied.', 'success');
			}).catch(function() {
				showNotice(strings.copyFailed || 'Could not copy link.', 'error');
			});
			return;
		}
		$input.trigger('focus').trigger('select');
		try {
			document.execCommand('copy');
			showNotice(strings.linkCopied || 'Link copied.', 'success');
		} catch (err) {
			showNotice(strings.copyFailed || 'Could not copy link.', 'error');
		}
	});

	$('#wpps-quick-launcher-shortcut').on('change', function() {
		var val = $(this).val();
		var $select = $(this);
		$select.prop('disabled', true);
		$.post(ajaxurl, { action: 'wp_powersuite_save_quick_launcher_shortcut', nonce: nonce, shortcut: val })
			.done(function(res) {
				if (res.success) {
					if (window.wpPowerSuite) {
						window.wpPowerSuite.quickLauncherShortcut = val;
					}
					showFeedback($select, strings.saved, true);
				} else {
					showFeedback($select, res.data && res.data.message ? res.data.message : strings.saveFailed, false);
				}
			})
			.fail(function() {
				showFeedback($select, strings.requestFailed, false);
			})
			.always(function() {
				$select.prop('disabled', false);
			});
	});

	$('#wpps-enable-performance-monitor').on('change', function() {
		var $checkbox = $(this);
		var enabled = $checkbox.is(':checked');
		var $linkRow = $('#wpps-performance-monitor-link-row');
		$checkbox.prop('disabled', true);
		$.post(ajaxurl, {
			action: 'wp_powersuite_save_performance_monitor',
			nonce: nonce,
			enabled: enabled ? 1 : 0
		}).done(function(res) {
			if (res.success) {
				if (enabled && res.data && res.data.url) {
					$('#wpps-performance-monitor-link').attr('href', res.data.url);
					$linkRow.show();
				} else {
					$linkRow.hide();
				}
				showFeedback($checkbox.closest('.wpps-settings-row'), res.data && res.data.message ? res.data.message : strings.saved, true);
			} else {
				$checkbox.prop('checked', !enabled);
				showFeedback($checkbox.closest('.wpps-settings-row'), res.data && res.data.message ? res.data.message : strings.saveFailed, false);
			}
		}).fail(function() {
			$checkbox.prop('checked', !enabled);
			showFeedback($checkbox.closest('.wpps-settings-row'), strings.requestFailed, false);
		}).always(function() {
			$checkbox.prop('disabled', false);
		});
	});

	var appearanceSaveTimer = null;
	var appearanceSaveXhr = null;
	var appearanceConfig = config.appearance || {};
	var defaultBrandColor = appearanceConfig.defaultBrandColor || '#57BBB6';
	var appearanceStyleEl = null;

	function normalizeHexColor(value) {
		var color = (value || '').trim();
		if (/^#[0-9A-Fa-f]{3}$/.test(color)) {
			return ('#' + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3)).toUpperCase();
		}
		if (/^#[0-9A-Fa-f]{6}$/.test(color)) {
			return color.toUpperCase();
		}
		return '';
	}

	function applyAppearanceCss(cssText) {
		if (!appearanceStyleEl) {
			appearanceStyleEl = document.getElementById('wpps-appearance-vars');
			if (!appearanceStyleEl) {
				appearanceStyleEl = document.createElement('style');
				appearanceStyleEl.id = 'wpps-appearance-vars';
				document.head.appendChild(appearanceStyleEl);
			}
		}
		appearanceStyleEl.textContent = cssText || '';
	}

	function toggleCustomBrandColorRow() {
		var custom = $('#wpps-interface-color-mode').val() === 'custom_brand';
		$('#wpps-custom-brand-color-row').toggle(custom);
	}

	function saveInterfaceAppearance($feedbackTarget) {
		var mode = $('#wpps-interface-color-mode').val();
		var color = normalizeHexColor($('#wpps-custom-brand-color').val()) || normalizeHexColor($('#wpps-custom-brand-color-picker').val()) || defaultBrandColor;
		$('#wpps-custom-brand-color').val(color);
		$('#wpps-custom-brand-color-picker').val(color);

		if (appearanceSaveXhr && appearanceSaveXhr.readyState !== 4) {
			appearanceSaveXhr.abort();
		}

		appearanceSaveXhr = $.post(ajaxurl, {
			action: 'wp_powersuite_save_interface_appearance',
			nonce: nonce,
			interface_color_mode: mode,
			custom_brand_color: color
		}).done(function(res) {
			if (res.success) {
				applyAppearanceCss(res.data && res.data.appearance_css ? res.data.appearance_css : '');
				showFeedback($feedbackTarget, res.data && res.data.message ? res.data.message : strings.saved, true);
			} else {
				showFeedback($feedbackTarget, res.data && res.data.message ? res.data.message : strings.saveFailed, false);
			}
		}).fail(function(_xhr, status) {
			if (status === 'abort') {
				return;
			}
			showFeedback($feedbackTarget, strings.requestFailed, false);
		});

		return appearanceSaveXhr;
	}

	function queueInterfaceAppearanceSave($feedbackTarget) {
		clearTimeout(appearanceSaveTimer);
		appearanceSaveTimer = setTimeout(function() {
			saveInterfaceAppearance($feedbackTarget);
		}, 600);
	}

	$('#wpps-interface-color-mode').on('change', function() {
		var $select = $(this);
		toggleCustomBrandColorRow();
		$select.prop('disabled', true);
		saveInterfaceAppearance($select.closest('.wpps-settings-row')).always(function() {
			$select.prop('disabled', false);
		});
	});

	$('#wpps-custom-brand-color-picker').on('change', function() {
		queueInterfaceAppearanceSave($(this).closest('.wpps-settings-row'));
	});

	$('#wpps-custom-brand-color').on('blur', function() {
		queueInterfaceAppearanceSave($(this).closest('.wpps-settings-row'));
	}).on('keydown', function(e) {
		if (e.key === 'Enter') {
			e.preventDefault();
			$(this).blur();
		}
	});

	$('#wpps-custom-brand-color-row').on('click', '.wpps-color-reset', function() {
		var def = $(this).data('default-color') || defaultBrandColor;
		$('#wpps-custom-brand-color-picker').val(def);
		$('#wpps-custom-brand-color').val(def).trigger('change');
	});

	$('#wpps-clear-cache').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true);
		$.post(ajaxurl, { action: 'wp_powersuite_clear_cache', nonce: nonce })
			.done(function(res) {
				if (res.success) {
					showFeedback($btn, res.data && res.data.message ? res.data.message : strings.done, true);
				} else {
					showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
				}
				$btn.prop('disabled', false);
			})
			.fail(function() {
				$btn.prop('disabled', false);
				showNotice(strings.requestFailed, 'error');
			});
	});

	$('#wpps-clear-inactive-data').on('click', function() {
		var $btn = $(this);
		confirmAction(strings.clearInactiveConfirm).then(function(ok) {
			if (!ok) {
				return;
			}
			$btn.prop('disabled', true);
			$.post(ajaxurl, { action: 'wp_powersuite_clear_inactive_data', nonce: nonce })
				.done(function(res) {
					if (res.success) {
						showFeedback($btn, res.data && res.data.message ? res.data.message : strings.done, true);
					} else {
						showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
					}
					$btn.prop('disabled', false);
				})
				.fail(function() {
					$btn.prop('disabled', false);
					showNotice(strings.requestFailed, 'error');
				});
		});
	});

	$('#wpps-clear-all-data').on('click', function() {
		var $btn = $(this);
		confirmAction(strings.clearAllConfirm).then(function(firstOk) {
			if (!firstOk) {
				return;
			}
			return confirmTypedAction(
				strings.clearAllConfirm,
				strings.clearAllTypeRequired || 'DELETE',
				strings.clearAllTypePrompt || 'Type DELETE below to permanently delete all plugin data.'
			);
		}).then(function(secondOk) {
			if (!secondOk) {
				return;
			}
			$btn.prop('disabled', true);
			$.post(ajaxurl, { action: 'wp_powersuite_clear_all_data', nonce: nonce })
				.done(function(res) {
					if (res.success) {
						window.location.href = baseUrl + (baseUrl.indexOf('?') >= 0 ? '&' : '?') + 'wpps_notice=cleared_all';
					} else {
						$btn.prop('disabled', false);
						showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
					}
				})
				.fail(function() {
					$btn.prop('disabled', false);
					showNotice(strings.requestFailed, 'error');
				});
		});
	});

	$('#wp-powersuite-reset-defaults').on('click', function() {
		var $btn = $(this);
		if ($btn.data('confirm')) {
			return;
		}
		confirmAction(strings.resetConfirm).then(function(ok) {
			if (!ok) {
				return;
			}
			$btn.prop('disabled', true).addClass('is-busy');
			$.post(ajaxurl, { action: 'wp_powersuite_reset_to_defaults', nonce: nonce })
				.done(function(res) {
					if (res.success) {
						window.location.href = baseUrl + (baseUrl.indexOf('?') >= 0 ? '&' : '?') + 'wpps_notice=reset_defaults';
					} else {
						$btn.prop('disabled', false).removeClass('is-busy');
						showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
					}
				})
				.fail(function() {
					$btn.prop('disabled', false).removeClass('is-busy');
					showNotice(strings.requestFailedRetry, 'error');
				});
		});
	});

	$('#wpps-config-save-preset').on('click', function() {
		var name = $('#wpps-config-preset-name').val().trim();
		if (!name) {
			showNotice(strings.presetNameRequired, 'error');
			return;
		}
		var $btn = $(this);
		$btn.prop('disabled', true);
		$.post(ajaxurl, { action: 'wp_powersuite_config_save_preset', nonce: nonce, name: name })
			.done(function(res) {
				if (res.success) {
					window.location.reload();
				} else {
					$btn.prop('disabled', false);
					showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
				}
			})
			.fail(function() {
				$btn.prop('disabled', false);
				showNotice(strings.requestFailedRetry, 'error');
			});
	});

	$(document).on('click', '.wpps-config-load-preset', function() {
		var id = $(this).data('id');
		var $btn = $(this);
		confirmAction(strings.loadPresetConfirm).then(function(ok) {
			if (!ok) {
				return;
			}
			$btn.prop('disabled', true);
			$.post(ajaxurl, { action: 'wp_powersuite_config_load_preset', nonce: nonce, id: id, merge: 0 })
				.done(function(res) {
					if (res.success) {
						window.location.href = baseUrl + (baseUrl.indexOf('?') >= 0 ? '&' : '?') + 'wpps_notice=preset_loaded&tab=configurations';
					} else {
						$btn.prop('disabled', false);
						showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
					}
				})
				.fail(function() {
					$btn.prop('disabled', false);
					showNotice(strings.requestFailedRetry, 'error');
				});
		});
	});

	$(document).on('click', '.wpps-config-delete-preset', function() {
		var id = $(this).data('id');
		var $row = $(this).closest('tr');
		confirmAction(strings.deletePresetConfirm).then(function(ok) {
			if (!ok) {
				return;
			}
			$.post(ajaxurl, { action: 'wp_powersuite_config_delete_preset', nonce: nonce, id: id })
				.done(function(res) {
					if (res.success) {
						$row.fadeOut();
					} else {
						showNotice(res.data && res.data.message ? res.data.message : strings.errorOccurred, 'error');
					}
				});
		});
	});

	$('#wpps-config-export').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true);
		$.post(ajaxurl, { action: 'wp_powersuite_config_export', nonce: nonce })
			.done(function(res) {
				if (res.success && res.data && res.data.config) {
					var blob = new Blob([JSON.stringify(res.data.config, null, 2)], { type: 'application/json' });
					var a = document.createElement('a');
					a.href = URL.createObjectURL(blob);
					a.download = 'wp-powersuite-config-' + Date.now() + '.json';
					a.click();
					URL.revokeObjectURL(a.href);
				} else {
					showNotice(res.data && res.data.message ? res.data.message : strings.exportFailed, 'error');
				}
				$btn.prop('disabled', false);
			})
			.fail(function() {
				$btn.prop('disabled', false);
				showNotice(strings.requestFailedRetry, 'error');
			});
	});

	$('#wpps-config-import-file').on('change', function() {
		$('#wpps-config-import').prop('disabled', !this.files || this.files.length === 0);
	});

	$('#wpps-config-import').on('click', function() {
		var file = document.getElementById('wpps-config-import-file').files[0];
		if (!file) {
			return;
		}
		var merge = $('input[name="wpps_config_import_mode"]:checked').val() === 'merge';
		var $btn = $(this);
		$btn.prop('disabled', true);
		var reader = new FileReader();
		reader.onload = function() {
			try {
				var configData = JSON.parse(reader.result);
				$.post(ajaxurl, { action: 'wp_powersuite_config_import', nonce: nonce, config: JSON.stringify(configData), merge: merge ? 1 : 0 })
					.done(function(res) {
						if (res.success) {
							window.location.href = baseUrl + (baseUrl.indexOf('?') >= 0 ? '&' : '?') + 'wpps_notice=imported&tab=configurations';
						} else {
							showNotice(res.data && res.data.message ? res.data.message : strings.importFailed, 'error');
						}
						$btn.prop('disabled', false);
					})
					.fail(function() {
						$btn.prop('disabled', false);
						showNotice(strings.requestFailedRetry, 'error');
					});
			} catch (e) {
				showNotice(strings.invalidJson, 'error');
				$btn.prop('disabled', false);
			}
		};
		reader.readAsText(file);
	});

	function collectAiConnectionsPayload() {
		var defaultProvider = $('input[name="wpps_ai_connections_default_provider"]:checked').val() || 'openai';
		var payload = {
			provider: defaultProvider,
			use_network_api_keys: $('#wpps-ai-connections-use-network').is(':checked') ? 1 : 0
		};

		$('.wpps-ai-connections-site-key').each(function() {
			var field = String($(this).data('field') || '');
			if (field) {
				payload[field] = $(this).val() || '';
			}
		});

		$('.wpps-ai-connections-network-key').each(function() {
			var field = String($(this).data('field') || '');
			if (field) {
				payload['network_' + field] = $(this).val() || '';
			}
		});

		return payload;
	}

	function clearAiConnectionKeyInputs() {
		$('.wpps-ai-connections-site-key, .wpps-ai-connections-network-key').val('');
	}

	$('#wpps-ai-connections-save').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true).addClass('is-busy');
		$.post(ajaxurl, {
			action: 'wp_powersuite_save_ai_connections',
			nonce: nonce,
			ai_connections: collectAiConnectionsPayload()
		}).done(function(res) {
			if (res.success) {
				clearAiConnectionKeyInputs();
				showNotice(res.data && res.data.message ? res.data.message : (strings.aiConnectionsSaved || strings.saved), 'success');
				showFeedback($btn, strings.saved, true);
			} else {
				showNotice(res.data && res.data.message ? res.data.message : strings.saveFailed, 'error');
			}
		}).fail(function() {
			showNotice(strings.requestFailed, 'error');
		}).always(function() {
			$btn.prop('disabled', false).removeClass('is-busy');
		});
	});

	$(document).on('click', '.wpps-ai-connections-test-provider', function() {
		var $btn = $(this);
		var provider = String($btn.data('provider') || 'openai');
		var keyInputId = String($btn.data('keyInput') || '');
		var $result = $('#wpps-ai-connections-test-result-' + provider);
		var apiKey = keyInputId ? ($('#' + keyInputId).val() || '') : '';

		$btn.prop('disabled', true);
		$result.removeClass('is-success is-error').text(strings.testingConnection || 'Testing…');
		$.post(ajaxurl, {
			action: 'wp_powersuite_test_ai_connection',
			nonce: nonce,
			provider: provider,
			api_key: apiKey
		}).done(function(res) {
			if (res.success) {
				$result.addClass('is-success').text(res.data && res.data.message ? res.data.message : (strings.connectionOk || 'Connection successful.'));
			} else {
				$result.addClass('is-error').text(res.data && res.data.message ? res.data.message : strings.connectionFailed);
			}
		}).fail(function() {
			$result.addClass('is-error').text(strings.requestFailed);
		}).always(function() {
			$btn.prop('disabled', false);
		});
	});
});
