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

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

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

const Group: FC<
    {
        legend?: string;
        headline: ReactNode;
        /**
         * Pass `true` if you want to render a group inside a group component to avoid unnecessary margins and paddings.
         */
        borderless?: boolean;
    } & HTMLAttributes<HTMLDivElement>
> = ({ headline, borderless, children, legend, ...rest }) => {
    const { Group, GroupInner, GroupDescription, screenReaderOnlyClass } = useStylesheet().extend(
        ...extendCommonGroupsStylesheet,
    );
    const useLegend = legend ? legend : typeof headline === "string" ? headline : undefined;

    const inner = (
        <GroupInner>
            {useLegend && <legend className={screenReaderOnlyClass}>{useLegend}</legend>}
            <span aria-hidden={!!useLegend}>{headline}</span>
            {children && <GroupDescription>{children}</GroupDescription>}
        </GroupInner>
    );

    return borderless ? (
        <div className="group" {...rest}>
            {inner}
        </div>
    ) : (
        <Group {...rest}>{inner}</Group>
    );
};

export { Group };
