/**
 * Login Page Customizer — restore defaults action.
 */
(function () {
	'use strict';

	function getStrings() {
		return (window.wppsLpcAdmin && window.wppsLpcAdmin.strings) || {};
	}

	function showRestoreNotice(message, type) {
		var wrap = document.querySelector('.wpps-lpc-notice');
		if (!wrap) {
			return;
		}
		var noticeType = type === 'error' ? 'error' : 'success';
		var notice = document.createElement('div');
		notice.className = 'notice notice-' + noticeType + ' is-dismissible';
		notice.setAttribute('data-wpps-save-notice', 'true');
		var p = document.createElement('p');
		p.textContent = message == null ? '' : String(message);
		notice.appendChild(p);
		wrap.innerHTML = '';
		wrap.appendChild(notice);
	}

	function bindRestoreButton(btn) {
		if (!btn || btn.getAttribute('data-wpps-lpc-restore-bound')) {
			return;
		}
		btn.setAttribute('data-wpps-lpc-restore-bound', '1');
		var strings = getStrings();

		btn.addEventListener('click', function () {
			if (!window.wpPowerSuite || !window.wpPowerSuite.ajaxUrl) {
				return;
			}
			if (!window.confirm(strings.confirmRestore || 'Are you sure you want to restore default settings? This will remove all customizations.')) {
				return;
			}

			var originalText = btn.textContent;
			btn.disabled = true;
			btn.textContent = strings.restoring || 'Restoring...';

			var formData = new FormData();
			formData.append('action', 'wpps_restore_lpc_settings');
			formData.append('nonce', window.wpPowerSuite.nonce);

			fetch(window.wpPowerSuite.ajaxUrl, { method: 'POST', body: formData })
				.then(function (r) { return r.json(); })
				.then(function (data) {
					if (data.success) {
						window.location.reload();
						return;
					}
					btn.disabled = false;
					btn.textContent = originalText;
					showRestoreNotice(
						(data.data && data.data.message) ? data.data.message : (strings.error || 'Could not restore settings.'),
						'error'
					);
				})
				.catch(function () {
					btn.disabled = false;
					btn.textContent = originalText;
					showRestoreNotice(strings.error || 'Could not restore settings.', 'error');
				});
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		document.querySelectorAll('.wpps-restore-lpc').forEach(bindRestoreButton);
	});
})();
