import { createRoot } from "react-dom/client";

import { FeedbackModal } from "../components/feedback/modal.js";
import { Provider } from "../components/provider.js";
import { RootStore } from "../store/stores.js";

function listenPluginDeactivation() {
    document.addEventListener(
        "click",
        (e) => {
            const { names, currentUserFullName } = RootStore.get.optionStore.others;
            const link = e?.target as HTMLAnchorElement;

            for (const slug in names) {
                const { plugin, hasAtLeastOneActiveLicense, isPluginActiveForNetwork } = names[slug];
                if (link.matches(`tr[data-plugin="${plugin}"] a[href*="action=deactivate"]`)) {
                    const node = document.createElement("div");
                    document.body.appendChild(node);
                    const root = createRoot(node);
                    root.render(
                        <Provider>
                            <FeedbackModal
                                {...names[slug]}
                                initialValues={{
                                    name: currentUserFullName,
                                }}
                                plugin={slug}
                                hasAtLeastOneActiveLicense={hasAtLeastOneActiveLicense}
                                isPluginActiveForNetwork={isPluginActiveForNetwork}
                                onClose={() => {
                                    root.unmount();
                                }}
                                onDeactivate={() => {
                                    window.location.href = link.href;
                                }}
                            />
                        </Provider>,
                    );

                    e.preventDefault();

                    // Stop `real-utils` functionality
                    e.stopImmediatePropagation();
                    break;
                }
            }
        },
        true,
    );
}

export { listenPluginDeactivation };
