/**
 * Build icon HTML / flex helpers for standalone + repeater buttons.
 */
import {
	normalizeIconRef,
	renderIconHtml,
	ensureIconStylesheets,
} from './iconRegistry';

/**
 * @param {object} attrs
 * @param {object} [styleVars] Optional CSS var map for icon size/color (--bm-label-icon-*).
 * @return {{ iconHtml: string, btnIconFlex: string, icon: string, iconPosition: string }}
 */
export function buildButtonIconTokens( attrs = {}, styleVars = {} ) {
	const icon = normalizeIconRef( String( attrs.icon || '' ).trim() );
	const iconPosition =
		String( attrs.iconPosition || 'left' ).toLowerCase() === 'right'
			? 'right'
			: 'left';

	if ( icon && ! icon.startsWith( 'dashicons:' ) ) {
		ensureIconStylesheets();
	}

	const useLabelVars =
		styleVars['--bm-label-icon-size'] != null ||
		styleVars['--bm-label-icon-color'] != null ||
		( ! attrs.iconSize && ! attrs.iconColor );

	let iconStyle;
	if ( useLabelVars && ! attrs.iconSize && ! attrs.iconColor ) {
		iconStyle =
			'font-size:var(--bm-label-icon-size, 20px);width:1em;height:1em;color:var(--bm-label-icon-color, currentColor)';
	} else {
		let iconSize = String(
			attrs.iconSize || styleVars['--bm-label-icon-size'] || '20px'
		).trim();
		if ( iconSize && /^-?[\d.]+$/.test( iconSize ) ) {
			iconSize = `${ iconSize }px`;
		}
		if ( ! iconSize || ! /^-?[\d.]+(px|rem|em|%)$/i.test( iconSize ) ) {
			iconSize = '20px';
		}
		const rawColor = String(
			attrs.iconColor || styleVars['--bm-label-icon-color'] || ''
		).trim();
		const iconColor =
			rawColor &&
			/^(#([0-9a-f]{3,8})|rgba?\([^)]+\)|hsla?\([^)]+\)|currentcolor|inherit|transparent|[a-z]+)$/i.test(
				rawColor
			)
				? rawColor
				: '';
		iconStyle = [
			`font-size:${ iconSize }`,
			'width:1em',
			'height:1em',
			iconColor ? `color:${ iconColor }` : '',
		]
			.filter( Boolean )
			.join( ';' );
	}

	return {
		icon,
		iconPosition,
		btnIconFlex: icon && iconPosition === 'right' ? 'row-reverse' : 'row',
		iconHtml: icon
			? renderIconHtml( icon, iconStyle, 'bm-button__icon bm-hero__btn-icon' )
			: '',
	};
}
