import { setFrontendCssMap, setRenderDefaults, setBreakpoint } from '@cliqui/design-runtime/designRender';
import { setFrontendIconPaths } from '@cliqui/design-runtime/frontendIcons';
import '../../shared/tokenFormats';
import './style.scss';

let linksMounted = false;

export const frontendConfig = () => window.CLIQ_SL || {};

export const configureFrontend = () => {
	const config = frontendConfig();
	setFrontendCssMap( config.cssMap );
	setRenderDefaults( config.renderDefaults );
	setBreakpoint( config.mobileBreakpoint );
	setFrontendIconPaths( config.icons );
	return config;
};

/** Delegated behaviour for linked PHP-rendered and client-rendered designs. */
export const mountDesignLinks = () => {
	if ( linksMounted ) return;
	linksMounted = true;
	document.addEventListener( 'click', ( event ) => {
		const card = event.target.closest( '.cliq-widget-design--linked[data-cliq-link]' );
		const interactive = event.target.closest( 'a,button,input,select,textarea,label,[role="button"]' );
		if ( ! card || ( interactive && card.contains( interactive ) ) ) return;
		event.stopPropagation();
		if ( card.dataset.cliqLinkTarget === '_blank' ) window.open( card.dataset.cliqLink, '_blank', 'noopener,noreferrer' );
		else window.location.assign( card.dataset.cliqLink );
	} );
	document.addEventListener( 'keydown', ( event ) => {
		if ( event.key !== 'Enter' && event.key !== ' ' ) return;
		const card = event.target.closest( '.cliq-widget-design--linked[data-cliq-link]' );
		if ( ! card || event.target !== card ) return;
		event.preventDefault();
		card.click();
	} );
};
