// 계층구조 사용시
async function loadTranslations(lang) {
    try {
        const response = await fetch(`/i18n/translations.${lang}.json`);
        if (!response.ok) {
            throw new Error(`Failed to load translations for ${lang}`);
        }
        return await response.json();
    } catch (error) {
        console.error(error);
        return {};
    }
}

async function localizePage(lang) {
    const translations = await loadTranslations(lang);

    const elements = document.querySelectorAll('[data-i18n]');
    elements.forEach(element => {
        const key = element.dataset.i18n;
        const localizedText = findNestedValue(translations, key);
        if (localizedText) {
            element.textContent = localizedText;
        }
    });
}

function findNestedValue(obj, key) {
    if (obj.hasOwnProperty(key)) {
        return obj[key];
    }
    for (const prop in obj) {
        if (typeof obj[prop] === 'object' && obj[prop] !== null) {
            const result = findNestedValue(obj[prop], key);
            if (result) {
                return result;
            }
        }
    }
    return null;
}

document.addEventListener('DOMContentLoaded', async () => {
    const storedLang = localStorage.getItem('lang');
    
    if (storedLang) {
        await localizePage(storedLang);
        return;
    }
    
    const urlParams = new URLSearchParams(window.location.search);
    const queryLang = urlParams.get('lang');
    
    const lang = queryLang || 'ko';
    
    localStorage.setItem('lang', lang);
    await localizePage(lang);
});

// 계층구조 미사용시 코드는 주석 처리된 상태로 유지