// i18n del LECTOR — strings de UI traducidos a ES / EN / KO.
// El admin se queda solo en español.
//
// Uso:
//   const lang = window.useLang();
//   const t = window.t;
//   t("home.read")  // "Leer" / "Read" / "읽기"
//
// Cuando user cambia de idioma, dispatchamos "trooper:lang-changed" para que
// componentes con cache (que leyeron lang via React.useState) re-rendereen.

const TROOPER_LANG_KEY = "trooper_lang_v1";
const SUPPORTED_LANGS = ["es", "en", "ko"];

// Lee el idioma persistido. Default 'es'.
function getCurrentLang() {
  try {
    const stored = localStorage.getItem(TROOPER_LANG_KEY);
    if (stored && SUPPORTED_LANGS.includes(stored)) return stored;
  } catch (e) {}
  return "es";
}

function setCurrentLang(lang) {
  if (!SUPPORTED_LANGS.includes(lang)) return;
  try { localStorage.setItem(TROOPER_LANG_KEY, lang); } catch (e) {}
  window.dispatchEvent(new CustomEvent("trooper:lang-changed", { detail: { lang } }));
}

// Hook React para suscribirse al idioma actual.
function useLang() {
  const [lang, setLang] = React.useState(getCurrentLang());
  React.useEffect(() => {
    const onChange = (e) => setLang(e?.detail?.lang || getCurrentLang());
    window.addEventListener("trooper:lang-changed", onChange);
    return () => window.removeEventListener("trooper:lang-changed", onChange);
  }, []);
  return lang;
}

// Diccionario de strings. Plain object → key.path → string traducido.
// Si falta una traducción → fallback al ES.
const STRINGS = {
  es: {
    // Auth (mobile)
    "auth.tagline": "UNA NOVELA ONLINE",
    "auth.login": "INICIAR SESIÓN",
    "auth.register": "CREAR CUENTA",
    "auth.field.name": "NOMBRE",
    "auth.field.handle": "USUARIO (HANDLE)",
    "auth.field.email": "CORREO",
    "auth.field.password": "CONTRASEÑA",
    "auth.placeholder.name": "Tu nombre",
    "auth.placeholder.handle": "tuusuario",
    "auth.placeholder.email": "tu@correo.com",
    "auth.btn.enter": "▸ ENTRAR",
    "auth.btn.create": "▸ CREAR CUENTA",
    "auth.error.required": "Correo y contraseña requeridos",
    "auth.error.handle": "Usuario (handle) requerido",
    "auth.error.name": "Nombre requerido",
    "auth.error.generic": "Algo salió mal",
    // Header (mobile)
    "header.logout": "CERRAR SESIÓN",
    // Home (mobile)
    "home.greeting": "HOLA,",
    "home.read.title": "LEER",
    "home.read.meta": (read, total) => total > 0
      ? `${read} / ${total} capítulos`
      : "Sin capítulos disponibles",
    "home.cards.title": "TARJETAS",
    "home.cards.meta": (owned, total) => total > 0
      ? `${owned} / ${total} colectadas`
      : "Sin tarjetas disponibles",
    // Library (mobile)
    "library.back": "◄ VOLVER",
    "library.empty.eyebrow": "SIN CAPÍTULOS",
    "library.empty.msg": "Todavía no hay capítulos publicados. Vuelve pronto.",
    "cap.read": "✓ LEÍDO",
    // Banner
    "banner.upcoming": "PRÓXIMAMENTE",
    "banner.new": "NUEVO CAPÍTULO",
    "banner.available": "DISPONIBLE",
    "banner.in.days": (n) => `en ${n} día${n > 1 ? "s" : ""}`,
    "banner.in.hours": (n) => `en ${n}h`,
    "banner.in.minutes": (n) => `en ${n} min`,
    "banner.almost": "ya casi",
    // Reader
    "reader.back": "◄ VOLVER",
    "reader.theme.paper": "PAPEL",
    "reader.theme.dark": "NOCHE",
    "reader.theme.crt": "CRT",
    "reader.cap": "CAP",
    "reader.continue": "CONTINUAR",
    "reader.previous": "◄ ANTERIOR",
    "reader.return": "▸ VOLVER",
    "reader.audio.label": "◀ AUDIOBOOK",
    "reader.listen": "▶ ESCUCHAR NARRACIÓN",
    "reader.listen.pause": "❚❚ PAUSAR NARRACIÓN",
    "reader.bottom.kind": "BE KIND · REWIND",
    "reader.bottom.autosave": "AUTOSAVE ●",
    "reader.fallback": "Este capítulo aún no está traducido al",
    // Card album
    "album.eyebrow": "COLECCIÓN",
    "album.title": "TROOPER · CARDS",
    "album.collected": "COLECTADAS",
    "album.tab.all": "TODAS",
    "album.tab.owned": "OBTENIDAS",
    "album.empty": "No hay tarjetas que mostrar.",
    "album.locked.unknown": "???",
    "album.detail.wallpaper": "↓ WALLPAPER",
    "album.detail.close": "CERRAR",
    "rarity.comun": "COMÚN",
    "rarity.rara": "RARA",
    "rarity.epica": "ÉPICA",
    "rarity.legendaria": "LEGENDARIA",
    "rarity.mitica": "MÍTICA",
    "category.personaje": "PERSONAJE",
    // Card drop overlay
    "drop.new": "¡NUEVA TARJETA DESBLOQUEADA!",
    "drop.duplicate": "DUPLICADO · +1",
    "drop.next": "SIGUIENTE →",
    "drop.album": "◆ MIRAR COLECCIÓN",
    "drop.return": "◄ VOLVER",
    "drop.continue": "CONTINUAR ▸",
    "drop.wallpaper": "↓ DESCARGAR WALLPAPER",
    // Footer
    "footer.label": "TROOPER · NOVELA WEB",
    // Card error toast
    "error.card.title": "◉ NO SE PUDO GUARDAR LA CARTA",
    "error.card.close": "CERRAR",
    // Gallery (desktop)
    "gallery.tab.arcs": "ARCOS",
    "gallery.tab.timeline": "LÍNEA DE TIEMPO",
    "gallery.timeline.title": "LÍNEA DE TIEMPO",
    "gallery.timeline.stats": (arcs, read, total) => `${arcs} ARCOS · ${read} / ${total} CAPÍTULOS LEÍDOS`,
    "gallery.arc": "ARCO",
    "gallery.chapters": "CAPÍTULOS",
    "gallery.chapters.read": (done, total) => `${done} / ${total} LEÍDOS`,
    "gallery.complete": "COMPLETO",
    "gallery.read": "LEÍDO",
    "gallery.read.btn": "▸ LEER",
    "gallery.read.again.btn": "▸ LEER DE NUEVO",
    "gallery.close": "✕ CERRAR",
    "gallery.select.arc": "SELECCIONA UN ARCO",
    "gallery.cap.label": "Capítulo",
    "gallery.tv.title.fallback": "TROOPER",
    // Tabs en startup TV (when in start screen)
    "tv.click.start": "CLICK START PARA LEER",
    "tv.click.vhs": "DA UN CLICK EN UN VHS PARA LEER",
  },

  en: {
    "auth.tagline": "AN ONLINE NOVEL",
    "auth.login": "SIGN IN",
    "auth.register": "CREATE ACCOUNT",
    "auth.field.name": "NAME",
    "auth.field.handle": "USERNAME (HANDLE)",
    "auth.field.email": "EMAIL",
    "auth.field.password": "PASSWORD",
    "auth.placeholder.name": "Your name",
    "auth.placeholder.handle": "yourusername",
    "auth.placeholder.email": "you@email.com",
    "auth.btn.enter": "▸ ENTER",
    "auth.btn.create": "▸ CREATE ACCOUNT",
    "auth.error.required": "Email and password required",
    "auth.error.handle": "Username (handle) required",
    "auth.error.name": "Name required",
    "auth.error.generic": "Something went wrong",
    "header.logout": "LOG OUT",
    "home.greeting": "HI,",
    "home.read.title": "READ",
    "home.read.meta": (read, total) => total > 0
      ? `${read} / ${total} chapters`
      : "No chapters available",
    "home.cards.title": "CARDS",
    "home.cards.meta": (owned, total) => total > 0
      ? `${owned} / ${total} collected`
      : "No cards available",
    "library.back": "◄ BACK",
    "library.empty.eyebrow": "NO CHAPTERS",
    "library.empty.msg": "No chapters published yet. Come back soon.",
    "cap.read": "✓ READ",
    "banner.upcoming": "COMING SOON",
    "banner.new": "NEW CHAPTER",
    "banner.available": "AVAILABLE",
    "banner.in.days": (n) => `in ${n} day${n > 1 ? "s" : ""}`,
    "banner.in.hours": (n) => `in ${n}h`,
    "banner.in.minutes": (n) => `in ${n} min`,
    "banner.almost": "almost there",
    "reader.back": "◄ BACK",
    "reader.theme.paper": "PAPER",
    "reader.theme.dark": "NIGHT",
    "reader.theme.crt": "CRT",
    "reader.cap": "CH",
    "reader.continue": "CONTINUE",
    "reader.previous": "◄ PREVIOUS",
    "reader.return": "▸ BACK",
    "reader.audio.label": "◀ AUDIOBOOK",
    "reader.listen": "▶ LISTEN",
    "reader.listen.pause": "❚❚ PAUSE",
    "reader.bottom.kind": "BE KIND · REWIND",
    "reader.bottom.autosave": "AUTOSAVE ●",
    "reader.fallback": "This chapter is not yet translated to",
    "album.eyebrow": "COLLECTION",
    "album.title": "TROOPER · CARDS",
    "album.collected": "COLLECTED",
    "album.tab.all": "ALL",
    "album.tab.owned": "OWNED",
    "album.empty": "No cards to show.",
    "album.locked.unknown": "???",
    "album.detail.wallpaper": "↓ WALLPAPER",
    "album.detail.close": "CLOSE",
    "rarity.comun": "COMMON",
    "rarity.rara": "RARE",
    "rarity.epica": "EPIC",
    "rarity.legendaria": "LEGENDARY",
    "rarity.mitica": "MYTHIC",
    "category.personaje": "CHARACTER",
    "drop.new": "NEW CARD UNLOCKED!",
    "drop.duplicate": "DUPLICATE · +1",
    "drop.next": "NEXT →",
    "drop.album": "◆ VIEW COLLECTION",
    "drop.return": "◄ BACK",
    "drop.continue": "CONTINUE ▸",
    "drop.wallpaper": "↓ DOWNLOAD WALLPAPER",
    "footer.label": "TROOPER · WEB NOVEL",
    "error.card.title": "◉ COULDN'T SAVE THE CARD",
    "error.card.close": "CLOSE",
    "gallery.tab.arcs": "ARCS",
    "gallery.tab.timeline": "TIMELINE",
    "gallery.timeline.title": "TIMELINE",
    "gallery.timeline.stats": (arcs, read, total) => `${arcs} ARCS · ${read} / ${total} CHAPTERS READ`,
    "gallery.arc": "ARC",
    "gallery.chapters": "CHAPTERS",
    "gallery.chapters.read": (done, total) => `${done} / ${total} READ`,
    "gallery.complete": "COMPLETE",
    "gallery.read": "READ",
    "gallery.read.btn": "▸ READ",
    "gallery.read.again.btn": "▸ READ AGAIN",
    "gallery.close": "✕ CLOSE",
    "gallery.select.arc": "SELECT AN ARC",
    "gallery.cap.label": "Chapter",
    "gallery.tv.title.fallback": "TROOPER",
    "tv.click.start": "CLICK START TO READ",
    "tv.click.vhs": "CLICK A VHS TO READ",
  },

  ko: {
    "auth.tagline": "온라인 소설",
    "auth.login": "로그인",
    "auth.register": "계정 만들기",
    "auth.field.name": "이름",
    "auth.field.handle": "사용자명 (핸들)",
    "auth.field.email": "이메일",
    "auth.field.password": "비밀번호",
    "auth.placeholder.name": "이름",
    "auth.placeholder.handle": "사용자명",
    "auth.placeholder.email": "you@email.com",
    "auth.btn.enter": "▸ 입장",
    "auth.btn.create": "▸ 계정 만들기",
    "auth.error.required": "이메일과 비밀번호가 필요합니다",
    "auth.error.handle": "사용자명이 필요합니다",
    "auth.error.name": "이름이 필요합니다",
    "auth.error.generic": "오류가 발생했습니다",
    "header.logout": "로그아웃",
    "home.greeting": "안녕,",
    "home.read.title": "읽기",
    "home.read.meta": (read, total) => total > 0
      ? `${read} / ${total} 챕터`
      : "사용 가능한 챕터 없음",
    "home.cards.title": "카드",
    "home.cards.meta": (owned, total) => total > 0
      ? `${owned} / ${total} 수집`
      : "사용 가능한 카드 없음",
    "library.back": "◄ 뒤로",
    "library.empty.eyebrow": "챕터 없음",
    "library.empty.msg": "아직 게시된 챕터가 없습니다. 곧 다시 확인하세요.",
    "cap.read": "✓ 읽음",
    "banner.upcoming": "곧 공개",
    "banner.new": "새 챕터",
    "banner.available": "이용 가능",
    "banner.in.days": (n) => `${n}일 후`,
    "banner.in.hours": (n) => `${n}시간 후`,
    "banner.in.minutes": (n) => `${n}분 후`,
    "banner.almost": "거의 다 왔어요",
    "reader.back": "◄ 뒤로",
    "reader.theme.paper": "종이",
    "reader.theme.dark": "어둠",
    "reader.theme.crt": "CRT",
    "reader.cap": "챕",
    "reader.continue": "계속",
    "reader.previous": "◄ 이전",
    "reader.return": "▸ 뒤로",
    "reader.audio.label": "◀ 오디오북",
    "reader.listen": "▶ 듣기",
    "reader.listen.pause": "❚❚ 일시 정지",
    "reader.bottom.kind": "BE KIND · REWIND",
    "reader.bottom.autosave": "AUTOSAVE ●",
    "reader.fallback": "이 챕터는 아직 번역되지 않았습니다:",
    "album.eyebrow": "컬렉션",
    "album.title": "TROOPER · CARDS",
    "album.collected": "수집됨",
    "album.tab.all": "전체",
    "album.tab.owned": "보유",
    "album.empty": "표시할 카드가 없습니다.",
    "album.locked.unknown": "???",
    "album.detail.wallpaper": "↓ 배경화면",
    "album.detail.close": "닫기",
    "rarity.comun": "보통",
    "rarity.rara": "희귀",
    "rarity.epica": "영웅",
    "rarity.legendaria": "전설",
    "rarity.mitica": "신화",
    "category.personaje": "캐릭터",
    "drop.new": "새 카드 획득!",
    "drop.duplicate": "중복 · +1",
    "drop.next": "다음 →",
    "drop.album": "◆ 컬렉션 보기",
    "drop.return": "◄ 뒤로",
    "drop.continue": "계속 ▸",
    "drop.wallpaper": "↓ 배경화면 다운로드",
    "footer.label": "TROOPER · 웹 소설",
    "error.card.title": "◉ 카드를 저장할 수 없습니다",
    "error.card.close": "닫기",
    "gallery.tab.arcs": "아크",
    "gallery.tab.timeline": "타임라인",
    "gallery.timeline.title": "타임라인",
    "gallery.timeline.stats": (arcs, read, total) => `${arcs} 아크 · ${read} / ${total} 챕터 읽음`,
    "gallery.arc": "아크",
    "gallery.chapters": "챕터",
    "gallery.chapters.read": (done, total) => `${done} / ${total} 읽음`,
    "gallery.complete": "완료",
    "gallery.read": "읽음",
    "gallery.read.btn": "▸ 읽기",
    "gallery.read.again.btn": "▸ 다시 읽기",
    "gallery.close": "✕ 닫기",
    "gallery.select.arc": "아크를 선택하세요",
    "gallery.cap.label": "챕터",
    "gallery.tv.title.fallback": "TROOPER",
    "tv.click.start": "시작을 누르세요",
    "tv.click.vhs": "VHS를 클릭하여 읽으세요",
  },
};

// Resuelve key + args. Si no encuentra la key en el lang actual, fallback a 'es'.
function t(key, ...args) {
  const lang = getCurrentLang();
  const dict = STRINGS[lang] || STRINGS.es;
  let val = dict[key];
  if (val == null) val = STRINGS.es[key];
  if (val == null) return key;
  if (typeof val === "function") return val(...args);
  return val;
}

// Resuelve el contenido de un capítulo según el idioma actual. Si la
// traducción no existe o está vacía, fallback al ES (cap original).
function resolveChapter(chapter, lang) {
  if (!chapter) return chapter;
  const l = lang || getCurrentLang();
  if (l === "es") return chapter;
  const tr = chapter.translations?.[l];
  if (!tr) return chapter;
  return {
    ...chapter,
    title: tr.title?.trim() ? tr.title : chapter.title,
    desc: tr.description?.trim() ? tr.description : chapter.desc,
    body: (Array.isArray(tr.body) && tr.body.some(p => p && p.trim())) ? tr.body : chapter.body,
    audioUrl: tr.audioUrl || chapter.audioUrl,
  };
}

// Resuelve un arco según el idioma actual.
function resolveArc(arc, lang) {
  if (!arc) return arc;
  const l = lang || getCurrentLang();
  if (l === "es") return arc;
  const tr = arc.translations?.[l];
  if (!tr) return arc;
  return {
    ...arc,
    title: tr.title?.trim() ? tr.title : arc.title,
    subtitle: tr.subtitle?.trim() ? tr.subtitle : arc.subtitle,
    tagline: tr.tagline?.trim() ? tr.tagline : arc.tagline,
  };
}

// Resuelve una card según el idioma actual.
function resolveCard(card, lang) {
  if (!card) return card;
  const l = lang || getCurrentLang();
  if (l === "es") return card;
  const tr = card.translations?.[l];
  if (!tr) return card;
  return {
    ...card,
    name: tr.name?.trim() ? tr.name : card.name,
    category: tr.category?.trim() ? tr.category : card.category,
    flavor: tr.flavor?.trim() ? tr.flavor : card.flavor,
    description: tr.description?.trim() ? tr.description : card.description,
  };
}

window.t = t;
window.useLang = useLang;
window.getCurrentLang = getCurrentLang;
window.setCurrentLang = setCurrentLang;
window.resolveChapter = resolveChapter;
window.resolveArc = resolveArc;
window.resolveCard = resolveCard;
window.SUPPORTED_LANGS = SUPPORTED_LANGS;
