const traducciones = {
  es: {
    title: "Crear Rutina – SwimmingArt",
    logout: "Salir",
    nav: {
      init: "Inicializar Rutina",
      equip: "Equipos Disponibles",
      pool: "Piscina"
    },
    form: {
      title: "Inicializar Nueva Rutina",
      routineTitle: "Título de la rutina",
      duration: "Duración",
      durationPlaceholder: "Selecciona tipo de competencia y modalidad",
      music: "Subir música (mp3)",
      competition: "Nombre de la competencia",
      type: "Tipo de competencia",
      free: "Libre",
      technical: "Técnica",
      mode: "Modalidad",
      solo: "Solo",
      duo: "Dúo",
      team: "Equipo",
      save: "Guardar Rutina"
    }
  },
  en: {
    title: "Create Routine – SwimmingArt",
    logout: "Logout",
    nav: {
      init: "Initialize Routine",
      equip: "Available Teams",
      pool: "Pool"
    },
    form: {
      title: "Initialize New Routine",
      routineTitle: "Title of the routine",
      duration: "Duration",
      durationPlaceholder: "Select type and modality",
      music: "Upload music (mp3)",
      competition: "Name of the competition",
      type: "Type of competition",
      free: "Free",
      technical: "Technical",
      mode: "Mode",
      solo: "Only",
      duo: "Duo",
      team: "Team",
      save: "Save Routine"
    }
  },
  fr: {
    title: "Créer une Routine – SwimmingArt",
    logout: "Se déconnecter",
    nav: {
      init: "Initialiser la Routine",
      equip: "Équipements Disponibles",
      pool: "Piscine"
    },
    form: {
      title: "Initialiser une Nouvelle Routine",
      routineTitle: "Titre de la routine",
      duration: "Durée",
      durationPlaceholder: "Sélectionnez le type et la modalité",
      music: "Télécharger musique (mp3)",
      competition: "Nom de la compétition",
      type: "Type de compétition",
      free: "Libre",
      technical: "Technique",
      mode: "Modalité",
      solo: "Solo",
      duo: "Duo",
      team: "Équipe",
      save: "Enregistrer la Routine"
    }
  }
};

let langActual = "es";

function updateLanguage(lang) {
  langActual = lang;
  const t = traducciones[lang];
  document.querySelector("title").innerText = t.title;

  document.querySelectorAll("[data-i18n]").forEach(el => {
    const keys = el.getAttribute("data-i18n").split(".");
    let value = t;
    for (let k of keys) value = value[k];
    if (el.tagName === "OPTION") {
      el.text = value;
    } else if (el.tagName === "INPUT" && el.placeholder !== undefined) {
      el.placeholder = value;
    } else {
      el.textContent = value;
    }
  });

  const input = document.getElementById("duration");
  if (input && !input.dataset.segundos) {
    input.value = traducciones[langActual].form.durationPlaceholder;
  }
}

document.getElementById("langSelector").addEventListener("change", function () {
  const selectedLang = this.value;
  localStorage.setItem("lang", selectedLang);
  updateLanguage(selectedLang);
});

async function loadUserLanguage() {
  const userId = sessionStorage.getItem("userId");

  if (!userId) {
    alert("Sesión expirada. Inicia sesión de nuevo.");
    window.location.href = "index.html";
    return;
  }

  try {
    const res = await fetch(`/api/users/${userId}`);
    const user = await res.json();

    if (user.language && traducciones[user.language]) {
      langActual = user.language;
      localStorage.setItem("lang", langActual);
    }
  } catch (err) {
    console.error("❌ Error al obtener idioma del usuario:", err);
  }

  updateLanguage(langActual);
}

window.onload = loadUserLanguage;
