/**
 * SiteStaffr Deactivation Modal
 *
 * Intercepts the "Deactivate" link on the Plugins page and shows a
 * confirmation dialog warning about active subscriptions.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.2.3
 */

(function() {
	'use strict';

	var data = window.sitestaffrDeactivationData;
	if (!data) {
		return;
	}

	var row = document.querySelector('tr[data-plugin="' + data.pluginBasename + '"]');
	if (!row) {
		return;
	}

	var deactivateLink = row.querySelector('.deactivate a');
	if (!deactivateLink) {
		return;
	}
	var targetHref = '';
	var modalController = null;

	function ensureModal() {
		var existing = document.getElementById('sitestaffr-deactivate-modal');
		if (existing) {
			return existing;
		}

		var i18n = data.i18n;

		var wrapper = document.createElement('div');
		wrapper.id = 'sitestaffr-deactivate-modal';
		wrapper.innerHTML =
			'<div class="sitestaffr-deactivate-card" role="dialog" aria-modal="true" aria-labelledby="sitestaffr-deactivate-title">' +
				'<div class="sitestaffr-deactivate-header" id="sitestaffr-deactivate-title">' +
					'<img class="sitestaffr-deactivate-logo" src="' + data.logoUrl + '" alt="SiteStaffr" onerror="this.style.display=\'none\'" />' +
					'<span class="sitestaffr-deact-header-spacer"></span>' +
					'<button type="button" class="sitestaffr-modal-close" data-sitestaffr-deact-close="1" aria-label="' + i18n.keepActive + '">' +
						'<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>' +
					'</button>' +
				'</div>' +
				'<div class="sitestaffr-deactivate-body">' +
					'<p class="sitestaffr-deact-warning">' + i18n.modalMessage + '</p>' +
					'<p class="sitestaffr-deactivate-description">' + i18n.modalDescription + '</p>' +
					'<div class="sitestaffr-deactivate-feedback sitestaffr-deact-hidden" data-sitestaffr-deact-feedback-wrap>' +
						'<label for="sitestaffr-deactivate-reason">' + i18n.feedbackLabel + '</label>' +
						'<select id="sitestaffr-deactivate-reason">' +
							'<option value="">' + i18n.selectReason + '</option>' +
							'<option value="low_usage">' + i18n.reasonLowUsage + '</option>' +
							'<option value="technical_issues">' + i18n.reasonTechnical + '</option>' +
							'<option value="missing_features">' + i18n.reasonMissingFeatures + '</option>' +
							'<option value="switching_service">' + i18n.reasonSwitching + '</option>' +
							'<option value="too_expensive">' + i18n.reasonExpensive + '</option>' +
							'<option value="other">' + i18n.reasonOther + '</option>' +
						'</select>' +
						'<textarea id="sitestaffr-deactivate-feedback" placeholder="' + i18n.feedbackPlaceholder + '"></textarea>' +
					'</div>' +
				'</div>' +
				'<div class="sitestaffr-deactivate-actions" data-sitestaffr-deact-actions-initial>' +
					'<button type="button" class="sitestaffr-deact-btn sitestaffr-deact-btn-cancel" data-sitestaffr-deact-close="1">' + i18n.keepActive + '</button>' +
					'<button type="button" class="sitestaffr-deact-btn sitestaffr-deact-btn-portal" data-sitestaffr-deact-portal-url="' + data.portalUrl + '">' + i18n.portalLabel + '</button>' +
					'<button type="button" class="sitestaffr-deact-btn sitestaffr-deact-btn-confirm" data-sitestaffr-deact-start-deactivate="1">' + i18n.confirmLabel + '</button>' +
				'</div>' +
				'<div class="sitestaffr-deactivate-actions sitestaffr-deact-hidden" data-sitestaffr-deact-actions-final>' +
					'<button type="button" class="sitestaffr-deact-btn sitestaffr-deact-btn-portal" data-sitestaffr-deact-portal-url="' + data.portalUrl + '">' + i18n.portalLabel + '</button>' +
					'<button type="button" class="sitestaffr-deact-btn sitestaffr-deact-btn-confirm" data-sitestaffr-deact-confirm="1">' + i18n.finalConfirmLabel + '</button>' +
				'</div>' +
			'</div>';

		document.body.appendChild(wrapper);

		// Chrome (Esc, backdrop, focus trap, focus-return) comes from the
		// shared component; is-open drives the stylesheet's display state.
		modalController = window.SiteStaffrModal
			? window.SiteStaffrModal.enhance(wrapper, {
				card: '.sitestaffr-deactivate-card',
				onOpen: function() {
					wrapper.classList.add('is-open');
				},
				onClose: function() {
					wrapper.classList.remove('is-open');
				}
			})
			: null;

		wrapper.addEventListener('click', function(event) {
			if (event.target.closest('[data-sitestaffr-deact-close="1"]') && modalController) {
				modalController.close();
			}
		});

		var feedbackWrap = wrapper.querySelector('[data-sitestaffr-deact-feedback-wrap]');
		var initialActions = wrapper.querySelector('[data-sitestaffr-deact-actions-initial]');
		var finalActions = wrapper.querySelector('[data-sitestaffr-deact-actions-final]');
		var reasonField = wrapper.querySelector('#sitestaffr-deactivate-reason');
		var detailsField = wrapper.querySelector('#sitestaffr-deactivate-feedback');
		var portalButtons = wrapper.querySelectorAll('.sitestaffr-deact-btn-portal');
		var startDeactivateBtn = wrapper.querySelector('[data-sitestaffr-deact-start-deactivate="1"]');
		var confirmBtn = wrapper.querySelector('[data-sitestaffr-deact-confirm="1"]');

		portalButtons.forEach(function(portalBtn) {
			portalBtn.addEventListener('click', function(event) {
				event.preventDefault();
				event.stopPropagation();
				var portalUrl = portalBtn.getAttribute('data-sitestaffr-deact-portal-url') || '';
				if (!portalUrl) {
					return;
				}

				var portalWindow = window.open(
					'',
					'sitestaffrBillingPortal',
					'width=980,height=760'
				);

				if (!portalWindow) {
					if (window.SiteStaffrModal) {
						window.SiteStaffrModal.alertDialog({
							message: 'Popup blocked. Please allow popups for this site and try again.'
						});
					}
					return;
				}

				try {
					portalWindow.opener = null;
				} catch (e) {}
				portalWindow.location = portalUrl;
			});
		});

		startDeactivateBtn.addEventListener('click', function(event) {
			event.preventDefault();
			feedbackWrap.classList.remove('sitestaffr-deact-hidden');
			initialActions.classList.add('sitestaffr-deact-hidden');
			finalActions.classList.remove('sitestaffr-deact-hidden');
			reasonField.focus();
		});

		confirmBtn.addEventListener('click', function(event) {
			event.preventDefault();
			var reason = (reasonField || {}).value || '';
			var details = (detailsField || {}).value || '';

			var submitAndProceed = function() {
				if (targetHref) {
					window.location.href = targetHref;
				}
			};

			if (!reason && !details.trim()) {
				submitAndProceed();
				return;
			}

			var xhr = new XMLHttpRequest();
			xhr.open('POST', data.ajaxUrl, true);
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					submitAndProceed();
				}
			};

			var params = new URLSearchParams();
			params.set('action', 'sitestaffr_submit_deactivation_feedback');
			params.set('nonce', data.feedbackNonce);
			params.set('reason', reason);
			params.set('details', details);
			xhr.send(params.toString());
		});

		return wrapper;
	}

	deactivateLink.addEventListener('click', function(event) {
		event.preventDefault();
		targetHref = deactivateLink.getAttribute('href') || '';
		var modal = ensureModal();
		var feedbackWrap = modal.querySelector('[data-sitestaffr-deact-feedback-wrap]');
		var initialActions = modal.querySelector('[data-sitestaffr-deact-actions-initial]');
		var finalActions = modal.querySelector('[data-sitestaffr-deact-actions-final]');
		var reasonField = modal.querySelector('#sitestaffr-deactivate-reason');
		var detailsField = modal.querySelector('#sitestaffr-deactivate-feedback');
		if (feedbackWrap && initialActions && finalActions) {
			feedbackWrap.classList.add('sitestaffr-deact-hidden');
			finalActions.classList.add('sitestaffr-deact-hidden');
			initialActions.classList.remove('sitestaffr-deact-hidden');
		}
		if (reasonField) {
			reasonField.value = '';
		}
		if (detailsField) {
			detailsField.value = '';
		}
		if (modalController) {
			modalController.open();
		} else {
			modal.classList.add('is-open');
		}
	});
})();
