/**
 * 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 = '';

	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="pe-deactivate-card" role="dialog" aria-modal="true" aria-labelledby="pe-deactivate-title">' +
				'<div class="pe-deactivate-header" id="pe-deactivate-title">' +
					'<img class="pe-deactivate-logo" src="' + data.logoUrl + '" alt="SiteStaffr" onerror="this.style.display=\'none\'" />' +
					'<span class="pe-header-spacer"></span>' +
					'<button type="button" class="pe-btn pe-btn-header-close" data-pe-close="1">' + i18n.keepActive + '</button>' +
				'</div>' +
				'<div class="pe-deactivate-body">' +
					'<p class="pe-warning">' + i18n.modalMessage + '</p>' +
					'<p class="pe-deactivate-description">' + i18n.modalDescription + '</p>' +
					'<div class="pe-deactivate-feedback pe-hidden" data-pe-feedback-wrap>' +
						'<label for="pe-deactivate-reason">' + i18n.feedbackLabel + '</label>' +
						'<select id="pe-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="pe-deactivate-feedback" placeholder="' + i18n.feedbackPlaceholder + '"></textarea>' +
					'</div>' +
				'</div>' +
				'<div class="pe-deactivate-actions" data-pe-actions-initial>' +
					'<button type="button" class="pe-btn pe-btn-portal" data-pe-portal-url="' + data.portalUrl + '">' + i18n.portalLabel + '</button>' +
					'<button type="button" class="pe-btn pe-btn-confirm" data-pe-start-deactivate="1">' + i18n.confirmLabel + '</button>' +
				'</div>' +
				'<div class="pe-deactivate-actions pe-hidden" data-pe-actions-final>' +
					'<button type="button" class="pe-btn pe-btn-portal" data-pe-portal-url="' + data.portalUrl + '">' + i18n.portalLabel + '</button>' +
					'<button type="button" class="pe-btn pe-btn-confirm" data-pe-confirm="1">' + i18n.finalConfirmLabel + '</button>' +
				'</div>' +
			'</div>';

		document.body.appendChild(wrapper);

		wrapper.addEventListener('click', function(event) {
			if (event.target === wrapper || event.target.closest('[data-pe-close="1"]')) {
				wrapper.classList.remove('is-open');
			}
		});

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

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

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

				if (!portalWindow) {
					alert('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('pe-hidden');
			initialActions.classList.add('pe-hidden');
			finalActions.classList.remove('pe-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());
		});

		document.addEventListener('keydown', function(event) {
			if (event.key === 'Escape') {
				wrapper.classList.remove('is-open');
			}
		});

		return wrapper;
	}

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