/**
 * WordPress dependencies
 */
import { useSelect } from '@wordpress/data';
import { useEffect, useState } from '@wordpress/element';
import type { Maybe } from '@nab/types';

/**
 * Internal dependencies
 */
import { store as NAB_CHECKER } from '../store';
import { getElementByXPath } from '../../public/tracking/xpath';

export const ClickHighlighter = ( {
	zIndex,
}: {
	zIndex: string;
} ): JSX.Element | null => {
	const click = useSelect(
		( select ) => select( NAB_CHECKER ).getHighlightedClick(),
		[]
	);
	const [ coords, setCoords ] =
		useState< Maybe< [ number, number ] > >( undefined );

	const element = (
		click?.selector ? getElementByXPath( click.selector ) : null
	) as HTMLElement | null;

	useEffect( () => {
		if ( ! click || ! element ) {
			setCoords( undefined );
			return;
		}

		const box = element.getBoundingClientRect();
		setCoords( [
			box.x + ( box.right - box.left ) * click.coords[ 0 ],
			box.y + ( box.bottom - box.top ) * click.coords[ 1 ],
		] );
	}, [ click, element ] );

	if ( ! element || ! coords ) {
		return null;
	}

	return (
		<div
			style={ {
				fontSize: '24px',
				width: '1em',
				height: '1em',
				position: 'absolute',
				left: coords[ 0 ],
				top: coords[ 1 ],
				background: '#cf2e2e',
				border: '5px solid #fff',
				transform: 'translate(-50%, -50%)',
				borderRadius: '100%',
				boxShadow: '0 0 0 5px #364377',
				zIndex,
			} }
		/>
	);
};
