import { useRef } from "react";

import { yieldLazyLoad } from "@devowl-wp/react-utils";
import { extendCommonButtonsStylesheet } from "@devowl-wp/web-cookie-banner";

import { BlockerBody } from "./body/body.js";
import { BlockerFooter } from "./footer/footer.js";
import { BlockerHeader } from "./header/header.js";
import { useBlocker } from "../../contexts/blocker.js";
import { useBlockerStylesheet } from "../../hooks/blocker/useBlockerStylesheet.js";
import { CONTEXT_LATEST_DESIGN_VERSION } from "../../types/commonContext.js";

import type { ComponentProps, FC, HTMLAttributes } from "react";

const YieldBlockerHeader = yieldLazyLoad(Promise.resolve(BlockerHeader));
const YieldBlockerBody = yieldLazyLoad(Promise.resolve(BlockerBody));
const YieldBlockerFooter = yieldLazyLoad(Promise.resolve(BlockerFooter));

const BlockerTextContainer: FC<
    {
        closeIcon?: ComponentProps<typeof BlockerHeader>["closeIcon"];
    } & HTMLAttributes<HTMLDivElement>
> = ({ closeIcon, ...rest }) => {
    const blocker = useBlocker();
    const {
        designVersion = CONTEXT_LATEST_DESIGN_VERSION,
        blocker: { visualType, visualThumbnail, name },
        texts: { blockerHeadline },
        i18n: { skipToConsentChoices },
    } = blocker;
    const {
        Inner,
        Content,
        InnerBackground,
        A11ySkipToLink,
        a11yIds: { firstButton },
    } = useBlockerStylesheet().extend(...extendCommonButtonsStylesheet);
    const ref = useRef<HTMLDivElement>();

    return (
        <Inner ref={ref} className="wp-exclude-emoji" {...rest}>
            <A11ySkipToLink
                href={`#${firstButton}`}
                aria-label={`${blockerHeadline.replace(/{{name}}/gi, name)}, ${skipToConsentChoices}`}
            >
                {skipToConsentChoices}
            </A11ySkipToLink>
            {visualType === "wrapped" && (
                <InnerBackground src={visualThumbnail.url} alt={visualThumbnail.title} aria-hidden />
            )}
            <Content>
                <YieldBlockerHeader closeIcon={closeIcon} />
                <YieldBlockerBody />
                {designVersion === 1 && <YieldBlockerFooter />}
            </Content>
        </Inner>
    );
};

export { BlockerTextContainer };
