import { Fragment } from 'react';
import { useShared } from '@/site/hooks/use-shared';

/**
 * English terms the site keeps as they are on pages in other languages:
 * the brand's approach ("Medical Longevity") and the English half of a
 * mixed name ("Medikal Longevity").
 */
const ENGLISH = /(Medical Longevity|Longevity)/;

/**
 * Prints a text with its English terms marked lang="en".
 *
 * Use it wherever a name or label is shown in capitals: CSS `uppercase`
 * follows the language of the page, and Turkish rules would print
 * "MEDİCAL LONGEVİTY". A name that is English as a whole carries its own
 * `lang` (see TermLang in types.ts); this covers the terms inside a text.
 */
export function Term({ text }: { text: string }) {
    const { locale } = useShared();

    if (locale === 'en' || !ENGLISH.test(text)) {
        return text;
    }

    // One element whatever is inside: in a flex row (an eyebrow) the parts
    // would otherwise be separate items, with the row's gap between them.
    return (
        <span>
            {text.split(ENGLISH).map((part, index) =>
                index % 2 === 1 ? (
                    <span key={index} lang="en">
                        {part}
                    </span>
                ) : (
                    <Fragment key={index}>{part}</Fragment>
                ),
            )}
        </span>
    );
}
