/**
 * Tag-style labels on Gutenberg inserter cards for My Library vs JBM Library.
 *
 * Core block titles are plain strings (no HTML), so we style a ::before chip on
 * inserter list items and inject translated `content` values here.
 */

import { __ } from '@wordpress/i18n';

const STYLE_ID = 'jocbm-inserter-library-tags';

/** Escape a string for use inside a CSS double-quoted content value. */
function cssContentString( value ) {
	return `"${ String( value ?? '' )
		.replace( /\\/g, '\\\\' )
		.replace( /"/g, '\\"' )
		.replace( /\n/g, '\\A ' ) }"`;
}

/**
 * Inject / refresh inserter tag label CSS (i18n-safe content).
 */
export function injectInserterLibraryTags() {
	if ( typeof document === 'undefined' ) {
		return;
	}

	const myLibrary = __( 'My Library', 'joc-blockora-morph' );
	const jbmLibrary = __( 'JBM Library', 'joc-blockora-morph' );

	const css = `
/* My Library — namespace joc-blockora-morph/ (exclude -lib) */
.block-editor-block-types-list__item[class*="editor-block-list-item-joc-blockora-morph-"]:not([class*="editor-block-list-item-joc-blockora-morph-lib-"]) .block-editor-block-types-list__item-title::before,
.components-autocomplete__result[class*="editor-block-list-item-joc-blockora-morph-"]:not([class*="editor-block-list-item-joc-blockora-morph-lib-"])::before {
	content: ${ cssContentString( myLibrary ) };
}

/* JBM Library — namespace joc-blockora-morph-lib/ */
.block-editor-block-types-list__item[class*="editor-block-list-item-joc-blockora-morph-lib-"] .block-editor-block-types-list__item-title::before,
.components-autocomplete__result[class*="editor-block-list-item-joc-blockora-morph-lib-"]::before {
	content: ${ cssContentString( jbmLibrary ) };
}
`.trim();

	let el = document.getElementById( STYLE_ID );
	if ( ! el ) {
		el = document.createElement( 'style' );
		el.id = STYLE_ID;
		document.head.appendChild( el );
	}
	el.textContent = css;
}
