/**
 * WordPress dependencies
 */
import { createRoot } from '@wordpress/element';

/**
 * External dependencies
 */
import once from 'lodash/once';

/**
 * Internal dependencies
 */
import { Wrapper } from './wrapper';

export const initChecker = once( () => {
	customElements.define( 'nab-checker-wrapper', ShadowHost );
	const wrapper = document.createElement( 'nab-checker-wrapper' );
	insertFirstInBody( wrapper );
} );

// =======
// HELPERS
// =======

class ShadowHost extends HTMLElement {
	constructor() {
		super();
		this.attachShadow( { mode: 'open' } );
	}

	connectedCallback() {
		const style = document.createElement( 'style' );
		style.textContent = `
			:host {
				all: initial;
				display: block;
				font-family: system-ui, sans-serif;
			}

			*, *::before, *::after {
				box-sizing: border-box;
			}
		`;
		this.shadowRoot?.appendChild( style );

		const mountPoint = document.createElement( 'div' );
		this.shadowRoot?.appendChild( mountPoint );

		const root = createRoot( mountPoint );
		root.render( <Wrapper zIndex={ zIndex() } /> );
	}
}

function insertFirstInBody( el: HTMLElement ): void {
	if ( document.body ) {
		document.body.prepend( el );
	} else {
		// Body not ready yet → wait for it
		const observer = new MutationObserver( () => {
			if ( document.body ) {
				document.body.prepend( el );
				observer.disconnect();
			}
		} );

		observer.observe( document.documentElement, {
			childList: true,
		} );
	}
}

function zIndex(): string {
	const overlay = document.getElementById( 'nelio-ab-testing-overlay' );
	const css = overlay?.textContent || '';
	const match = css.match( /z-index\s*:\s*([+-]?\d+)/i );
	const value = match && match[ 1 ];
	return ( value || '999999' ) + '0';
}
