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

	if (!$('#wpps-ai-connections-save').length) {
		return;
	}

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

	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 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('');
	}

	function applyProviderStatus($status, status) {
		$status.removeClass('is-connected is-disconnected is-saved is-failed');

		switch (status) {
			case 'verified':
				$status.addClass('is-connected').text(strings.aiConnected || 'Connected');
				break;
			case 'saved':
				$status.addClass('is-saved').text(strings.aiKeySaved || 'Key saved');
				break;
			case 'failed':
				$status.addClass('is-failed').text(strings.aiInvalidKey || 'Invalid key');
				break;
			default:
				$status.addClass('is-disconnected').text(strings.aiNotConnected || 'Not connected');
		}
	}

	function updateAiConnectionStatuses(statusMap, siteKeyMap, networkKeyMap) {
		if (!statusMap || typeof statusMap !== 'object') {
			return;
		}

		$.each(statusMap, function(providerId, status) {
			var $section = $('.wpps-ai-connections-providers:not(.wpps-ai-connections-providers--network) .wpps-ai-connections-provider[data-provider="' + providerId + '"]');
			var $status = $section.find('.wpps-ai-connections-provider__status').first();
			if ($status.length) {
				applyProviderStatus($status, status);
			}

			var $input = $section.find('.wpps-ai-connections-site-key').first();
			if ($input.length) {
				var hasSiteKey = siteKeyMap && siteKeyMap[providerId];
				if (hasSiteKey) {
					$input.attr('placeholder', '••••••••••••••••');
				} else if (status === 'none') {
					$input.attr('placeholder', $input.data('emptyPlaceholder') || '');
				}
			}

			if (siteKeyMap && Object.prototype.hasOwnProperty.call(siteKeyMap, providerId)) {
				var $remove = $section.find('.wpps-ai-connections-remove-key[data-scope="site"]');
				if ($remove.length) {
					$remove.closest('.wpps-ai-connections-key-actions').toggle(!!siteKeyMap[providerId]);
				}
			}

			if (networkKeyMap && Object.prototype.hasOwnProperty.call(networkKeyMap, providerId)) {
				var $networkSection = $('.wpps-ai-connections-providers--network .wpps-ai-connections-provider[data-provider="' + providerId + '"]');
				var $networkRemove = $networkSection.find('.wpps-ai-connections-remove-key[data-scope="network"]');
				if ($networkRemove.length) {
					$networkRemove.closest('.wpps-ai-connections-key-actions').toggle(!!networkKeyMap[providerId]);
				}
				var $networkInput = $networkSection.find('.wpps-ai-connections-network-key');
				if ($networkInput.length) {
					$networkInput.attr('placeholder', networkKeyMap[providerId] ? '••••••••••••••••' : ($networkInput.data('emptyPlaceholder') || ''));
				}
			}
		});
	}

	function updateAiConnectionsResponse(data) {
		if (!data || !data.ai_connections) {
			return;
		}

		updateAiConnectionStatuses(
			data.ai_connections.provider_status,
			data.ai_connections.provider_has_site_key,
			data.ai_connections.provider_has_network_key
		);
	}

	function saveAiConnectionsPayload(extraPayload, $feedbackBtn) {
		var payload = $.extend({}, collectAiConnectionsPayload(), extraPayload || {});
		var $btn = $feedbackBtn && $feedbackBtn.length ? $feedbackBtn : $('#wpps-ai-connections-save');

		$btn.prop('disabled', true).addClass('is-busy');
		return $.post(ajaxurl, {
			action: 'wp_powersuite_save_ai_connections',
			nonce: nonce,
			ai_connections: payload
		}).done(function(res) {
			if (res.success) {
				clearAiConnectionKeyInputs();
				updateAiConnectionsResponse(res.data);
				showNotice(res.data && res.data.message ? res.data.message : (strings.aiConnectionsSaved || strings.saved), 'success');
				if ($feedbackBtn && $feedbackBtn.length) {
					showFeedback($feedbackBtn, 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-ai-connections-save').on('click', function() {
		saveAiConnectionsPayload({}, $(this));
	});

	$(document).on('click', '.wpps-ai-connections-remove-key', function() {
		var $btn = $(this);
		var field = String($btn.data('field') || '');
		var scope = String($btn.data('scope') || 'site');
		var confirmMessage = scope === 'network'
			? (strings.removeNetworkKeyConfirm || strings.removeKeyConfirm)
			: (strings.removeKeyConfirm || 'Remove the saved API key for this provider?');

		if (!field || !window.confirm(confirmMessage)) {
			return;
		}

		var extraPayload = scope === 'network'
			? { clear_network_keys: [field] }
			: { clear_keys: [field] };

		saveAiConnectionsPayload(extraPayload, $btn).done(function(res) {
			if (res.success) {
				showNotice(strings.keyRemoved || strings.saved, 'success');
			}
		});
	});

	$(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.'));
				if (res.data && res.data.provider_status) {
					var $status = $('.wpps-ai-connections-providers:not(.wpps-ai-connections-providers--network) .wpps-ai-connections-provider[data-provider="' + provider + '"] .wpps-ai-connections-provider__status').first();
					applyProviderStatus($status, res.data.provider_status);
				}
			} else {
				$result.addClass('is-error').text(res.data && res.data.message ? res.data.message : strings.connectionFailed);
				if (res.data && res.data.provider_status) {
					var $failedStatus = $('.wpps-ai-connections-providers:not(.wpps-ai-connections-providers--network) .wpps-ai-connections-provider[data-provider="' + provider + '"] .wpps-ai-connections-provider__status').first();
					applyProviderStatus($failedStatus, res.data.provider_status);
				}
			}
		}).fail(function() {
			$result.addClass('is-error').text(strings.requestFailed);
		}).always(function() {
			$btn.prop('disabled', false);
		});
	});
});
