import apiFetch from '@wordpress/api-fetch';
import { dispatch } from '@wordpress/data';
import domReady from '@wordpress/dom-ready';
import { createElement, render } from '@wordpress/element';

import App from './components/App';
import { STORE_KEY } from './store';
import './style.scss';

const bootstrap = window.CLIQTHEMES_UI ??
	window.CLIQTHEMES_UI_DATA ?? {
		providers: {},
		rest: {},
	};

const restConfig = bootstrap.rest ?? {};

if ( restConfig.root ) {
	apiFetch.use( apiFetch.createRootURLMiddleware( restConfig.root ) );
}

if ( restConfig.nonce ) {
	apiFetch.use( apiFetch.createNonceMiddleware( restConfig.nonce ) );
}

dispatch( STORE_KEY ).bootstrap( bootstrap );

domReady( () => {
	const target = document.getElementById( bootstrap.app?.rootId || 'cliqthemes-ui-root' );

	if ( ! target ) {
		return;
	}

	render( createElement( App ), target );
} );
