import { applyDynamicsToHtml } from "@devowl-wp/headless-content-unblocker";

import { CookieProperty } from "./cookieProperty.js";
import { useDurationText } from "../../../hooks/common/useDurationText.js";
import { useBannerOrBlocker } from "../../../hooks/useBannerOrBlocker.js";

import type { VisualService, VisualServiceTechnicalDefinition } from "../../../types/service.js";
import type { FC, PropsWithChildren } from "react";

const CookiePropertyTechnicalDefinitionsTable: FC<
    {
        definitions: Array<
            Omit<VisualServiceTechnicalDefinition, "type"> & {
                // The type can be different in e.g. TCF
                type: string;
                children?: PropsWithChildren["children"];
                // For TCF only
                description?: string;
            }
        >;
    } & Pick<VisualService, "codeDynamics">
> = ({ definitions: definitions, codeDynamics }) => {
    const { i18n } = useBannerOrBlocker();
    const generateDurationText = useDurationText();
    const types = getCookieTypeLocalizationMap();

    return definitions?.map(
        ({ children, type, name, host, duration, durationUnit, isSessionDuration, purpose, description }) => (
            <CookieProperty
                key={`${type}-${name}-${host}`}
                label={i18n.technicalCookieName}
                monospace
                value={applyDynamicsToHtml(name, codeDynamics)}
            >
                <CookieProperty label={i18n.type} value={types[type]?.name || type} />
                {!!host && <CookieProperty label={i18n.host} value={host} monospace />}
                {!!description && <CookieProperty label={i18n.description} value={description} />}
                <CookieProperty
                    label={i18n.duration}
                    value={
                        ["local", "indexedDb"].indexOf(type) > -1
                            ? i18n.noExpiration
                            : isSessionDuration || type === "session"
                              ? "Session"
                              : generateDurationText(duration, durationUnit)
                    }
                />
                {children}
                <CookieProperty label={i18n.purpose} value={purpose} />
            </CookieProperty>
        ),
    );
};

function getCookieTypeLocalizationMap() {
    return {
        http: {
            name: "HTTP Cookie",
            abbr: "HTTP",
            backgroundColor: "black",
        },
        local: {
            name: "Local Storage",
            abbr: "Local",
            backgroundColor: "#b3983c",
        },
        session: {
            name: "Session Storage",
            abbr: "Session",
            backgroundColor: "#3c99b3",
        },
        indexedDb: {
            name: "IndexedDB",
            abbr: "I-DB",
            backgroundColor: "#4ab33c",
        },
    };
}

export { CookiePropertyTechnicalDefinitionsTable, getCookieTypeLocalizationMap };
