<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Login - Langfuse Lens</title>
  <link rel="stylesheet" href="/static/style.css" />
  <script>(function(){var t=localStorage.getItem('lens_theme');if(!t)t=window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark';document.documentElement.setAttribute('data-theme',t)})()</script>
  <style>
    .login-page {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--bg-0);
      padding: 1rem;
    }
    .login-card {
      width: 100%;
      max-width: 400px;
      background: var(--bg-2);
      border: 1px solid var(--border-1);
      border-radius: var(--radius-lg);
      padding: 2.5rem 2rem 2rem;
      box-shadow: var(--shadow-elevated);
    }
    .login-header {
      text-align: center;
      margin-bottom: 2rem;
    }
    .login-header svg {
      width: 40px;
      height: 40px;
      color: var(--accent);
      margin-bottom: 0.75rem;
    }
    .login-header h1 {
      font-size: 1.25rem;
      font-weight: 600;
      color: var(--text-1);
      margin: 0;
    }
    .form-group {
      margin-bottom: 1.25rem;
    }
    .form-group label {
      display: block;
      font-size: 0.8125rem;
      font-weight: 500;
      color: var(--text-2);
      margin-bottom: 0.375rem;
    }
    .form-input {
      width: 100%;
      padding: 0.625rem 0.75rem;
      font-size: 0.875rem;
      font-family: var(--font);
      color: var(--text-1);
      background: var(--bg-3);
      border: 1px solid var(--border-1);
      border-radius: var(--radius-sm);
      outline: none;
      transition: border-color var(--transition);
      box-sizing: border-box;
    }
    .form-input:focus {
      border-color: var(--border-focus);
      box-shadow: 0 0 0 3px var(--accent-glow);
    }
    .btn-primary {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      width: 100%;
      padding: 0.625rem 1rem;
      font-size: 0.875rem;
      font-weight: 500;
      font-family: var(--font);
      color: #fff;
      background: var(--accent);
      border: none;
      border-radius: var(--radius-sm);
      cursor: pointer;
      transition: background var(--transition);
    }
    .btn-primary:hover {
      background: var(--accent-hover);
    }
    .btn-primary:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
    .btn-spinner {
      width: 14px;
      height: 14px;
      border: 2px solid rgba(255,255,255,0.3);
      border-top-color: #fff;
      border-radius: 50%;
      animation: spin 0.6s linear infinite;
      display: none;
    }
    .btn-primary:disabled .btn-spinner { display: inline-block; }
    @keyframes spin { to { transform: rotate(360deg); } }
    .switch-link {
      text-align: center;
      margin-top: 1.25rem;
      font-size: 0.8125rem;
    }
    .switch-link a {
      color: var(--accent);
      text-decoration: none;
      cursor: pointer;
    }
    .switch-link a:hover {
      text-decoration: underline;
    }
    .login-footer {
      display: flex;
      justify-content: center;
      gap: 0.5rem;
      margin-top: 1.5rem;
    }
    .login-toggle {
      padding: 0.25rem 0.625rem;
      font-size: 0.75rem;
      font-family: var(--font);
      color: var(--text-3);
      background: var(--bg-3);
      border: 1px solid var(--border-1);
      border-radius: var(--radius-sm);
      cursor: pointer;
      transition: color var(--transition), border-color var(--transition);
    }
    .login-toggle:hover {
      color: var(--text-2);
      border-color: var(--border-2);
    }
    .error-msg {
      color: var(--red);
      font-size: 0.8125rem;
      text-align: center;
      margin-bottom: 1rem;
      display: none;
    }
    .toast-container {
      position: fixed;
      top: 1rem;
      right: 1rem;
      z-index: 9999;
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
    }
    .toast {
      padding: 0.75rem 1rem;
      border-radius: var(--radius-sm);
      font-size: 0.8125rem;
      color: var(--text-1);
      background: var(--bg-3);
      border: 1px solid var(--border-1);
      box-shadow: var(--shadow-card);
    }
    .toast-error { border-left: 3px solid var(--red); }
    .toast-success { border-left: 3px solid var(--green); }
  </style>
</head>
<body class="login-page">
  <div class="login-card">
    <div class="login-header">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a10 10 0 0 1 0 20"/><path d="M2 12h20"/></svg>
      <h1>Langfuse Lens</h1>
    </div>

    <div class="error-msg" id="error-msg"></div>

    <!-- Login form -->
    <form id="login-form">
      <div class="form-group">
        <label for="login-username" data-i18n="auth.username">Username</label>
        <input type="text" id="login-username" class="form-input" autocomplete="username" required />
      </div>
      <div class="form-group">
        <label for="login-password" data-i18n="auth.password">Password</label>
        <input type="password" id="login-password" class="form-input" autocomplete="current-password" required />
      </div>
      <button type="submit" class="btn-primary" id="login-btn">
        <span class="btn-spinner"></span>
        <span data-i18n="auth.loginBtn">Login</span>
      </button>
    </form>

    <!-- Register form (hidden by default, hidden entirely when signup disabled) -->
    <form id="register-form" style="display:none">
      <div class="form-group">
        <label for="register-username" data-i18n="auth.username">Username</label>
        <input type="text" id="register-username" class="form-input" autocomplete="username" required minlength="3" />
      </div>
      <div class="form-group">
        <label for="register-password" data-i18n="auth.password">Password</label>
        <input type="password" id="register-password" class="form-input" autocomplete="new-password" required minlength="8" />
      </div>
      <button type="submit" class="btn-primary" id="register-btn">
        <span class="btn-spinner"></span>
        <span data-i18n="auth.registerBtn">Register</span>
      </button>
    </form>

    <p class="switch-link" id="switch-link">
      <a href="#" id="switch-to-register" data-i18n="auth.switchToRegister">Don't have an account? Register</a>
      <a href="#" id="switch-to-login" data-i18n="auth.switchToLogin" style="display:none">Already have an account? Login</a>
    </p>

    <div class="login-footer">
      <button class="login-toggle" id="lang-toggle">EN</button>
      <button class="login-toggle" id="theme-toggle-btn">
        <span id="theme-icon-label">Light</span>
      </button>
    </div>
  </div>

  <div class="toast-container" id="toast-container"></div>

  <script type="module">
    import { t, setLocale, getLocale, applyTranslations } from '/static/js/i18n.js';

    // Already logged in? Redirect to home
    if (localStorage.getItem('lens_token')) {
      const returnUrl = new URLSearchParams(window.location.search).get('next') || '/';
      window.location.href = returnUrl;
    }

    // --- Toast ---
    function toast(message, type = 'info', duration = 3500) {
      const container = document.getElementById('toast-container');
      if (!container) return;
      const el = document.createElement('div');
      el.className = `toast toast-${type}`;
      el.textContent = message;
      container.appendChild(el);
      setTimeout(() => {
        el.style.opacity = '0';
        el.style.transform = 'translateX(40px)';
        el.style.transition = 'all 0.3s ease';
        setTimeout(() => el.remove(), 300);
      }, duration);
    }

    // --- Check signup availability & hide register if disabled ---
    const switchLink = document.getElementById('switch-link');
    try {
      const res = await fetch('/health');
      const health = await res.json();
      // Probe: try to see if register will be rejected (no users = always allow)
      // We'll just show the form and let backend reject if needed.
      // But if user count > 0 and signup disabled, the 403 error will be clear.
    } catch(e) {}

    // --- Elements ---
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const switchToRegister = document.getElementById('switch-to-register');
    const switchToLogin = document.getElementById('switch-to-login');
    const errorMsg = document.getElementById('error-msg');

    // --- Clear error on input ---
    function clearError() { errorMsg.style.display = 'none'; }
    document.querySelectorAll('.form-input').forEach(input => {
      input.addEventListener('input', clearError);
    });

    // --- Form toggle ---
    switchToRegister.addEventListener('click', (e) => {
      e.preventDefault();
      loginForm.style.display = 'none';
      registerForm.style.display = '';
      switchToRegister.style.display = 'none';
      switchToLogin.style.display = '';
      clearError();
    });

    switchToLogin.addEventListener('click', (e) => {
      e.preventDefault();
      registerForm.style.display = 'none';
      loginForm.style.display = '';
      switchToLogin.style.display = 'none';
      switchToRegister.style.display = '';
      clearError();
    });

    // --- Return URL ---
    const nextUrl = new URLSearchParams(window.location.search).get('next') || '/';

    // --- Login ---
    loginForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      clearError();
      const username = document.getElementById('login-username').value.trim();
      const password = document.getElementById('login-password').value;
      const btn = document.getElementById('login-btn');
      btn.disabled = true;
      try {
        const res = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username, password }),
        });
        const data = await res.json();
        if (res.ok && data.ok) {
          localStorage.setItem('lens_token', data.data.access_token);
          toast(t('auth.loginSuccess'), 'success');
          setTimeout(() => { window.location.href = nextUrl; }, 300);
        } else {
          const msg = data.detail || t('auth.loginError');
          errorMsg.textContent = msg;
          errorMsg.style.display = '';
        }
      } catch (err) {
        errorMsg.textContent = t('auth.loginError');
        errorMsg.style.display = '';
      } finally {
        btn.disabled = false;
      }
    });

    // --- Register ---
    registerForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      clearError();
      const username = document.getElementById('register-username').value.trim();
      const password = document.getElementById('register-password').value;
      const btn = document.getElementById('register-btn');
      btn.disabled = true;
      try {
        const res = await fetch('/api/auth/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username, password }),
        });
        const data = await res.json();
        if (res.ok && data.ok) {
          toast(t('auth.registerSuccess'), 'success');
          switchToLogin.click();
          document.getElementById('login-username').value = username;
        } else {
          const msg = data.detail || t('auth.registerError');
          errorMsg.textContent = msg;
          errorMsg.style.display = '';
        }
      } catch (err) {
        errorMsg.textContent = t('auth.registerError');
        errorMsg.style.display = '';
      } finally {
        btn.disabled = false;
      }
    });

    // --- Language toggle ---
    const langBtn = document.getElementById('lang-toggle');
    langBtn.textContent = getLocale() === 'ko' ? 'EN' : 'KO';
    langBtn.addEventListener('click', async () => {
      const next = getLocale() === 'ko' ? 'en' : 'ko';
      await setLocale(next);
      langBtn.textContent = next === 'ko' ? 'EN' : 'KO';
    });

    // --- Theme toggle ---
    const themeBtn = document.getElementById('theme-toggle-btn');
    const themeLabel = document.getElementById('theme-icon-label');
    function updateThemeLabel() {
      const current = document.documentElement.getAttribute('data-theme') || 'dark';
      themeLabel.textContent = current === 'dark' ? 'Light' : 'Dark';
    }
    updateThemeLabel();
    themeBtn.addEventListener('click', () => {
      const current = document.documentElement.getAttribute('data-theme') || 'dark';
      const next = current === 'dark' ? 'light' : 'dark';
      document.documentElement.setAttribute('data-theme', next);
      localStorage.setItem('lens_theme', next);
      updateThemeLabel();
    });

    applyTranslations();
  </script>
</body>
</html>
