import {__} from "./globals";
import {decode} from "he";
import {CardType} from "./tree/cards";

/**
 * Decodes HTML entities in a string.
 * Converts entities like &amp; to &, &lt; to <, etc.
 * IMPORTANT: This does NOT render HTML tags - it only decodes entities to their characters.
 * For example: "&amp;" becomes "&", but "<script>" remains as text, not executed code.
 */
export const decodeHtmlEntities = (text: string): string => {
    return decode(text);
}

/**
 * Returns a CardType with decoded HTML entities in name and description fields.
 * Use this wrapper when displaying component metadata from PHP that may contain escaped characters.
 */
export const withDecodedEntities = <T extends Partial<CardType>>(cardType: T): T => {
    return {
        ...cardType,
        name: cardType.name ? decodeHtmlEntities(cardType.name) : cardType.name,
        description: cardType.description ? decodeHtmlEntities(cardType.description) : cardType.description,
    };
}

export const render = (value: string | Function) : string => {
    if (typeof value === 'function') {
        let Value = value

        return <Value />
    }
    return value;
}

export const getLabelForComponentType = (componentType: string): string => {
    if (componentType.startsWith('filter')) {
        return __('Filters')
    } else if (componentType.startsWith('condition')) {
        return __('Conditions')
    } else if (componentType.startsWith('offer')) {
        return __('Offers')
    }

    return __('Components')
}