const translations = {
  es: {
    title: "Bienvenidos a SwimmingArt",
    subtitle: "La herramienta para tus rutinas de nado sincronizado",
    login_prompt: "Inicia sesión con tu cuenta para continuar",
    email: "Correo electrónico",
    password: "Contraseña",
    forgot_password: "¿Olvidaste tu contraseña?",
    login_button: "Ingresar",
    no_account: "¿No tienes cuenta?",
    register: "Regístrate",
    create_account: "Crear cuenta de SwimmingArt",
    name: "Nombre completo",
    username: "Nombre de usuario",
    register_email: "Correo electrónico",
    register_password: "Contraseña",
    role: "Rol",
    language: "Idioma",
    register_button: "Registrarse",
    has_account: "¿Ya tienes cuenta?",
    login: "Inicia sesión"
  },
  en: {
    title: "Welcome to SwimmingArt",
    subtitle: "The tool for your synchronized swimming routines",
    login_prompt: "Log in with your account to continue",
    email: "Email",
    password: "Password",
    forgot_password: "Forgot your password?",
    login_button: "Log in",
    no_account: "Don't have an account?",
    register: "Sign up",
    create_account: "Create account in SwimmingArt",
    name: "Full name",
    username: "Username",
    register_email: "Email",
    register_password: "Password",
    role: "Role",
    language: "Language",
    register_button: "Sign up",
    has_account: "Already have an account?",
    login: "Log in"
  },
  fr: {
    title: "Bienvenue sur SwimmingArt",
    subtitle: "L’outil pour vos routines de natation synchronisée",
    login_prompt: "Connectez-vous avec votre compte pour continuer",
    email: "Courriel",
    password: "Mot de passe",
    forgot_password: "Mot de passe oublié ?",
    login_button: "Connexion",
    no_account: "Vous n’avez pas de compte ?",
    register: "S’inscrire",
    create_account: "Créer un compte sur SwimmingArt",
    name: "Nom complet",
    username: "Nom d'utilisateur",
    register_email: "Courriel",
    register_password: "Mot de passe",
    role: "Rôle",
    language: "Langue",
    register_button: "S’inscrire",
    has_account: "Vous avez déjà un compte ?",
    login: "Connexion"
  }
};
 
function getLoginHTML(lang) {
  const t = translations[lang];
  return `
    <div class="text-center mb-4">
      <h1 class="fw-bold mb-3 text-primary-strong display-3">${t.title}</h1>
      <h3 class="fw mb-5 text-secondary-strong">${t.subtitle}</h3>
    </div>
    <form id="loginForm" class="w-100" style="max-width: 480px;">
      <p class="subtext-muted mb-3 text-center">${t.login_prompt}</p>
      <div class="mb-3">
        <input type="email" class="form-control" placeholder="${t.email}" required>
      </div>
      <div class="mb-3">
        <input type="password" class="form-control" placeholder="${t.password}" required>
      </div>
      <div class="d-flex justify-content-end mb-3">
        <a href="#" class="small text-primary">${t.forgot_password}</a>
      </div>
      <button type="submit" class="btn btn-primary w-100">${t.login_button}</button>
    </form>
    <p class="mt-4">${t.no_account} <a href="#" class="text-primary" onclick="showRegister()">${t.register}</a></p>
    <div class="mt-3 d-flex align-items-center fs-6">
      <i class="bi bi-globe me-2"></i>
      <select class="form-select form-select-sm border-0 shadow-none" id="languageSelect" style="width: auto; font-size: 1rem;" onchange="changeLanguage(this.value)">
        <option value="es">Español</option>
        <option value="en">English</option>
        <option value="fr">Français</option>
      </select>
    </div>
  `;
}

function getRegisterHTML(lang) {
  const t = translations[lang];
  return `
    <div class="text-center mb-4">
      <h2 class="fw-bold mb-3 text-primary-strong display-2">${t.create_account}</h2>
    </div>
    <form id="registerForm" class="w-100" style="max-width: 500px;">
      <div class="mb-3">
        <label class="form-label">${t.name}</label>
        <input type="text" name="name" class="form-control green-input" placeholder="${t.name}" required>
      </div>
      <div class="mb-3">
        <label class="form-label">${t.username}</label>
        <input type="text" name="username" class="form-control green-input" placeholder="${t.username}" required>
      </div>
      <div class="mb-3">
        <label class="form-label">${t.register_email}</label>
        <input type="email" name="email" class="form-control green-input" placeholder="${t.register_email}" required>
      </div>
      <div class="mb-3">
        <label class="form-label">${t.register_password}</label>
        <input type="password" name="password" class="form-control green-input" placeholder="${t.register_password}" required>
      </div>
      <div class="mb-3">
        <label class="form-label">${t.role}</label>
        <select name="role" class="form-select" required>
          <option value="coach">Coach</option>
          <option value="athlete">Atleta</option>
        </select>
      </div>
      <div class="mb-4">
        <label class="form-label">${t.language}</label>
        <select name="language" class="form-select" required>
          <option value="es">Español</option>
          <option value="en">Inglés</option>
          <option value="fr">Francés</option>
        </select>
      </div>
      <button type="submit" class="btn btn-primary w-100">${t.register_button}</button>
    </form>
    <p class="mt-4 text-center">${t.has_account} <a href="#" onclick="showLogin()">${t.login}</a></p>
    <div class="mt-3 d-flex align-items-center fs-6">
      <i class="bi bi-globe me-2"></i>
      <select class="form-select form-select-sm border-0 shadow-none" id="languageSelect" style="width: auto; font-size: 1rem;" onchange="changeLanguage(this.value)">
        <option value="es">Español</option>
        <option value="en">English</option>
        <option value="fr">Français</option>
      </select>
    </div>
  `;
}

let currentLang = 'es';

function showLogin() {
  document.getElementById('rightPanel').innerHTML = getLoginHTML(currentLang);
  document.getElementById('languageSelect').value = currentLang;
  setupLoginForm();
}

function showRegister() {
  document.getElementById('rightPanel').innerHTML = getRegisterHTML(currentLang);
  document.getElementById('languageSelect').value = currentLang;
  setupRegisterForm();
}

function changeLanguage(lang) {
  currentLang = lang;
  const isLogin = document.getElementById('loginForm') !== null;
  if (isLogin) {
    showLogin();
  } else {
    showRegister(); 
  }
}

function setupLoginForm() {
  const form = document.getElementById('loginForm');
  if (!form) return;

  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    const email = form.querySelector('input[type="email"]').value;
    const password = form.querySelector('input[type="password"]').value;

    try {
      const res = await fetch('/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
      });

      if (!res.ok) {
        alert("Credenciales incorrectas.");
        return;
      }

      const data = await res.json();
      sessionStorage.setItem("userId", data.userId);
      sessionStorage.setItem("role", data.role);

      if (data.role === "coach") {
        window.location.href = "equipoDisponibles.html";
      } else if (data.role === "athlete") {
        window.location.href = "atleta.html";
      } else {
        window.location.href = "ventanaPrincipal.html";
      }
    } catch (error) {
      console.error("Error al iniciar sesión:", error);
      alert("Error de red al intentar iniciar sesión.");
    }
  });
}

function setupRegisterForm() {
  const form = document.getElementById('registerForm');
  if (!form) return;

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(form));
    try {
      const response = await fetch('/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });

      if (response.ok) {
        //alert('Registro exitoso. Ahora inicia sesión.');
        showLogin(); 
      } else {
        const errorText = await response.text();
        alert(`Error: ${errorText}`);
      }
    } catch (err) {
      console.error('Error de red:', err);
      alert('Ocurrió un error. Intenta más tarde.');
    }
  });
}

window.onload = () => {
  showLogin(); 
};


 