/** biome-ignore-all lint/complexity/noBannedTypes: {} is the "empty props" type in React */
import { Callable, type Node, type NodePathMap } from "godot"
import * as React from "react"
import * as Reconciler from "./Reconciler.js"


const ConcurrentRoot = 1

export const renderComponent: {
    (
        container: Node<NodePathMap>,
        component: React.FC<{}>,
    ): void
    <P>(
        container: Node<NodePathMap>,
        component: React.FC<P>,
        props: NoInfer<P>,
    ): void
} = (
    container: Node<NodePathMap>,
    component: React.FC<{}>,
    props?: Record<string, unknown>,
): void => {
    if (!(container as any)._reactReconciler)
        (container as any)._reactReconciler = Reconciler.make()

    if (!(container as any)._reactContainer) {
        (container as any)._reactContainer = (container as any)._reactReconciler.createContainer(
            container,
            ConcurrentRoot,
            null,
            false,
            false,
            "",
            console.error,
        )

        const cleanup = Callable.create(container, function(this) {
            (container as any)._reactReconciler.updateContainer(
                null,
                (container as any)._reactContainer,
                null,
            )
            delete (container as any)._reactReconciler
            delete (container as any)._reactContainer

            container.tree_exiting.disconnect(cleanup)
        })
        container.tree_exiting.connect(cleanup)
    }

    (container as any)._reactReconciler.updateContainer(
        React.createElement(component, props),
        (container as any)._reactContainer,
        null,
    )
}
