/**
 * KooKoa Folders — Top-level admin menu icon painter.
 *
 * Overrides WP svg-painter's inline !important style on the #toplevel_page_kookoa-folders
 * icon so that the folder glyph switches to green neon on hover / active / click, and
 * falls back to gray otherwise. A MutationObserver catches svg-painter rewrites without
 * an infinite loop (guard flag), and mouseenter / mouseleave / click listeners drive
 * the user-facing transitions.
 *
 * Expects `window.kookoawpfMenuIcon.path` to contain the SVG folder path, injected via
 * wp_localize_script from class KookoaWPF in kookoa-folders.php.
 */
(function () {
	const li = document.getElementById( 'toplevel_page_kookoa-folders' );
	if ( ! li ) {
		return;
	}
	const img = li.querySelector( '.wp-menu-image' );
	if ( ! img ) {
		return;
	}

	const data = window.kookoawpfMenuIcon || {};
	const path = data.path || '';

	function svgUrl( fill ) {
		return "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='" + encodeURIComponent( fill ) + "'%3E%3Cpath d='" + path + "'/%3E%3C/svg%3E\")";
	}

	const gray  = svgUrl( '#a7aaad' );
	const green = svgUrl( '#39FF14' );

	function isActive() {
		return li.classList.contains( 'current' ) || li.classList.contains( 'wp-has-current-submenu' );
	}

	// Initial state.
	img.style.setProperty( 'background-image', isActive() ? green : gray, 'important' );

	// Hover overrides svg-painter.
	let guard = false;
	function setIcon( color ) {
		guard = true;
		img.style.setProperty( 'background-image', color, 'important' );
		guard = false;
	}

	// MutationObserver catches svg-painter rewrites without infinite loop.
	const mo = new MutationObserver( function () {
		if ( guard ) {
			return;
		}
		const target = li.classList.contains( 'kookoawpf-clicked' ) || isActive()
			? green
			: ( li.matches( ':hover' ) ? green : gray );
		setIcon( target );
	} );
	mo.observe( img, { attributes: true, attributeFilter: [ 'style' ] } );

	li.addEventListener( 'mouseenter', function () { setIcon( green ); } );
	li.addEventListener( 'mouseleave', function () { setIcon( isActive() ? green : gray ); } );
	li.querySelector( 'a' ).addEventListener( 'click', function () {
		li.classList.add( 'kookoawpf-clicked' );
		setIcon( green );
	} );
})();
