/**
 * The entry point for the admin side wp-admin resource.
 */
import "@devowl-wp/utils/antd.scss";
import "@devowl-wp/react-folder-tree/legacy/style/style.scss";
import "@devowl-wp/react-folder-tree/legacy/style/theme-wordpress.scss";
import "./style/admin.scss";
import $ from "jquery";
import { createRoot } from "react-dom/client";

import { waitObject } from "@devowl-wp/react-utils";
import { handleCorruptRestApi } from "@devowl-wp/utils";

import { AppTree } from "./components/appTree.js";
import { Provider } from "./components/provider.js";
import { addSwitchToListTable } from "./others/addSwitchToListTable.js";
import { RootStore } from "./store/stores.js";
import { request } from "./utils/request.js";

handleCorruptRestApi({
    [RootStore.get.optionStore.restNamespace]: async () => {
        await request({
            location: {
                path: "/plugin",
            },
        });
    },
});

$(document).ready(async () => {
    const {
        optionStore: { others },
    } = RootStore.get;
    const {
        typenow,
        screenSettings: { isActive },
    } = others;

    // Compatibility with Elementor "Popup" cause it listens to the first "Add new" button
    if (process.env.PLUGIN_CTX === "pro") {
        /* onlypro:start */
        if (typenow === "elementor_library") {
            await waitObject(() => (window as any).elementorNewTemplate);
        }
        /* onlypro:end */
    }

    // Avoid flickering
    $("#wpbody").fadeTo(100, 1);

    if (isActive) {
        $("body").addClass("activate-aiot");
        const container = $("<div/>").prependTo("body.wp-admin #wpbody").addClass("rcl-container").get(0);

        createRoot(container).render(
            <Provider>
                <AppTree />
            </Provider>,
        );
    } else {
        addSwitchToListTable();
    }
});

$("link#dark_mode-css").length && $("body").addClass("aiot-wp-dark-mode");

// Expose this functionalities to add-ons, but you need to activate the library functionality
// in your webpack configuration, see also https://webpack.js.org/guides/author-libraries/
export * from "@devowl-wp/utils";
export * from "./wp-api/index.js";
export * from "./store/index.js";
