import type { OptInEvent } from "@devowl-wp/cookie-consent-web-client";
import { OPT_IN_EVENT } from "@devowl-wp/cookie-consent-web-client";
import type { OptInContentBlockerEvent } from "@devowl-wp/headless-content-unblocker";
import { OPT_IN_CONTENT_BLOCKER, putHtmlCodeToDom } from "@devowl-wp/headless-content-unblocker";
import { waitObject } from "@devowl-wp/react-utils";

let amazonWidgetsSlotNum = 0;

/**
 * Some templates have custom opt-in coding, e. g. Amazon Widgets.
 */
function listenTemplateOptIn() {
    document.addEventListener(OPT_IN_EVENT, (async ({
        detail: {
            service: { presetId, codeOptIn, codeDynamics },
        },
    }: CustomEvent<OptInEvent<{ presetId: string }>>) => {
        switch (presetId) {
            case "amazon-associates-widget": {
                const { amznAssoWidgetHtmlId } = codeDynamics || {};
                if (amznAssoWidgetHtmlId) {
                    const element = document.getElementById(amznAssoWidgetHtmlId);

                    if (element) {
                        const slotNum = amazonWidgetsSlotNum;
                        amazonWidgetsSlotNum++;
                        putHtmlCodeToDom(codeOptIn, codeDynamics, element);

                        // Amazon Widgets is using `document.write`, we need to manually move the ad container...
                        const adContainer = await waitObject(
                            () =>
                                document.querySelector(
                                    `[id^="amzn_assoc_ad_div_"][id$="${slotNum}"]`,
                                ) as HTMLDivElement,
                            500,
                            50,
                        );
                        if (adContainer) {
                            element.appendChild(adContainer);
                        }
                    }
                }
                break;
            }
            case "google-maps": {
                document.addEventListener(OPT_IN_CONTENT_BLOCKER, (async ({
                    detail: { element },
                }: CustomEvent<OptInContentBlockerEvent>) => {
                    const { et_pb_map_init, jQuery } = window as unknown as {
                        et_pb_map_init: any;
                        jQuery: JQueryStatic;
                    };
                    if (jQuery && element.matches(".et_pb_map") && et_pb_map_init) {
                        await waitObject(() => (window as any).google);
                        et_pb_map_init(jQuery(element).parent());
                    }
                }) as any);
                break;
            }
            default:
                break;
        }
    }) as any);
}

export { listenTemplateOptIn };
