/**
 * ConvesioPay WC Subscriptions – "Update cards on file" (Customer Card Manager).
 * My Account → Subscriptions list and single subscription view.
 */
(function () {
	'use strict';

	var dialogEl = null;
	var lastFocusedEl = null;

	function init() {
		if (typeof jQuery === 'undefined') {
			return;
		}
		var $ = jQuery;
		var config = window.peachpayConvesioPayCardManager || {};
		var ajaxUrl = config.ajaxUrl || (typeof wp !== 'undefined' && wp.ajax && wp.ajax.settings && wp.ajax.settings.url) || '';
		var nonce = config.nonce || '';

		if (!ajaxUrl || !nonce) {
			return;
		}

		ensureSuccessDialog(config);

		// Selector must match class in hooks.php (list button + wcs_view_subscription_actions key).
		$(document).on('click', '.peachpay-convesiopay-subscriptions-update-cards-on-file-btn, [class*="peachpay-convesiopay-subscriptions-update-cards-on-file"]', function (e) {
			e.preventDefault();
			var $btn = $(this);
			if ($btn.prop('disabled')) {
				return;
			}
			// On view-subscription page the button has no data attr; use global subscriptionId from config.
			var subscriptionId = $btn.data('subscription-id') || config.subscriptionId || '';

			lastFocusedEl = $btn[0];
			$btn.prop('disabled', true).addClass('loading');
			var originalText = $btn.text();
			$btn.text(config.sendingText || 'Sending…');

			$.ajax({
				url: ajaxUrl,
				type: 'POST',
				data: {
					action: 'peachpay_convesiopay_request_card_manager_link',
					nonce: nonce,
					subscription_id: subscriptionId
				}
			})
				.done(function (res) {
					if (res && res.success) {
						showCardManagerSuccessDialog(config, res.data && res.data.message ? res.data.message : '');
					} else {
						showNotice((res && res.data && res.data.message) ? res.data.message : 'Request failed.', 'error');
					}
				})
				.fail(function (xhr, status, err) {
					var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message)
						? xhr.responseJSON.data.message
						: (err || 'Request failed. Please try again.');
					showNotice(msg, 'error');
				})
				.always(function () {
					$btn.prop('disabled', false).removeClass('loading').text(originalText);
				});
		});

		// Card for renewals: save selection when user picks a different card
		$(document).on('change', '.peachpay-convesiopay-subscription-card-radio', function () {
			var $radio = $(this);
			var subscriptionId = $radio.data('subscription-id');
			var nonce = $radio.data('nonce');
			var cardToken = $radio.val();
			var action = config.saveCardAction || 'peachpay_convesiopay_save_subscription_card';
			if (!subscriptionId || !nonce) {
				return;
			}
			lastFocusedEl = $radio[0];

			// Show saving state: dim the list and add a spinner next to the selected label.
			var $list = $radio.closest('.peachpay-convesiopay-subscription-cards-list');
			var $spinner = $('<span class="peachpay-convesiopay-card-saving-spinner" aria-hidden="true"></span>');
			$list.addClass('peachpay-convesiopay-subscription-cards-list--saving');
			$radio.closest('label').append($spinner);

			$.ajax({
				url: ajaxUrl,
				type: 'POST',
				data: {
					action: action,
					nonce: nonce,
					subscription_id: subscriptionId,
					card_token: cardToken
				}
			})
				.done(function (res) {
					if (res && res.success) {
						showCardSavedSuccessDialog(config);
					} else {
						showNotice((res && res.data && res.data.message) ? res.data.message : 'Update failed.', 'error');
					}
				})
				.fail(function (xhr, status, err) {
					var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message)
						? xhr.responseJSON.data.message
						: (err || 'Update failed. Please try again.');
					showNotice(msg, 'error');
				})
				.always(function () {
					$spinner.remove();
					$list.removeClass('peachpay-convesiopay-subscription-cards-list--saving');
				});
		});
	}

	function ensureSuccessDialog(config) {
		if (dialogEl) {
			return;
		}

		var title = config.successTitle || 'Check your email';
		var closeText = config.closeText || 'Got it';
		var closeLabel = config.closeLabel || 'Close';

		dialogEl = document.createElement('div');
		dialogEl.className = 'peachpay-convesiopay-card-manager-dialog';
		dialogEl.setAttribute('role', 'dialog');
		dialogEl.setAttribute('aria-modal', 'true');
		dialogEl.setAttribute('aria-labelledby', 'peachpay-convesiopay-card-manager-dialog-title');
		dialogEl.hidden = true;
		dialogEl.innerHTML =
			'<div class="peachpay-convesiopay-card-manager-dialog__backdrop" data-dismiss="true"></div>' +
			'<div class="peachpay-convesiopay-card-manager-dialog__panel">' +
				'<button type="button" class="peachpay-convesiopay-card-manager-dialog__close" data-dismiss="true" aria-label="' + escapeAttr(closeLabel) + '">&times;</button>' +
				'<h2 id="peachpay-convesiopay-card-manager-dialog-title" class="peachpay-convesiopay-card-manager-dialog__title"></h2>' +
				'<div class="peachpay-convesiopay-card-manager-dialog__body"></div>' +
				'<div class="peachpay-convesiopay-card-manager-dialog__actions">' +
					'<button type="button" class="button peachpay-convesiopay-card-manager-dialog__confirm" data-dismiss="true"></button>' +
				'</div>' +
			'</div>';

		document.body.appendChild(dialogEl);

		dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__title').textContent = title;
		dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__confirm').textContent = closeText;

		dialogEl.addEventListener('click', function (event) {
			if (event.target && event.target.getAttribute('data-dismiss') === 'true') {
				closeCardManagerSuccessDialog();
			}
		});

		document.addEventListener('keydown', onDialogKeydown);
	}

	function onDialogKeydown(event) {
		if (!dialogEl || dialogEl.hidden) {
			return;
		}
		if (event.key === 'Escape') {
			event.preventDefault();
			closeCardManagerSuccessDialog();
		}
	}

	function showCardManagerSuccessDialog(config, apiMessage) {
		ensureSuccessDialog(config);

		var titleEl = dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__title');
		var bodyEl = dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__body');
		var confirmBtn = dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__confirm');

		titleEl.textContent = config.successTitle || 'Check your email';
		bodyEl.innerHTML = buildSuccessBodyHtml(config, apiMessage);

		dialogEl.hidden = false;
		document.body.classList.add('peachpay-convesiopay-card-manager-dialog--open');

		if (confirmBtn) {
			confirmBtn.focus();
		}
	}

	function closeCardManagerSuccessDialog() {
		if (!dialogEl || dialogEl.hidden) {
			return;
		}

		dialogEl.hidden = true;
		document.body.classList.remove('peachpay-convesiopay-card-manager-dialog--open');

		if (lastFocusedEl && typeof lastFocusedEl.focus === 'function') {
			lastFocusedEl.focus();
		}
	}

	function showCardSavedSuccessDialog(config) {
		ensureSuccessDialog(config);

		var titleEl  = dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__title');
		var bodyEl   = dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__body');
		var confirmBtn = dialogEl.querySelector('.peachpay-convesiopay-card-manager-dialog__confirm');

		titleEl.textContent = config.savedTitle || 'Card updated';
		bodyEl.innerHTML = '<p>' + escapeHtml(config.savedIntro || 'Your renewal card has been updated.') + '</p>';

		dialogEl.hidden = false;
		document.body.classList.add('peachpay-convesiopay-card-manager-dialog--open');

		if (confirmBtn) {
			confirmBtn.focus();
		}
	}

	function buildSuccessBodyHtml(config, apiMessage) {
		var paragraphs = [];

		if (config.successIntro) {
			paragraphs.push(config.successIntro);
		}

		var steps = config.successSteps;
		if (Array.isArray(steps)) {
			steps.forEach(function (step) {
				if (step) {
					paragraphs.push(step);
				}
			});
		}

		if (!paragraphs.length && apiMessage) {
			paragraphs.push(apiMessage);
		}

		if (!paragraphs.length) {
			paragraphs.push('A secure link to update your cards has been sent to your email.');
		}

		return paragraphs.map(function (text) {
			return '<p>' + escapeHtml(text) + '</p>';
		}).join('');
	}

	function showNotice(message, type) {
		var $ = jQuery;
		var noticeClass = type === 'success' ? 'woocommerce-message' : 'woocommerce-error';
		var $wrapper = $('.woocommerce-notices-wrapper').first();
		if (!$wrapper.length) {
			$wrapper = $('.woocommerce-MyAccount-content').first();
		}
		if (!$wrapper.length) {
			$wrapper = $('.woocommerce').first();
		}
		if (!$wrapper.length) {
			$wrapper = $('main, .content').first();
		}
		if (!$wrapper.length) {
			$wrapper = $('body');
		}
		var $notice = $('<div class="' + noticeClass + '" role="alert">' + escapeHtml(message) + '</div>');
		$wrapper.prepend($notice);
		if (type === 'success') {
			$notice[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		}
		setTimeout(function () {
			$notice.fadeOut(300, function () {
				$(this).remove();
			});
		}, 6000);
	}

	function escapeHtml(text) {
		var div = document.createElement('div');
		div.textContent = text;
		return div.innerHTML;
	}

	function escapeAttr(text) {
		return String(text)
			.replace(/&/g, '&amp;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#39;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;');
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
