(function($) {
	'use strict';

	function extractCycleOffsetFromUrl(url) {
		if (!url) {
			return 0;
		}
		try {
			var parsed = new URL(url, window.location.origin);
			var raw = parsed.searchParams.get('cycle_offset');
			var offset = parseInt(raw, 10);
			return Number.isFinite(offset) && offset >= 0 ? offset : 0;
		} catch (error) {
			return 0;
		}
	}

	function setLoading($container, isLoading) {
		if (!$container || !$container.length) {
			return;
		}
		$container.toggleClass('is-loading', !!isLoading);
	}

	function setCycleLoading(isLoading) {
		var $dashboard = $('.wrap.sitestaffr-usage-dashboard');
		if (!$dashboard.length) {
			return;
		}
		$dashboard.toggleClass('is-cycle-loading', !!isLoading);
	}

	function updateCycleView(offset, targetUrl) {
		var config = window.sitestaffrUsageDashboard || {};
		if (!config.pageUrl) {
			return;
		}

		var requestUrl = targetUrl || (config.pageUrl + '&cycle_offset=' + encodeURIComponent(offset));
		setCycleLoading(true);

		$.get(requestUrl)
			.done(function(responseHtml) {
				var $parsed = $('<div>').append($.parseHTML(responseHtml));
				var $incomingWrap = $parsed.find('.wrap.sitestaffr-usage-dashboard').first();
				var $currentWrap = $('.wrap.sitestaffr-usage-dashboard').first();
				if (!$incomingWrap.length || !$currentWrap.length) {
					return;
				}

				$currentWrap.replaceWith($incomingWrap);

				var appliedOffset = parseInt($incomingWrap.attr('data-cycle-offset'), 10);
				config.cycleOffset = Number.isFinite(appliedOffset) && appliedOffset >= 0 ? appliedOffset : 0;

				if (window.history && window.history.replaceState) {
					window.history.replaceState({}, '', config.pageUrl + '&cycle_offset=' + config.cycleOffset);
				}
			})
			.always(function() {
				setCycleLoading(false);
			});
	}

	function updateSection(section, channel, $filters) {
		var config = window.sitestaffrUsageDashboard || {};
		if (!config.ajaxUrl || !config.nonce) {
			return;
		}

		var $content = section === 'chart' ? $('#sitestaffr-chart-content') : $('#sitestaffr-recent-content');
		setLoading($content, true);

		$.post(config.ajaxUrl, {
			action: 'sitestaffr_filter_usage_data',
			nonce: config.nonce,
			section: section,
			channel: channel,
			cycle_offset: parseInt(config.cycleOffset, 10) || 0
		})
			.done(function(response) {
				if (!response || !response.success || !response.data || !response.data.html) {
					return;
				}
				$content.html(response.data.html);
				$filters.find('.sitestaffr-filter-pill').removeClass('is-active');
				$filters.find('.sitestaffr-filter-pill[data-channel="' + channel + '"]').addClass('is-active');
			})
			.always(function() {
				setLoading($content, false);
			});
	}

	$(document).on('click', '.sitestaffr-channel-filters .sitestaffr-filter-pill', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var $filters = $btn.closest('.sitestaffr-channel-filters');
		var section = String($filters.data('section') || '').toLowerCase();
		var channel = String($btn.data('channel') || 'all').toLowerCase();

		if (section !== 'chart' && section !== 'recent') {
			return;
		}
		if (channel !== 'all' && channel !== 'widget' && channel !== 'button') {
			channel = 'all';
		}

		updateSection(section, channel, $filters);
	});

	$(document).on('click', '.sitestaffr-cycle-nav-btn[href], .sitestaffr-cycle-option[href]', function(e) {
		e.preventDefault();
		var $link = $(this);
		if ($link.hasClass('is-disabled')) {
			return;
		}
		var href = String($link.attr('href') || '');
		var offset = extractCycleOffsetFromUrl(href);
		updateCycleView(offset, href);
	});

	// ====================================================================
	// Upgrade Plan Modal
	// ====================================================================

	// Plan color definitions — used for dynamic gradients in upgrade/downgrade modals
	var planColors = {
		trial:    { primary: '#8b5cf6', light: '#ede9fe', gradient: '#a78bfa' },
		starter:  { primary: '#3b82f6', light: '#dbeafe', gradient: '#60a5fa' },
		business: { primary: '#10b981', light: '#d1fae5', gradient: '#34d399' },
		pro:      { primary: '#059669', light: '#a7f3d0', gradient: '#047857' }
	};

	function getPlanColor(planName) {
		return planColors[planName] || planColors.trial;
	}

	var $upgradeModal = $('#sitestaffr-upgrade-modal');
	var $upgradeLoading = $('#sitestaffr-upgrade-loading');
	var $upgradeError = $('#sitestaffr-upgrade-error');
	var $upgradeErrorMessage = $('#sitestaffr-upgrade-error-message');
	var $upgradePreview = $('#sitestaffr-upgrade-preview');
	var $upgradeFooter = $('#sitestaffr-upgrade-footer');
	var $upgradeProcessing = $('#sitestaffr-upgrade-processing');
	var $upgradeConfirmBtn = $('#sitestaffr-upgrade-confirm');
	var upgradePendingPlan = null;
	var upgradeLastFocused = null;

	function openUpgradeModal(planName) {
		upgradeLastFocused = document.activeElement;
		upgradePendingPlan = planName;

		// Read target plan data from the clicked button
		var $btn = $('.sitestaffr-upgrade-plan-card[data-plan="' + planName + '"]');
		var targetLabel = $btn.data('plan-label') || planName;

		// Update heading
		$('#sitestaffr-upgrade-modal-heading').text('Upgrade to ' + targetLabel);

		// Reset states: show loading, hide everything else
		$upgradeLoading.show();
		$upgradeError.hide();
		$upgradePreview.hide();
		$upgradeFooter.hide();
		$upgradeProcessing.hide();
		$upgradeConfirmBtn.prop('disabled', false);

		$upgradeModal.show();
		$upgradeModal.find('.sitestaffr-modal').focus();
		$('body').css('overflow', 'hidden');

		// Fetch proration preview
		var config = window.sitestaffrUsageDashboard || {};
		$.post(config.ajaxUrl, {
			action: 'sitestaffr_preview_upgrade',
			nonce: config.upgradeNonce,
			plan_name: planName
		})
		.done(function(response) {
			$upgradeLoading.hide();

			if (!response || !response.success || !response.data) {
				var errMsg = (response && response.data && response.data.message)
					? response.data.message
					: 'Could not load upgrade preview. Please try again.';
				showUpgradeError(errMsg);
				return;
			}

			populateUpgradePreview(response.data, planName);
		})
		.fail(function() {
			$upgradeLoading.hide();
			showUpgradeError('Could not reach the server. Please check your connection and try again.');
		});
	}

	function showUpgradeError(message) {
		$upgradeErrorMessage.text(message);
		$upgradeError.show();
		$upgradeFooter.hide();
	}

	function formatUsdFromCents(valueCents) {
		var cents = parseInt(valueCents, 10);
		if (!Number.isFinite(cents)) {
			return '';
		}
		return '$' + (cents / 100).toFixed(2);
	}

	function formatDateLabel(dateRaw) {
		if (!dateRaw) {
			return '';
		}
		var parsed = new Date(dateRaw);
		if (!Number.isFinite(parsed.getTime())) {
			return String(dateRaw);
		}
		return parsed.toLocaleDateString(undefined, {
			year: 'numeric',
			month: 'short',
			day: 'numeric'
		});
	}

	function populateUpgradePreview(data, planName) {
		// Read context data
		var $context = $('.sitestaffr-upgrade-context');
		var currentPlanLabel = $context.data('current-plan-label') || 'Current Plan';
		var currentPlanKey = String($context.data('current-plan') || 'trial');
		var currentMinutes = parseInt($context.data('current-minutes'), 10) || 0;

		var $btn = $('.sitestaffr-upgrade-plan-card[data-plan="' + planName + '"]');
		var targetLabel = $btn.data('plan-label') || planName;
		var targetMinutes = parseInt($btn.data('plan-minutes'), 10) || 0;

		// Plan comparison — dynamic gradient from current to target plan color
		var fromColor = getPlanColor(currentPlanKey);
		var toColor = getPlanColor(planName);
		$('.sitestaffr-upgrade-plan-comparison').css(
			'background',
			'linear-gradient(135deg, ' + fromColor.light + ' 0%, ' + toColor.light + ' 100%)'
		).css('border-color', toColor.gradient);
		$('.sitestaffr-upgrade-plan-comparison .sitestaffr-upgrade-arrow').css('color', toColor.gradient);

		// Color the plan labels with colored background + white text
		$('#sitestaffr-upgrade-from-label').text(currentPlanLabel).css({
			'background': fromColor.primary,
			'color': '#fff',
			'padding': '3px 12px',
			'border-radius': '6px',
			'display': 'inline-block'
		});
		$('#sitestaffr-upgrade-to-label').text(targetLabel).css({
			'background': toColor.primary,
			'color': '#fff',
			'padding': '3px 12px',
			'border-radius': '6px',
			'display': 'inline-block'
		});

		// Proration summary (preferred fields: due_today_amount_*)
		var dueTodayDisplay = data.due_today_amount_display || data.proration_amount_display || '';
		if (dueTodayDisplay) {
			$('#sitestaffr-upgrade-due-today').text(dueTodayDisplay);
		} else if (typeof data.due_today_amount_cents === 'number' || typeof data.proration_amount === 'number') {
			$('#sitestaffr-upgrade-due-today').text(
				formatUsdFromCents(
					(typeof data.due_today_amount_cents === 'number') ? data.due_today_amount_cents : data.proration_amount
				)
			);
		} else {
			$('#sitestaffr-upgrade-due-today').text('$0.00');
		}

		var nextAmountDisplay = data.next_renewal_amount_display || '';
		var nextDate = data.next_renewal_date || '';
		var nextText = '';
		if (nextAmountDisplay) {
			nextText = nextAmountDisplay;
		} else if (typeof data.next_renewal_amount === 'number') {
			nextText = '$' + (data.next_renewal_amount / 100).toFixed(2) + '/mo';
		}
		if (nextDate) {
			$('#sitestaffr-upgrade-next-renewal-label').text('Next renewal (' + formatDateLabel(nextDate) + ')');
		} else {
			$('#sitestaffr-upgrade-next-renewal-label').text('Next renewal');
		}
		$('#sitestaffr-upgrade-next-renewal').text(nextText);

		// Minutes change
		var minutesFrom = data.current_minutes || currentMinutes;
		var minutesTo = data.new_minutes || targetMinutes;
		$('#sitestaffr-upgrade-minutes-text').text(
			minutesFrom + ' \u2192 ' + minutesTo + ' min/month \u2014 effective immediately'
		);

		// Billing cycle reset note (paid-to-paid upgrades only)
		var $cycleNote = $('#sitestaffr-upgrade-cycle-note');
		var $ctx2 = $('.sitestaffr-upgrade-context');
		var currentRank = parseInt($ctx2.data('current-rank'), 10) || 0;
		if (currentRank > 0) {
			var renewalDate = new Date();
			renewalDate.setMonth(renewalDate.getMonth() + 1);
			var renewalLabel = renewalDate.toLocaleDateString(undefined, {
				year: 'numeric',
				month: 'short',
				day: 'numeric'
			});
			$('#sitestaffr-upgrade-cycle-text').text(
				'Resets today \u2014 next renewal ' + renewalLabel
			);
			$cycleNote.show();
		} else {
			$cycleNote.hide();
		}

		// Trial carryover note
		var trialCarryoverMinutes = parseInt(data.trial_carryover_minutes, 10) || 0;
		if (trialCarryoverMinutes > 0) {
			$('#sitestaffr-upgrade-carryover-text').text(
				trialCarryoverMinutes + ' remaining trial minutes carry over'
			);
			$('#sitestaffr-upgrade-carryover-note').show();
		} else {
			$('#sitestaffr-upgrade-carryover-note').hide();
		}

		$upgradePreview.show();
		$upgradeFooter.show();
	}

	function closeUpgradeModal() {
		$upgradeModal.hide();
		$('body').css('overflow', '');
		upgradePendingPlan = null;
		if (upgradeLastFocused) {
			upgradeLastFocused.focus();
			upgradeLastFocused = null;
		}
	}

	// Intercept plan card clicks: route to upgrade or downgrade modal based on rank
	$(document).on('click', '.sitestaffr-upgrade-plan-card[data-plan]', function(e) {
		e.preventDefault();
		var $card = $(this);
		var planName = String($card.data('plan') || '');
		if (!planName) {
			return;
		}

		var targetRank = parseInt($card.data('plan-rank'), 10) || 0;
		var $ctx = $('.sitestaffr-upgrade-context');
		var currentRank = parseInt($ctx.data('current-rank'), 10) || 0;

		// Fallback: infer rank from plan name if data attribute missing
		var rankMap = { starter: 1, business: 2, pro: 3 };
		if (!currentRank) {
			currentRank = rankMap[String($ctx.data('current-plan') || '')] || 0;
		}
		if (!targetRank) {
			targetRank = rankMap[planName] || 0;
		}

		// No active subscription: route to new checkout session
		if (currentRank === 0) {
			var $checkoutForm = $('#sitestaffr-checkout-form');
			if ($checkoutForm.length) {
				$('#sitestaffr-checkout-plan-name').val(planName);
				$checkoutForm.submit();
			}
			return;
		}

		if (targetRank < currentRank) {
			// Downgrade: show downgrade confirmation modal
			openDowngradeModal(planName);
		} else if (targetRank > currentRank) {
			// Upgrade: show proration preview modal
			openUpgradeModal(planName);
		}
		// Same rank: no action (cards for current plan are excluded server-side)
	});

	// Confirm upgrade — redirects to Stripe Checkout
	$(document).on('click', '#sitestaffr-upgrade-confirm', function(e) {
		e.preventDefault();
		if (!upgradePendingPlan) {
			return;
		}

		$upgradeConfirmBtn.prop('disabled', true);
		$upgradeFooter.hide();
		$upgradeProcessing.show();

		var config = window.sitestaffrUsageDashboard || {};
		$.post(config.ajaxUrl, {
			action: 'sitestaffr_execute_upgrade',
			nonce: config.upgradeNonce,
			plan_name: upgradePendingPlan
		})
		.done(function(response) {
			if (response && response.success && response.data && response.data.checkout_url) {
				// Redirect to Stripe Checkout for payment
				window.location.href = response.data.checkout_url;
			} else {
				$upgradeProcessing.hide();
				var errMsg = (response && response.data && response.data.message)
					? response.data.message
					: 'Upgrade failed. Please try again.';
				$upgradePreview.hide();
				showUpgradeError(errMsg);
			}
		})
		.fail(function() {
			$upgradeProcessing.hide();
			$upgradePreview.hide();
			showUpgradeError('Could not reach the server. Please check your connection and try again.');
		});
	});

	// Close upgrade modal: close button, cancel button
	$(document).on('click', '#sitestaffr-upgrade-modal .sitestaffr-modal-close, #sitestaffr-upgrade-modal .sitestaffr-modal-cancel', function(e) {
		e.preventDefault();
		closeUpgradeModal();
	});

	// Close upgrade modal: click overlay
	$(document).on('click', '#sitestaffr-upgrade-modal', function(e) {
		if ($(e.target).is('#sitestaffr-upgrade-modal')) {
			closeUpgradeModal();
		}
	});

	// Close upgrade modal: Escape key (extend existing handler)
	$(document).on('keydown', function(e) {
		if (e.key === 'Escape' && $upgradeModal.is(':visible')) {
			closeUpgradeModal();
		}
	});

	// Focus trap within upgrade modal
	$(document).on('keydown', function(e) {
		if (!$upgradeModal.is(':visible') || e.key !== 'Tab') {
			return;
		}

		var $focusable = $upgradeModal.find('button:visible, input:visible, [tabindex]:not([tabindex="-1"])');
		if (!$focusable.length) {
			return;
		}

		var $first = $focusable.first();
		var $last = $focusable.last();

		if (e.shiftKey) {
			if (document.activeElement === $first[0] || !$.contains($upgradeModal[0], document.activeElement)) {
				e.preventDefault();
				$last.focus();
			}
		} else {
			if (document.activeElement === $last[0] || !$.contains($upgradeModal[0], document.activeElement)) {
				e.preventDefault();
				$first.focus();
			}
		}
	});

	// ====================================================================
	// Downgrade Plan Modal
	// ====================================================================

	var $downgradeModal = $('#sitestaffr-downgrade-modal');
	var $downgradeConfirmBtn = $('#sitestaffr-downgrade-confirm');
	var $downgradeProcessing = $('#sitestaffr-downgrade-processing');
	var $downgradeFooter = $('#sitestaffr-downgrade-footer');
	var $downgradeError = $('#sitestaffr-downgrade-error');
	var $downgradeErrorMessage = $('#sitestaffr-downgrade-error-message');
	var downgradeLastFocused = null;
	var downgradePendingPlan = null;

	function openDowngradeModal(planName) {
		var $ctx = $('.sitestaffr-upgrade-context');
		if (!$ctx.length) {
			return;
		}

		downgradePendingPlan = planName;

		var currentPlanKey = String($ctx.data('current-plan') || 'trial');
		var currentPlanLabel = String($ctx.data('current-plan-label') || '');
		var currentMinutes = parseInt($ctx.data('current-minutes'), 10) || 0;
		var nextBillingDate = String($ctx.data('next-billing-date') || '');

		var $btn = $('.sitestaffr-upgrade-plan-card[data-plan="' + planName + '"]');
		var targetLabel = String($btn.data('plan-label') || planName);
		var targetMinutes = parseInt($btn.data('plan-minutes'), 10) || 0;

		downgradeLastFocused = document.activeElement;

		// Dynamic gradient on plan comparison (current → target)
		var fromColor = getPlanColor(currentPlanKey);
		var toColor = getPlanColor(planName);
		$('.sitestaffr-downgrade-plan-comparison').css(
			'background',
			'linear-gradient(135deg, ' + fromColor.light + ' 0%, ' + toColor.light + ' 100%)'
		).css('border-color', toColor.gradient);
		$('.sitestaffr-downgrade-plan-comparison .sitestaffr-downgrade-arrow').css('color', fromColor.gradient);
		$('#sitestaffr-downgrade-from-label').css({
			'background': fromColor.primary,
			'color': '#fff',
			'padding': '3px 12px',
			'border-radius': '6px',
			'display': 'inline-block'
		});
		$('#sitestaffr-downgrade-to-label').css({
			'background': toColor.primary,
			'color': '#fff',
			'padding': '3px 12px',
			'border-radius': '6px',
			'display': 'inline-block'
		});

		// Reset modal state
		$downgradeProcessing.hide();
		$downgradeError.hide();
		$downgradeFooter.show();
		$downgradeConfirmBtn.prop('disabled', false);

		// Populate modal content
		$('#sitestaffr-downgrade-modal-heading').text('Downgrade to ' + targetLabel);
		$('#sitestaffr-downgrade-from-label').text(currentPlanLabel);
		$('#sitestaffr-downgrade-from-minutes').text(currentMinutes + ' min/month');
		$('#sitestaffr-downgrade-to-label').text(targetLabel);
		$('#sitestaffr-downgrade-to-minutes').text(targetMinutes + ' min/month');

		var billingDate = nextBillingDate || 'your next billing date';
		$('#sitestaffr-downgrade-info-text').text(
			'Your plan will change to ' + targetLabel + ' at the end of your current billing cycle on ' + billingDate + '. You\'ll keep your current plan benefits until then.'
		);
		$('#sitestaffr-downgrade-effective-text').text(
			'Change takes effect on ' + billingDate
		);
		$('#sitestaffr-downgrade-keep-text').text(
			'You keep ' + currentPlanLabel + ' benefits until then'
		);
		$('#sitestaffr-downgrade-minutes-warning').text(
			'Included minutes change: ' + currentMinutes + ' min \u2192 ' + targetMinutes + ' min at renewal'
		);

		$downgradeModal.show();
		$downgradeModal.find('.sitestaffr-modal').focus();
		$('body').css('overflow', 'hidden');
	}

	function closeDowngradeModal() {
		$downgradeModal.hide();
		$('body').css('overflow', '');
		downgradePendingPlan = null;
		if (downgradeLastFocused) {
			downgradeLastFocused.focus();
			downgradeLastFocused = null;
		}
	}

	$(document).on('click', '#sitestaffr-downgrade-confirm', function(e) {
		e.preventDefault();
		if (!downgradePendingPlan) {
			return;
		}

		$downgradeConfirmBtn.prop('disabled', true);
		if ($downgradeFooter.length) {
			$downgradeFooter.hide();
		}
		if ($downgradeProcessing.length) {
			$downgradeProcessing.show();
		}

		var config = window.sitestaffrUsageDashboard || {};
		$.post(config.ajaxUrl, {
			action: 'sitestaffr_execute_downgrade',
			nonce: config.upgradeNonce,
			plan_name: downgradePendingPlan
		})
		.done(function(response) {
			if (response && response.success) {
				window.location.reload();
			} else {
				if ($downgradeProcessing.length) {
					$downgradeProcessing.hide();
				}
				var errMsg = (response && response.data && response.data.message)
					? response.data.message
					: 'Downgrade failed. Please try again.';
				if ($downgradeErrorMessage.length && $downgradeError.length) {
					$downgradeErrorMessage.text(errMsg);
					$downgradeError.show();
				}
				$downgradeConfirmBtn.prop('disabled', false);
				if ($downgradeFooter.length) {
					$downgradeFooter.show();
				}
			}
		})
		.fail(function() {
			if ($downgradeProcessing.length) {
				$downgradeProcessing.hide();
			}
			if ($downgradeErrorMessage.length && $downgradeError.length) {
				$downgradeErrorMessage.text('Could not reach the server. Please check your connection and try again.');
				$downgradeError.show();
			}
			$downgradeConfirmBtn.prop('disabled', false);
			if ($downgradeFooter.length) {
				$downgradeFooter.show();
			}
		});
	});

	// Close downgrade modal: close button, cancel button
	$(document).on('click', '#sitestaffr-downgrade-modal .sitestaffr-modal-close, #sitestaffr-downgrade-modal .sitestaffr-modal-cancel', function(e) {
		e.preventDefault();
		closeDowngradeModal();
	});

	// Close downgrade modal: click overlay
	$(document).on('click', '#sitestaffr-downgrade-modal', function(e) {
		if ($(e.target).is('#sitestaffr-downgrade-modal')) {
			closeDowngradeModal();
		}
	});

	// Close downgrade modal: Escape key
	$(document).on('keydown', function(e) {
		if (e.key === 'Escape' && $downgradeModal.is(':visible')) {
			closeDowngradeModal();
		}
	});

	// Focus trap for downgrade modal
	$(document).on('keydown', function(e) {
		if (!$downgradeModal.is(':visible') || e.key !== 'Tab') {
			return;
		}

		var $focusable = $downgradeModal.find('button:visible, input:visible, [tabindex]:not([tabindex="-1"])');
		if (!$focusable.length) {
			return;
		}

		var $first = $focusable.first();
		var $last = $focusable.last();

		if (e.shiftKey) {
			if (document.activeElement === $first[0] || !$.contains($downgradeModal[0], document.activeElement)) {
				e.preventDefault();
				$last.focus();
			}
		} else {
			if (document.activeElement === $last[0] || !$.contains($downgradeModal[0], document.activeElement)) {
				e.preventDefault();
				$first.focus();
			}
		}
	});

})(jQuery);
