/**
 * Single authority for editor canvas width.
 *
 * Reads tablet/mobile widths from the AxcelersBlocks settings page and applies
 * them whenever WordPress's native preview device type changes — whether the
 * user clicks WP's own top-right buttons or the per-block ResponsiveControl
 * (which dispatches to the same WP store).
 */
import apiFetch from '@wordpress/api-fetch';
import { subscribe, select } from '@wordpress/data';

const deviceWidths = {
	Tablet: '1024px',
	Mobile: '768px',
};

const getWpDeviceType = () =>
	select( 'core/editor' )?.getDeviceType?.() ||
	select( 'core/edit-post' )?.__experimentalGetPreviewDeviceType?.() ||
	'Desktop';

const applyCanvasWidth = ( deviceType ) => {
	const iframe = document.querySelector( 'iframe[name="editor-canvas"]' );
	if ( ! iframe ) {
		return;
	}

	// WordPress 7.1 wraps the editor canvas in a resizable container and drives
	// the device preview width from that wrapper, not from the iframe. Sizing
	// only the iframe leaves core's drag handles sitting outside the visible
	// canvas, so drive the wrapper when it exists and fall back to the iframe
	// on releases that do not have one.
	const resizable = iframe.closest( '.editor-resizable-editor' );
	const target = resizable || iframe;

	// Clear any width previously written to the iframe so the two elements
	// cannot disagree after an upgrade from the iframe-only behaviour.
	if ( resizable ) {
		iframe.style.width = '';
		iframe.style.marginLeft = '';
		iframe.style.marginRight = '';
	}

	if ( deviceType === 'Tablet' || deviceType === 'Mobile' ) {
		target.style.width = deviceWidths[ deviceType ];
		target.style.marginLeft = 'auto';
		target.style.marginRight = 'auto';
	} else {
		target.style.width = '100%';
		target.style.marginLeft = '';
		target.style.marginRight = '';
	}
};

// Fetch the settings-page values once. After they arrive, re-apply for
// whichever device is currently active so a race on initial load is corrected.
apiFetch( { path: '/axcelersblocks/v1/device-settings' } )
	.then( ( settings ) => {
		if ( settings?.devices?.tablet?.width ) {
			deviceWidths.Tablet = settings.devices.tablet.width;
		}
		if ( settings?.devices?.mobile?.width ) {
			deviceWidths.Mobile = settings.devices.mobile.width;
		}

		// Re-apply with the correct values in case the device was already
		// switched before the fetch completed.
		const current = getWpDeviceType();
		window.requestAnimationFrame( () => applyCanvasWidth( current ) );
		window.setTimeout( () => applyCanvasWidth( current ), 150 );
	} )
	.catch( () => {} );

let lastDeviceType = null;

subscribe( () => {
	const deviceType = getWpDeviceType();
	if ( deviceType === lastDeviceType ) {
		return;
	}
	lastDeviceType = deviceType;

	window.requestAnimationFrame( () => applyCanvasWidth( deviceType ) );
	window.setTimeout( () => applyCanvasWidth( deviceType ), 150 );
} );
