import domReady from '@wordpress/dom-ready';
import { render, createElement } from '@wordpress/element';
import LocatorApp from '../LocatorApp';
import { configureFrontend, mountDesignLinks } from '../runtime';
import '../locator.scss';

const mountLocators = () => {
	const config = configureFrontend();
	mountDesignLinks();
	document.querySelectorAll( '.cliq-sl-root' ).forEach( ( el ) => {
		if ( el.dataset.mounted ) return;
		const templateId = el.dataset.templateId;
		if ( ! templateId ) return;
		el.dataset.mounted = '1';
		const defaults = {};
		[ 'country', 'category', 'brand', 'q', 'metaKey', 'metaValue', 'perPage' ].forEach( ( key ) => {
			if ( el.dataset[ key ] ) defaults[ key ] = el.dataset[ key ];
		} );
		const instanceConfig = Object.keys( defaults ).length ? { ...config, defaults } : config;
		let bootstrap = null;
		// The renderer emits the bootstrap island as the root's NEXT SIBLING —
		// SafeHtml::filter() would strip a <script> from inside the root, so
		// FrontendModule lifts it out and appends it after the div. Keep the
		// legacy in-root lookup as well so either shape hydrates.
		const bootEl =
			el.querySelector( ':scope > script.cliq-sl-bootstrap' ) ||
			( el.nextElementSibling &&
			el.nextElementSibling.matches?.( 'script.cliq-sl-bootstrap' )
				? el.nextElementSibling
				: null );
		if ( bootEl ) {
			try {
				bootstrap = JSON.parse( bootEl.textContent );
			} catch ( error ) {
				bootstrap = null;
			}
		}
		if ( bootstrap ) el.textContent = '';
		render( createElement( LocatorApp, { templateId, config: instanceConfig, bootstrap } ), el );
	} );
};

domReady( mountLocators );
