/**
 * Moves image block borders from <img> to <figure> in the current document only.
 * Does not access editor canvas iframes (avoids cross-origin SecurityError).
 */
( function () {
	'use strict';

	var scheduled = false;

	function fixImageBlockBorders() {
		scheduled = false;

		var imageBlocks = document.querySelectorAll( '.wp-block-image' );

		imageBlocks.forEach( function ( block ) {
			var img = block.querySelector( 'img' );
			var figure = block.querySelector( 'figure' );

			if ( ! img || ! figure ) {
				return;
			}

			var computedStyle = window.getComputedStyle( img );
			var hasBorder =
				computedStyle.border !== 'none' ||
				computedStyle.borderWidth !== '0px' ||
				computedStyle.borderRadius !== '0px' ||
				computedStyle.borderColor !== 'rgba(0, 0, 0, 0)';

			if ( ! hasBorder ) {
				return;
			}

			figure.style.border = computedStyle.border;
			figure.style.borderWidth = computedStyle.borderWidth;
			figure.style.borderColor = computedStyle.borderColor;
			figure.style.borderStyle = computedStyle.borderStyle;
			figure.style.borderRadius = computedStyle.borderRadius;

			if ( computedStyle.borderRadius !== '0px' ) {
				figure.style.overflow = 'hidden';
			}

			img.style.setProperty( 'border', 'none', 'important' );
			img.style.setProperty( 'border-radius', '0', 'important' );
			img.style.setProperty( 'border-width', '0', 'important' );
			img.style.setProperty( 'border-color', 'transparent', 'important' );
			img.style.setProperty( 'border-style', 'none', 'important' );
		} );
	}

	function scheduleFix() {
		if ( scheduled ) {
			return;
		}

		scheduled = true;
		window.requestAnimationFrame( fixImageBlockBorders );
	}

	function init() {
		scheduleFix();

		if ( typeof wp !== 'undefined' && wp.data && wp.data.subscribe ) {
			wp.data.subscribe( scheduleFix );
		}
	}

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