import { forwardRef } from "react";

import { extendBannerContentStylesheet, extendCommonContentStylesheet } from "@devowl-wp/web-cookie-banner";

import { BannerCloseIcon } from "./closeIcon.js";
import { useBanner } from "../../../contexts/banner.js";
import { useBannerStylesheet } from "../../../hooks/banner/useBannerStylesheet.js";

const BannerHeader = forwardRef<
    HTMLDivElement,
    {
        className: string;
    }
>(({ className }, ref) => {
    const stylesheet = useBannerStylesheet();
    const { a11yIds, HeaderContainer, hasCloseIcon, HeaderTitle } = stylesheet
        .extend(...extendBannerContentStylesheet)
        .extend(...extendCommonContentStylesheet);

    const {
        headerDesign: { logo, logoRetina, logoAlt },
        decision: { showCloseIcon },
        texts: { headline },
        activeAction,
        individualPrivacyOpen,
        individualTexts,
        i18n: { headerTitlePrivacyPolicyHistory },
    } = useBanner();

    // Calculate logo
    const useRetina = logoRetina && !logo?.endsWith(".svg") && window.devicePixelRatio > 1;
    const useLogo = useRetina ? logoRetina : logo;

    // Calculate headline
    const useCloseIcon = !!showCloseIcon || !!activeAction;
    const useHeadline = individualPrivacyOpen
        ? activeAction === "history"
            ? headerTitlePrivacyPolicyHistory
            : individualTexts.headline
        : headline;

    return (
        <HeaderContainer ref={ref} className={className}>
            <div>
                {!!useLogo && <img aria-hidden alt={logoAlt || ""} src={useLogo} />}
                {!!useHeadline && (
                    <HeaderTitle id={a11yIds.headline} className={useCloseIcon ? hasCloseIcon : undefined}>
                        {useHeadline}
                    </HeaderTitle>
                )}
                {useCloseIcon && <BannerCloseIcon />}
            </div>
        </HeaderContainer>
    );
});

export { BannerHeader };
