// Set the public path before any other imports
__webpack_public_path__ = (window as any).hulk_epfitf_webpack_public_path;
import "./index.scss";
import FallbackRender from "../components/FallbackRender";
import React, {StrictMode} from "react";
import {createRoot, Root} from "react-dom/client";
import {ErrorBoundary} from "react-error-boundary";
import Field from "./Field";

declare let elementorFrontend: any;

/**
 * Render field
 * @param element
 * @param formElement
 * @protected
 */
function handleField(element: HTMLDivElement & { _reactRoot?: Root }, formElement: HTMLFormElement) {
	const settingsString = element.getAttribute('data-settings') as string;
	const settings = JSON.parse(settingsString as string);

	if (!element._reactRoot) {
		element._reactRoot = createRoot(element);
	}

	const DynamicComponent = <Field formElement={formElement} {...settings}/>;
	// @ts-ignore
	if (process.env.NODE_ENV !== 'production') {
		element._reactRoot.render(
			<ErrorBoundary fallback={<FallbackRender/>}>
				<StrictMode>{DynamicComponent}</StrictMode>
			</ErrorBoundary>
		);
	} else {
		element._reactRoot.render(
			<ErrorBoundary fallback={<FallbackRender/>}>
				{DynamicComponent}
			</ErrorBoundary>
		);
	}
}

/**
 * Handle form widget
 */
function handleWidget() {
	const formElements = document.querySelectorAll<HTMLFormElement>('.elementor-form');
	formElements.forEach((formElement: HTMLFormElement) => {
		const fields = formElement.querySelectorAll<HTMLDivElement>('.hulk_epfitf_telephone_wrap');
		fields.forEach((element: HTMLDivElement) => handleField(element, formElement));
	});
}

/**
 * Form widget init
 * @protected
 */
function onInit() {
	elementorFrontend.hooks.addAction(
		'frontend/element_ready/form.default',
		handleWidget
	);
}

window.addEventListener('elementor/frontend/init', onInit);
