/* Parent-side postMessage bridge for the PrintPrice → Dashboard iframe.
   The React SPA inside the iframe can't navigate the parent WordPress
   admin directly (different origin), so when it needs to send the
   merchant somewhere in wp-admin it posts a message to us and we
   navigate here.

   Config injected from PHP via wp_localize_script as
   window.PrintPriceDashboard:
     - iframeOrigin:         e.g. "https://wp.printprice.one"  (origin filter)
     - settingsUrl:          WP admin URL of PrintPrice → Settings
     - upgradeUrl:           Freemius pricing page (no plan preselected)
     - checkoutUrlTemplate:  same, with __PLAN_ID__ to substitute
     - accountUrl:           Freemius account page (downgrade / cancel)

   SECURITY: every destination is a URL built in PHP. The iframe can pick
   BETWEEN them and can supply a numeric Freemius plan id, and nothing
   else — a URL arriving in the message is never navigated to. Without
   that rule, any page able to postMessage here could redirect a logged-in
   admin anywhere. */
( function () {
	var cfg = window.PrintPriceDashboard;
	if ( ! cfg || ! cfg.iframeOrigin || ! cfg.settingsUrl ) {
		return;
	}

	/* Freemius plan ids are integers. Anything else is not substituted — we
	   fall back to the plain pricing page rather than building a URL out of
	   untrusted text. */
	function checkoutUrlFor( planId ) {
		if ( ! cfg.checkoutUrlTemplate ) {
			return null;
		}
		var id = String( planId );
		if ( ! /^[0-9]{1,12}$/.test( id ) ) {
			return null;
		}
		return cfg.checkoutUrlTemplate.replace( '__PLAN_ID__', id );
	}

	window.addEventListener( 'message', function ( e ) {
		// Reject messages from any origin except our own backend. This is
		// the only sender we trust — without this check, any embedded page
		// on the WP admin could navigate the admin away.
		if ( e.origin !== cfg.iframeOrigin ) {
			return;
		}
		if ( ! e.data || typeof e.data !== 'object' ) {
			return;
		}
		if ( e.data.type === 'printprice:navigate-settings' ) {
			window.location.href = cfg.settingsUrl;
		}
		if ( e.data.type === 'printprice:navigate-upgrade' ) {
			// With a plan id: straight to that plan's checkout. Without one
			// (or with one we don't accept): the pricing page, where the
			// merchant picks a plan themselves. Either way they can complete
			// the purchase, so a bad id degrades instead of dead-ending.
			var url = checkoutUrlFor( e.data.planId ) || cfg.upgradeUrl;
			if ( url ) {
				window.location.href = url;
			}
		}
		if ( e.data.type === 'printprice:navigate-account' && cfg.accountUrl ) {
			window.location.href = cfg.accountUrl;
		}
	} );
} )();
