import { Fragment } from "react";

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

import { useStylesheet } from "../../../contexts/stylesheet.js";
import { useBannerOrBlocker } from "../../../hooks/useBannerOrBlocker.js";

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

const BodyDescription: FC<
    {
        description?: string;
        nl2br?: boolean;
        teachings?: ReactNode[];
        isPostamble?: boolean;
    } & HTMLAttributes<HTMLParagraphElement>
> = ({ description, nl2br, teachings, isPostamble, children, ...rest }) => {
    const { individualPrivacyOpen } = useBannerOrBlocker();
    const { DescriptionContainer, Teaching, TeachingSeparator } = useStylesheet().extend(...extendTeachingStylesheet);

    return (
        <DescriptionContainer
            style={
                [
                    true,
                    // For content blockers, automatically use the "individual layout" text align
                    undefined,
                ].indexOf(individualPrivacyOpen) > -1
                    ? undefined
                    : { textAlign: "inherit" }
            }
        >
            {children}
            {!!description && (
                <p
                    role="presentation"
                    {...rest}
                    dangerouslySetInnerHTML={{
                        __html: nl2br ? description.replace(/\n/gm, '<br aria-hidden="true" />') : description,
                    }}
                />
            )}
            {teachings?.length > 0 && (
                <Fragment>
                    {(!!description || isPostamble) && <TeachingSeparator />}
                    {teachings.map((teaching) =>
                        typeof teaching === "string" ? (
                            <Teaching
                                key={teaching}
                                style={{ marginBottom: isPostamble ? 7 : 0 }}
                                dangerouslySetInnerHTML={{ __html: teaching }}
                            />
                        ) : (
                            teaching
                        ),
                    )}
                </Fragment>
            )}
        </DescriptionContainer>
    );
};

export { BodyDescription };
