import { Fragment } from "react";

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

import { CookieProperty } from "./cookieProperty.js";
import { useStylesheet } from "../../../contexts/stylesheet.js";
import { createSuperScriptTagFactory } from "../../../hooks/common/useTeachings.js";
import { useBannerOrBlocker } from "../../../hooks/useBannerOrBlocker.js";
import { calculateSafetyMechanismsFromSpecialTreatments } from "../../../others/calculateSafetyMechanismsFromSpecialTreatments.js";

import type { FC } from "react";

const CookiePropertyDataTransmission: FC<
    Parameters<typeof calculateSafetyMechanismsFromSpecialTreatments>[0]["service"] & {
        /**
         * Additional transfer mechanisms which we need to mention, useful for the TCF standard.
         */
        mechanisms?: (
            usedMechanisms: ReturnType<typeof calculateSafetyMechanismsFromSpecialTreatments>["result"][""][0][],
        ) => string[];
    }
> = ({ mechanisms, ...service }) => {
    const { screenReaderOnlyClass } = useStylesheet();
    const createSuperScriptTag = createSuperScriptTagFactory(screenReaderOnlyClass);
    const {
        iso3166OneAlpha2,
        predefinedDataProcessingInSafeCountriesLists,
        territorialLegalBasis,
        isDataProcessingInUnsafeCountries,
        i18n: {
            dataProcessingInThirdCountries,
            territorialLegalBasisArticles: {
                "dsg-switzerland": {
                    dataProcessingInUnsafeCountries: territorialLegalBasisArticleDataProcessingInUnsafeCountriesDsg,
                },
                "gdpr-eprivacy": {
                    dataProcessingInUnsafeCountries: territorialLegalBasisArticleDataProcessingInUnsafeCountriesGdpr,
                },
            },
            safetyMechanisms: {
                label,
                eu,
                switzerland,
                adequacyDecision,
                contractualGuaranteeSccSubprocessors,
                standardContractualClauses,
                bindingCorporateRules,
            },
        },
    } = useBannerOrBlocker();
    const { result, filter, isGdpr } = calculateSafetyMechanismsFromSpecialTreatments({
        predefinedDataProcessingInSafeCountriesLists,
        territorialLegalBasis,
        isDataProcessingInUnsafeCountries,
        service,
    });
    const entries = Object.entries(result);

    const mechanismToText: Record<(typeof result)[""][0], string> = {
        A: adequacyDecision,
        "A-EU": `${adequacyDecision} (${eu})`,
        "A-CH": `${adequacyDecision} (${switzerland})`,
        B: standardContractualClauses,
        C: contractualGuaranteeSccSubprocessors,
        D:
            territorialLegalBasis.length > 1
                ? // covered by D-EU and D-CH
                  ""
                : isGdpr
                  ? territorialLegalBasisArticleDataProcessingInUnsafeCountriesGdpr
                  : territorialLegalBasisArticleDataProcessingInUnsafeCountriesDsg,
        "D-EU": territorialLegalBasisArticleDataProcessingInUnsafeCountriesGdpr,
        "D-CH": territorialLegalBasisArticleDataProcessingInUnsafeCountriesDsg,
        E: bindingCorporateRules,
    };

    const usedMechanisms = Object.keys(mechanismToText).filter(
        (mechanism) => filter((b) => b === mechanism).length > 0,
    ) as unknown as (keyof typeof mechanismToText)[];
    const allMechanisms = mechanisms ? mechanisms(usedMechanisms) : usedMechanisms;

    return (
        <Fragment>
            {entries.length > 0 && (
                <CookieProperty
                    label={dataProcessingInThirdCountries}
                    value={jsxJoin(
                        entries.map(([country, mechanism]) => (
                            <span
                                key={country}
                                dangerouslySetInnerHTML={{
                                    __html: createSuperScriptTag(
                                        mechanism.map((m) => [m, mechanismToText[m]]),
                                        iso3166OneAlpha2[country] ?? country,
                                    ),
                                }}
                            />
                        )),
                        ", ",
                    )}
                />
            )}
            {allMechanisms.length > 0 && (
                <CookieProperty
                    label={label}
                    value={jsxJoin(
                        allMechanisms.map((mechanism) => (
                            <span
                                key={mechanism}
                                dangerouslySetInnerHTML={{
                                    __html: mechanismToText[mechanism]
                                        ? createSuperScriptTag([[mechanism]], mechanismToText[mechanism])
                                        : mechanism,
                                }}
                            />
                        )),
                        ", ",
                    )}
                />
            )}
        </Fragment>
    );
};

export { CookiePropertyDataTransmission };
