import { cookies } from 'next/headers';
import { messages } from '../messages';
import { MessageLangProps, isValidLanguage } from '../types';

export async function MessageLang({ text, data = [] }: MessageLangProps) {
    const cookieStore = await cookies();
    const savedLang = cookieStore.get('lang')?.value || 'ja';
    const lang = isValidLanguage(savedLang) ? savedLang : 'ja';

    let message = messages[lang][text];

    data.forEach((value, index) => {
        message = message.replace(new RegExp('\\{' + index + '\\}', 'g'), value);
    });

    return <span dangerouslySetInnerHTML={{__html: message}} />;
}