/**
 * Entrypoint for customize preview when the banner needs to be customized.
 * The main difference to `banner.tsx` is, that we use an observable mobx store
 * instead of a simple context.
 */

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

import { listenChanges } from "@devowl-wp/customize";
import { ready, waitObject } from "@devowl-wp/react-utils";

import { CustomizeBanner } from "./components/customizeBanner.js";
import { applyCustomizeBannerPreview } from "./others/customizeBannerPreview.js";
import { RootStore } from "./store/stores.js";
import { getOtherOptionsFromWindow } from "./utils/getOtherOptionsFromWindow.js";

const bannerContainer = document.createElement("div");
bannerContainer.className = "rcb-customize-banner-container";

function renderBanner() {
    const {
        customizeIdsBanner: {
            settings: {
                texts: { poweredBy },
            },
        },
        poweredByTexts,
    } = getOtherOptionsFromWindow();

    const currentPoweredBy = wp.customize(poweredBy).get();

    // Generate powered-by link
    const poweredLink = document.createElement("a");
    poweredLink.target = "_blank";
    poweredLink.href = RootStore.get.optionStore.others.pluginUrl;
    poweredLink.innerHTML = poweredByTexts[currentPoweredBy];

    createRoot(document.body.appendChild(bannerContainer)).render(
        <RootStore.StoreProvider>
            <CustomizeBanner poweredLink={poweredLink} />
        </RootStore.StoreProvider>,
    );
}

ready(async () => {
    // Wait at least one customize parameter is registered
    await waitObject(() => wp.customize("rcb-banner-texts-powered-by"));

    const {
        customizeIdsBanner: {
            settings: {
                texts: { poweredBy },
            },
        },
    } = getOtherOptionsFromWindow();

    // Some values in customizer are not directly passed within our context
    // Listen to changes and rerender.
    listenChanges(
        {
            texts: {
                poweredBy,
            },
        },
        () => setTimeout(renderBanner, 0), // Delay execution so in `renderBanner` the newest values are available
    );

    renderBanner();

    document.querySelectorAll<HTMLTableElement>(".devowl-wp-react-cookie-banner-cookie-policy").forEach((element) => {
        import(
            /* webpackChunkName: "cookie-policy", webpackMode: "lazy-once" */ "@devowl-wp/react-cookie-banner/cookie-policy"
        ).then(({ createCookiePolicyTable }) => createCookiePolicyTable(element));
    });
});

applyCustomizeBannerPreview();

export * from "./store/index.js";
