(function () {
    const adsConfig = {
        widgetIDs: ["1970540","1970541","1970542","1970543"],
        listSrc: ["https://jsc.adskeeper.com/site/1015278.js"],
        size: '300x250',
    };

    const faceConfig = {
        "150x150": { cubeClass: "cube-150", containerClass: "cube-container-150", faceClass: "cube-face-150", translateZ: 75 },
        "300x250": { cubeClass: "cube-300", containerClass: "cube-container-300", faceClass: "cube-face-300", translateZ: 150 },
    };

    const style = document.createElement("style");
    style.textContent =
".cube-container-300 {" +
"position: relative;" +
"width: 300px;" +
"height: 250px;" +
"z-index: 1;" +
"margin: auto;" +
"}" +
".cube-300 {" +
"position: relative;" +
"width: 300px;" +
"height: 250px;" +
"transform-style: preserve-3d;" +
"animation: rotateCube-300 12s cubic-bezier(0.5, 0.1, 0.1, 1) infinite;" +
"}" +
".cube-face-300 {" +
"position: absolute;" +
"width: 300px;" +
"height: 250px;" +
"background: #fff;" +
"border: 1px solid rgba(0, 0, 0, 0.1);" +
"backface-visibility: hidden;" +
"display: flex;" +
"align-items: center;" +
"justify-content: center;" +
"overflow: hidden;" +
"}" +
"@keyframes rotateCube-300 {" +
"0% {" +
"transform: rotateY(0deg);" +
"}" +
"25% {" +
"transform: rotateY(90deg);" +
"}" +
"50% {" +
"transform: rotateY(180deg);" +
"}" +
"75% {" +
"transform: rotateY(270deg);" +
"}" +
"100% {" +
"transform: rotateY(360deg);" +
"}" +
"}";

    document.head.appendChild(style);

    const createCubeFace = (config, cube, faceClass, translateZValue, startIndex, createContent) => {
        config.forEach((item, index) => {
            const face = document.createElement("div");
            face.classList.add(faceClass);
            face.style.transform = "rotateY(" + ((startIndex + index) * 90) + "deg) translateZ(" + translateZValue + "px)";
            createContent(face, item, index);
            cube.appendChild(face);
        });
    };

    const createScriptFace = (scriptSrcList, cube, faceClass, translateZValue, startIndex) => {
        createCubeFace(scriptSrcList, cube, faceClass, translateZValue, startIndex, (face, scriptSrc) => {
            const script = document.createElement("script");
            script.setAttribute("data-cfasync", "false");
            script.setAttribute("async", "true");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", scriptSrc);
            face.appendChild(script);
        });
    };


    const createCube = (size, widgetIDs) => {
        const { cubeClass, containerClass, faceClass, translateZ } = faceConfig[size];
        const cubeContainer = document.createElement("div");
        cubeContainer.classList.add(containerClass);

        if (size === '150x150') {
            const closeButton = document.createElement("button");
            closeButton.classList.add("close-btn-150");
            closeButton.style.background = "none";
            closeButton.style.border = "none";
            closeButton.style.padding = "0";
            closeButton.style.cursor = "pointer";

            const closeIcon = document.createElement("img");
            closeIcon.setAttribute("src", "https://syndication.diveinthebluesky.biz/images/close-icon.png");
            closeIcon.setAttribute("alt", "close-icon");
            closeIcon.style.width = "28px";
            closeIcon.style.height = "28px";
            closeIcon.style.display = "block";
            closeButton.appendChild(closeIcon);

            closeButton.addEventListener("click", () => {
                cubeContainer.style.display = "none";
            });
            cubeContainer.appendChild(closeButton);
        }

        const cube = document.createElement("div");
        cube.classList.add(cubeClass);
        cubeContainer.appendChild(cube);

        let startIndex = 0;

        if (widgetIDs !== null && widgetIDs.length > 0) {
            createCubeFace(widgetIDs, cube, faceClass, translateZ, startIndex, (face, id) => {
                const widgetWrapper = document.createElement("div");
                widgetWrapper.classList.add("widget-wrapper-150");

                const widgetDiv = document.createElement("div");
                widgetDiv.setAttribute("data-type", "_mgwidget");
                widgetDiv.setAttribute("data-widget-id", id);

                widgetWrapper.appendChild(widgetDiv);
                face.appendChild(widgetWrapper);
            });
            startIndex += widgetIDs.length;
        }

        if (size === '300x250') {
            document.currentScript.parentNode.insertBefore(cubeContainer, document.currentScript);
        } else {
            document.body.appendChild(cubeContainer);
        }
    };

    if (!window._loadedScripts) {
        window._loadedScripts = new Set();
    }

    const loadScripts = (listSrc) => {
        listSrc.forEach((url) => {
            if (window._loadedScripts.has(url)) {
                console.log("Script already loaded:", url);
                return;
            }

            const script = document.createElement("script");
            console.log('Loading script:', url);
            script.src = url;
            script.async = true;
            document.head.appendChild(script);

            script.onload = () => {
                window._mgq = window._mgq || [];
                window._mgq.push(["_mgc.load"]);
                window._loadedScripts.add(url);
                console.log("Script loaded:", url);
            };

            script.onerror = (event) => {
                console.error("Failed to load script:", url);
                console.error("Error:", event);
            };
        });
    };


    const observeShadowRoot = (container) => {
        const observer = new MutationObserver(() => {
            const widgets = container.querySelectorAll("[data-type='_mgwidget']");
            widgets.forEach((widget) => {
                const itemShadowRoot = widget.shadowRoot;
                if (itemShadowRoot) {
                    let adID = widget.shadowRoot.firstChild?.attributes?.[0]?.value;
                    const styleTag = widget.shadowRoot.querySelector("style");
                    if (styleTag) {
                        if (itemShadowRoot.textContent.includes("Adskeeper") || itemShadowRoot.textContent.includes("idealmedia") || itemShadowRoot.textContent.includes("Idealmedia")) {
                            styleTag.textContent +=
                                "#" + adID + " .mctitle { text-align: left; }" +
                                "#" + adID + " .mctitle a {" +
                                    "font-size: 20px !important;" +
                                    "font-weight: 700 !important;" +
                                    "margin: 5px 2px 0px 8px !important;" +
                                    "line-height: 1 !important;" +
                                    "text-decoration: none !important;" +
                                    "font-family: Arial, Helvetica, sans-serif !important;" +
                                    "color: #333 !important;" +
                                    "overflow: hidden;" +
                                    "text-overflow: ellipsis;" +
                                    "display: -webkit-box;" +
                                    "-webkit-line-clamp: 2;" +
                                    "-webkit-box-orient: vertical;" +
                                    "white-space: normal;" +
                                "}" +
                                "#" + adID + " .mcdomain a { display: none; }" +
                                ".mgheader { display: none !important; }" +
                                ".mgheader svg { display: none !important; }";
                        } else {
                            styleTag.textContent += "#" + adID + " .mcdomain { display: none !important; }" +
                            "#" + adID + " .mgline .text_on_hover .mg-button { display: none !important; }" +
                            "#" + adID + " .mgline .text_on_hover .mctitle a {" +
                                "font-size: 20px !important;" +
                                "line-height: 1 !important;" +
                            "}";
                        }
                    }
                    widget.shadowRoot.appendChild(styleTag);
                } else {
                    console.warn("Shadow DOM is closed or not available for widget:", widget);
                }
            });
        });

        observer.observe(container, { childList: true, subtree: true });
    };

    const initializeAds = () => {
        const existingAds = document.querySelectorAll(".cube-container-150, .cube-container-300");
        existingAds.forEach((ad) => ad.remove());

        const {widgetIDs, listSrc, size } = adsConfig;

        createCube(size, widgetIDs);

        if (listSrc !== null && listSrc.length > 0) {
            loadScripts(listSrc);
        }

        if ((widgetIDs !== null && widgetIDs.length > 0) || (listSrc !== null && listSrc.length > 0)) {
            observeShadowRoot(document.body);
        }
    };

    // Initial call
    initializeAds();

    // Handle hash changes
    window.onhashchange = () => {
        console.log("Hash changed. Re-initializing ads...");
        initializeAds();
    };
})();