import { forwardRef, useCallback } from "react";

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

import { useBanner } from "../../../contexts/banner.js";
import { useBannerStylesheet } from "../../../hooks/banner/useBannerStylesheet.js";
import { useCommonFooterLinks } from "../../../hooks/common/useFooterLinks.js";
import { FooterLink } from "../../common/footer/link.js";
import { LanguageSwitcher } from "../../common/languageSwitcher.js";

import type { DOMAttributes } from "react";

const BannerFooter = forwardRef<HTMLDivElement>((_, ref) => {
    const { FooterContainer } = useBannerStylesheet().extend(...extendBannerContentStylesheet);
    const banner = useBanner();
    const {
        isTcf,
        layout: { type },
        footerDesign: { languageSwitcher: languageSwitcherChoice },
        individualPrivacyOpen,
        onClose,
        i18n: { tcf },
        isConsentRecord,
        languageSwitcher,
        set,
    } = banner;

    const handleClose: DOMAttributes<HTMLAnchorElement>["onClick"] = useCallback(
        (e) => {
            onClose();
            e.preventDefault();
        },
        [onClose],
    );

    const { rows: links, render: renderLinks } = useCommonFooterLinks({
        onClose: isConsentRecord ? handleClose : undefined,
        putPoweredByLinkInRow: type === "banner" ? 0 : 1,
        row1: [
            process.env.IS_TCF === "1" && isTcf && !individualPrivacyOpen && (
                <FooterLink href="#" onClick={() => set({ individualPrivacyOpen: true })} key="vendorList">
                    {tcf.vendorList}
                </FooterLink>
            ),
        ],
        row1End: [
            languageSwitcher?.length > 0 && languageSwitcherChoice && languageSwitcherChoice !== "disabled" && (
                <LanguageSwitcher key="languageSwitcher" />
            ),
        ],
    });

    return (
        <FooterContainer ref={ref}>
            <div>{renderLinks(links)}</div>
        </FooterContainer>
    );
});

export { BannerFooter };
