import { Fragment, useCallback, useLayoutEffect, useRef, useState } from "react";

import { CookieProperty } from "./cookieProperty.js";
import { joinWithAndSeparator } from "../../../hooks/common/useTeachings.js";
import { useBannerOrBlocker } from "../../../hooks/useBannerOrBlocker.js";
import { LinkToggle } from "../linkToggle.js";

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

const CookiePropertyListLessRelevant: FC<
    PropsWithChildren<{
        expandable?: boolean;
        labelModifications?: Record<string, string>;
        groupLabel?: ComponentProps<typeof LinkToggle>["groupLabel"];
    }>
> = ({ expandable, children, labelModifications = {}, groupLabel }) => {
    const {
        group: { detailsHideLessRelevant },
        i18n: { andSeparator, showLessRelevantDetails, hideLessRelevantDetails },
    } = useBannerOrBlocker();
    const ref = useRef<HTMLDivElement>(null);
    const [joinedAnd, setJoinedAnd] = useState("");

    useLayoutEffect(() => {
        const { current } = ref;
        if (current) {
            const labels = [
                ...new Set(
                    [...(current.querySelectorAll(":scope>div>strong") as NodeListOf<HTMLElement>)].map((c) => {
                        const originalLabel = c.innerText.replace(/:?\s+$/, "");
                        return labelModifications[originalLabel] || originalLabel;
                    }),
                ),
            ];

            setJoinedAnd(joinWithAndSeparator(labels, andSeparator));
        }
    }, [ref.current, labelModifications]);

    const replaceVariables = useCallback((str: string) => str.replace("%s", joinedAnd), [joinedAnd]);

    return detailsHideLessRelevant && expandable ? (
        <div aria-hidden={!joinedAnd} hidden={!joinedAnd}>
            <CookieProperty
                value={
                    <Fragment>
                        <br />
                        <LinkToggle
                            showMore={replaceVariables(showLessRelevantDetails)}
                            hideMore={replaceVariables(hideLessRelevantDetails)}
                            style={{ fontStyle: "italic" }}
                            forceRender
                            groupLabel={groupLabel}
                        >
                            <div ref={ref}>
                                <br />
                                {children}
                            </div>
                        </LinkToggle>
                    </Fragment>
                }
            />
        </div>
    ) : (
        children
    );
};

export { CookiePropertyListLessRelevant };
