(function( $ ) {
	'use strict';

	// Wait for the document to be ready
	$( function() {

		/**
		 * Shows the media alert once per browser session.
		 */
		function manualdogMaybeShowMediaAlert() {
			if ( sessionStorage.getItem( 'manualdog_media_alert_shown' ) === 'true' ) {
				return;
			}

			if ( typeof manualdog_l10n !== 'undefined' && manualdog_l10n.media_alert ) {
				alert( manualdog_l10n.media_alert );
			}

			sessionStorage.setItem( 'manualdog_media_alert_shown', 'true' );
		}

		// Earlier versions of this file patched wp.media (first the
		// MediaFrame.Post prototype directly, then the wp.media() factory
		// function itself) to detect when the media library modal opens.
		// Neither reliably caught the block editor's own "Media Library"
		// button in testing, most likely because of exactly which internal
		// code path/JS context it goes through since WordPress 7.1 made the
		// editor canvas always iframed -- and that internal path has proven
		// hard to pin down from the outside.
		//
		// Instead of chasing WordPress's internal media APIs, watch the DOM
		// directly: WordPress always renders the media modal as a top-level
		// ".media-modal" element appended to <body> (never inside the block
		// editor's iframe canvas), regardless of which frame class or JS
		// context triggered it. That makes it a much more reliable signal.
		var manualdogObserver = new MutationObserver( function( mutations ) {
			for ( var i = 0; i < mutations.length; i++ ) {
				var addedNodes = mutations[ i ].addedNodes;
				for ( var j = 0; j < addedNodes.length; j++ ) {
					var node = addedNodes[ j ];
					if ( node.nodeType !== 1 ) {
						continue;
					}
					if (
						( node.classList && node.classList.contains( 'media-modal' ) ) ||
						( node.querySelector && node.querySelector( '.media-modal' ) )
					) {
						manualdogMaybeShowMediaAlert();
						return;
					}
				}
			}
		} );

		manualdogObserver.observe( document.body, { childList: true, subtree: true } );
	});

})( jQuery );