import { createElementFromHTML } from './createHtmlElement';

export function handleToolTip(element: Element, tooltip: string): void {
	element.addEventListener('focus', event => handleToolTipEnterEvent(event, tooltip));
	element.addEventListener('mouseover', event => handleToolTipEnterEvent(event, tooltip));
	element.addEventListener('blur', event => handleToolTipLeaveEvent(event, tooltip));
	element.addEventListener('mouseout', event => handleToolTipLeaveEvent(event, tooltip));
}

function handleToolTipEnterEvent(event: Event, tooltip: string) {
	const alreadyExists = document.getElementById(`tooltip-${tooltip}`);
	if (alreadyExists) {
		return;
	}
	const htmlString = `<div class="tooltip" role="tooltip" aria-label="${tooltip}" aria-labelledby="${tooltip
		.toLocaleLowerCase()
		.replace(' ', '-')}" id="tooltip-${tooltip}">
				<div class="tooltip-arrow">
				</div>
				<span>${tooltip}</span>
			</div>`;
	const toolTip = createElementFromHTML(htmlString);
	const buttonElement = event.target as HTMLElement;
	if (event.type === 'focus') {
		buttonElement.classList.add('focus-visible');
	}
	const rect = buttonElement.getBoundingClientRect();
	toolTip.style.top = `${(rect.top - 58).toString()}px`;
	toolTip.style.left = `${(rect.left - 10).toString()}px`;
	document.getElementsByTagName('docs-markdown-editor')[0].appendChild(toolTip);
}

function handleToolTipLeaveEvent(event: Event, tooltip: string) {
	const buttonElement = event.target as HTMLElement;
	if (buttonElement && event.type === 'blur') {
		buttonElement.classList.remove('focus-visible');
	}
	const elementExists = document.getElementById(`tooltip-${tooltip}`);
	if (elementExists) {
		elementExists.remove();
	}
}
