<?php
/**
 * Preview bootstrap — real-site iframe bridge for the settings panel.
 *
 * @package wuppi
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handle ?wuppi_frame=1 requests — real-site iframe mode.
 *
 * Suppresses the admin bar and injects the postMessage bridge listener so the
 * settings panel can send live CSS variable updates to the real frontend.
 */
function wuppi_frame_mode_setup() {
	if ( empty( $_GET['wuppi_frame'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return;
	}

	if ( ! current_user_can( wuppi_get_settings_page_capability() ) ) {
		return;
	}

	// $show_admin_bar is cached by _wp_admin_bar_init() on 'init' before this hook fires,
	// so the filter alone is too late — override the global directly.
	global $show_admin_bar;
	$show_admin_bar = false;
	// wp_enqueue_admin_bar_bump_styles() (on wp_enqueue_scripts) checks has_action() not
	// is_admin_bar_showing(), so it injects the bump CSS regardless of $show_admin_bar.
	// Override it with a high-priority wp_head style instead of removing core actions.
	add_action( 'wp_head', 'wuppi_frame_no_admin_bump', PHP_INT_MAX );
	add_action( 'wp_head', 'wuppi_frame_inject_bridge_listener', 99 );
}
add_action( 'template_redirect', 'wuppi_frame_mode_setup' );

/**
 * Override admin bar bump CSS for preview frames — avoids remove_action on core hooks.
 */
function wuppi_frame_no_admin_bump() {
	echo '<style>html{margin-top:0!important}</style>';
}

/**
 * Inject the postMessage listener that receives wuppi:vars and applies CSS custom properties.
 */
function wuppi_frame_inject_bridge_listener() {
	?>
	<script id="wuppi-frame-bridge">
	(function(){
		window.addEventListener('message',function(e){
			if(e.origin!==window.location.origin)return;
			if(!e.data||e.data.type!=='wuppi:vars')return;
			var tag=document.getElementById('wuppi-preview-overrides');
			if(!tag){tag=document.createElement('style');tag.id='wuppi-preview-overrides';document.head.appendChild(tag);}
			var vars=e.data.vars||{};
			tag.textContent=':root{'+Object.entries(vars).map(function(p){return p[0]+':'+p[1];}).join(';')+'}';
			if(e.data.bodyClasses){
				document.body.className=document.body.className.replace(/\bwuppi-[^\s]+/g,'').trim();
				e.data.bodyClasses.forEach(function(c){document.body.classList.add(c);});
			}
		});
		window.parent.postMessage({type:'wuppi:ready'},window.location.origin);
		document.addEventListener('click',function(e){
			var a=e.target.closest?e.target.closest('a[href]'):null;
			if(!a)return;
			if(e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;
			var t=a.target;
			if(t&&t!==''&&t!=='_self')return;
			var href=a.getAttribute('href');
			if(!href||href.charAt(0)==='#')return;
			try{
				var url=new URL(href,window.location.href);
				if(url.origin!==window.location.origin)return;
				if(url.searchParams.has('wuppi_frame'))return;
				e.preventDefault();
				url.searchParams.set('wuppi_frame','1');
				window.location.href=url.toString();
			}catch(err){}
		});
	})();
</script>
	<?php
}
