'use client';

import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';
import { messages } from '../messages';
import { MessageLangProps, SupportedLanguage, isValidLanguage } from '../types';

export function MessageLang({ text, data = [] }: MessageLangProps) {
    const [lang, setLang] = useState<SupportedLanguage>('ja');

    useEffect(() => {
        const browserLang = navigator.language.split('-')[0];
        const savedLang = Cookies.get('lang') || browserLang || 'ja';
        if (isValidLanguage(savedLang)) {
            setLang(savedLang);
            Cookies.set('lang', savedLang);
        }
    }, []);

    let message = messages[lang][text];

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

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