import { Fragment, useCallback } from "react";

import { jsxJoin } from "@devowl-wp/react-utils";

import { FooterLink } from "../../components/common/footer/link.js";
import { FooterPoweredByLink } from "../../components/common/footer/poweredByLink.js";
import { useBannerOrBlocker } from "../useBannerOrBlocker.js";

import type { AnchorHTMLAttributes, DOMAttributes } from "react";

function useCommonFooterLinks({
    onClose,
    putPoweredByLinkInRow,
    row1,
    row1End,
}: {
    onClose?: DOMAttributes<HTMLAnchorElement>["onClick"];
    putPoweredByLinkInRow?: number;
    row1?: JSX.Element[];
    row1End?: JSX.Element[];
} = {}) {
    const {
        i18n: { close },
        footerDesign: { poweredByLink },
        poweredLink,
        links = [],
        affiliate,
    } = useBannerOrBlocker();

    const targetBlankAttributes: AnchorHTMLAttributes<HTMLAnchorElement> = { target: "_blank", rel: "noopener" };

    const rows = [
        // Row 1
        [
            onClose && (
                <FooterLink href="#" onClick={onClose} key="close" interaction-player-skip="1">
                    <strong>{close}</strong>
                </FooterLink>
            ),
            ...(row1 || []),
            ...links.map(
                ({ label, url, isTargetBlank }, i) =>
                    !!label &&
                    !!url && (
                        <FooterLink
                            key={`${i.toString()}-links`}
                            href={url}
                            {...(isTargetBlank === undefined || isTargetBlank ? targetBlankAttributes : {})}
                        >
                            {label}
                        </FooterLink>
                    ),
            ),
            ...(row1End || []),
        ].filter(Boolean),
        // Row 2
        [], // Nothing yet
    ];

    if (!!poweredLink && poweredByLink) {
        rows[putPoweredByLinkInRow || 0].push(
            <FooterPoweredByLink key="poweredBy" poweredLink={poweredLink} affiliate={affiliate} />,
        );
    }

    const render = useCallback(
        (rows: JSX.Element[][]) =>
            jsxJoin(
                rows.map((row) =>
                    row.length ? (
                        <Fragment key={row[0].key}>{jsxJoin(row, <span aria-hidden> &bull; </span>)}</Fragment>
                    ) : null,
                ),
                <br aria-hidden />,
            ),
        [],
    );

    return { rows, render };
}

export { useCommonFooterLinks };
