/* Langfuse Lens — i18n Module */
const STORAGE_KEY = 'lens_locale';

let translations = {};
let currentLocale = 'ko';

async function loadTranslations(locale) {
  try {
    const res = await fetch(`/static/locales/${locale}.json`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    translations = await res.json();
    currentLocale = locale;
  } catch (e) {
    console.warn(`[i18n] Failed to load ${locale}`, e);
    translations = {};
  }
}

export function t(key, params = {}) {
  const keys = key.split('.');
  let value = translations;
  for (const k of keys) {
    if (value && typeof value === 'object' && k in value) {
      value = value[k];
    } else {
      return key;
    }
  }
  if (typeof value !== 'string') return key;
  return value.replace(/\{(\w+)\}/g, (_, name) =>
    params[name] !== undefined ? String(params[name]) : `{${name}}`
  );
}

export function getLocale() {
  return currentLocale;
}

export function applyTranslations() {
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const key = el.getAttribute('data-i18n');
    const val = t(key);
    if (val !== key) el.textContent = val;
  });
  document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
    const key = el.getAttribute('data-i18n-placeholder');
    const val = t(key);
    if (val !== key) el.placeholder = val;
  });
  document.querySelectorAll('[data-i18n-title]').forEach(el => {
    const key = el.getAttribute('data-i18n-title');
    const val = t(key);
    if (val !== key) el.title = val;
  });
  document.querySelectorAll('[data-i18n-html]').forEach(el => {
    const key = el.getAttribute('data-i18n-html');
    const val = t(key);
    if (val !== key) el.innerHTML = val;
  });
  document.documentElement.lang = currentLocale;
}

export async function setLocale(locale) {
  localStorage.setItem(STORAGE_KEY, locale);
  await loadTranslations(locale);
  applyTranslations();
  const btn = document.getElementById('locale-toggle');
  if (btn) btn.textContent = locale === 'ko' ? 'EN' : 'KO';
}

// Auto-initialize: load translations before any dependent module runs
const savedLocale = localStorage.getItem(STORAGE_KEY) || 'ko';
await loadTranslations(savedLocale);

// Apply DOM translations + bind toggle button when DOM ready
function onReady() {
  applyTranslations();
  const btn = document.getElementById('locale-toggle');
  if (btn) {
    btn.textContent = currentLocale === 'ko' ? 'EN' : 'KO';
    btn.addEventListener('click', () => {
      setLocale(currentLocale === 'ko' ? 'en' : 'ko');
    });
  }
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', onReady);
} else {
  onReady();
}
