import { useMemo } from "react";

import type { TcfDeclarationFilter } from "@devowl-wp/cookie-consent-web-client";

import { useBanner } from "../../contexts/banner.js";

function useTcfVendors(filter: TcfDeclarationFilter) {
    const { tcf } = useBanner();

    if (!tcf) {
        return [];
    }

    const {
        gvl: { vendors: gvlVendors },
        model,
    } = tcf;

    return useMemo(
        () =>
            Object.values(gvlVendors)
                // Only show vendor if suitable for the current filter
                .filter(({ [filter === "consent" ? "purposes" : "legIntPurposes"]: usedPurposes }) =>
                    filter === "consent" ? true : usedPurposes.length > 0,
                )
                // We need to manually sort it again cause the `vendor-list.json#vendors` property uses numeric keys and
                // JavaScript does automatically sort it
                .sort(({ name: x }, { name: y }) => (x < y ? -1 : x > y ? 1 : 0)),
        [gvlVendors, filter, model],
    );
}

export { useTcfVendors };
