"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const hooks_1 = require("../../gravity-blocks/hooks/index.js");
const loadHubspotScript_1 = tslib_1.__importDefault(require("./loadHubspotScript.js"));
const setHubspotDefaultValues_1 = require("./setHubspotDefaultValues.js");
const HubspotFormContainer = React.forwardRef((props, ref) => {
    const { className, formId, formInstanceId, portalId, region, formClassName, createDOMElement, defaultValues, } = props;
    const containerRef = React.useRef(null);
    const hsContainerRef = React.useRef();
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    React.useImperativeHandle(ref, () => containerRef.current);
    const containerId = formInstanceId
        ? `hubspot-form-${formId}-${formInstanceId}`
        : `hubspot-form-${formId}`;
    const createForm = () => {
        if (containerRef.current && !hsContainerRef.current && createDOMElement) {
            hsContainerRef.current = document.createElement('div');
            containerRef.current.id = '';
            hsContainerRef.current.id = containerId;
            containerRef.current.appendChild(hsContainerRef.current);
        }
        if (!createDOMElement || hsContainerRef.current) {
            if (window.hbspt) {
                window.hbspt.forms.create({
                    region,
                    portalId,
                    formId,
                    target: `#${containerId}`,
                    cssClass: formClassName,
                    formInstanceId,
                    onFormReady: defaultValues
                        ? (form) => (0, setHubspotDefaultValues_1.setHubspotDefaultValues)(form, defaultValues)
                        : undefined,
                });
            }
        }
    };
    (0, hooks_1.useMount)(() => {
        (async () => {
            if (!window.hbspt) {
                await (0, loadHubspotScript_1.default)();
            }
            createForm();
        })();
        return () => {
            if (createDOMElement && containerRef.current && containerRef.current.lastChild) {
                containerRef.current.removeChild(containerRef.current.lastChild);
            }
        };
    });
    return (0, jsx_runtime_1.jsx)("div", { className: className, id: containerId, ref: containerRef });
});
HubspotFormContainer.displayName = 'HubspotFormContainer';
exports.default = HubspotFormContainer;
//# sourceMappingURL=HubspotFormContainer.js.map
