import { useEffect, useRef } from "react";

import { extendBannerBubbleStylesheet } from "@devowl-wp/web-cookie-banner";

import { BannerStickyBubble } from "./bubble.js";
import { useBanner } from "../../../contexts/banner.js";
import { useStylesheet } from "../../../contexts/stylesheet.js";
import { useBannerStylesheet } from "../../../hooks/banner/useBannerStylesheet.js";
import { AnimatedCss } from "../../animateCss.js";
import { Portal } from "../../portal.js";

import type { FC } from "react";

const BannerSticky: FC = () => {
    if (process.env.PLUGIN_CTX === "pro") {
        /* onlypro:start */
        const {
            visible,
            sticky: { animationsEnabled },
        } = useBanner();
        const { className } = useStylesheet();
        const stylesheet = useBannerStylesheet();
        const { stickyBar } = stylesheet.extend(...extendBannerBubbleStylesheet);
        const isAnimationEnabled = useRef(false);

        // The initial animation / on page switch should not be shown, but the fade animation
        // should take action when opening / closing the cookie banner
        useEffect(() => {
            isAnimationEnabled.current = true;
        }, [visible]);

        return (
            <Portal renderInContainer={document.body}>
                <AnimatedCss
                    animationIn="fadeIn"
                    animationInDuration={isAnimationEnabled.current && animationsEnabled ? 300 : 0}
                    animationOut="fadeOut"
                    animationOutDuration={animationsEnabled ? 300 : 0}
                    isVisible={!visible}
                    className={`${className} ${stylesheet.className} ${stickyBar}`}
                >
                    <BannerStickyBubble />
                </AnimatedCss>
            </Portal>
        );
        /* onlypro:end */
    } else {
        return null;
    }
};

export { BannerSticky };
