/**
 * Build preview body HTML + CSS string for admin iframes.
 */
import {
	PREVIEW_SELECTOR,
	elementFontFamilyCssFromVars,
	elementHoverCss,
	elementHoverCssFromVars,
	elementSpacingCssFromVars,
	styleableFields,
	toCss,
	toCssForBreakpoint,
} from '../../cssVars';
import { toCssForSlides } from '../../shared/slideLayoutStyle';
import {
	elementsOrderDefaultsFromSchema,
	toElementsOrderCssForAttrs,
} from '../../shared/elementsOrder';
import { toElementsVisibilityCssForAttrs } from '../../shared/elementsVisibility';
import { buttonHoverCss, interpolate } from '../../interpolate';
import { getLibraryStylesMap } from '../../shared/buttonLibrary';

/**
 * @param {string}      markup
 * @param {object}      attrs
 * @param {object}      cssVars
 * @param {Array}       fieldSchema
 * @param {string|null} breakpoint  When set, bake that breakpoint’s effective
 *                                  vars (admin device switcher). When null,
 *                                  emit responsive media queries.
 * @return {{ __html: string, styleCss: string }}
 */
export function renderPreview(
	markup,
	attrs = {},
	cssVars = {},
	fieldSchema = [],
	breakpoint = null
) {
	const libStyles = getLibraryStylesMap();
	const html = interpolate(
		markup,
		{
			...attrs,
			cssVars,
			instanceId: String( attrs.instanceId || attrs.clientId || 'admin-preview' )
				.replace( /[^a-zA-Z0-9_-]/g, '' )
				.slice( 0, 20 ),
		},
		libStyles
	);
	const varsCss = breakpoint
		? toCssForBreakpoint( PREVIEW_SELECTOR, cssVars, breakpoint )
		: toCss( PREVIEW_SELECTOR, cssVars );
	const slidesCss = toCssForSlides(
		PREVIEW_SELECTOR,
		Array.isArray( attrs.slides ) ? attrs.slides : [],
		cssVars,
		breakpoint
	);
	const orderDefaults = elementsOrderDefaultsFromSchema( fieldSchema, attrs );
	const orderCss = toElementsOrderCssForAttrs(
		PREVIEW_SELECTOR,
		attrs,
		orderDefaults,
		breakpoint
	);
	const visCss = toElementsVisibilityCssForAttrs(
		PREVIEW_SELECTOR,
		attrs,
		[],
		breakpoint
	);
	const hoverFromFields = elementHoverCss(
		PREVIEW_SELECTOR,
		styleableFields( fieldSchema )
	);
	const hoverFromVars = elementHoverCssFromVars( PREVIEW_SELECTOR, cssVars );
	const fontFromVars = elementFontFamilyCssFromVars( PREVIEW_SELECTOR, cssVars );
	const spacingFromVars = elementSpacingCssFromVars( PREVIEW_SELECTOR, cssVars );
	const btnHover = buttonHoverCss(
		PREVIEW_SELECTOR,
		attrs,
		'buttons',
		libStyles
	);
	const styleCss = [
		varsCss,
		slidesCss,
		orderCss,
		visCss,
		hoverFromFields || hoverFromVars,
		btnHover,
		fontFromVars,
		spacingFromVars,
	]
		.filter( Boolean )
		.join( '\n\n' );
	return {
		__html: `<div class="bm-preview-root">${ html }</div>`,
		styleCss,
	};
}
