<?php $pageTitle = 'EL3AB - تسجيل الدخول'; ?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
  <meta name="theme-color" content="#030A12">
  <title><?= $pageTitle ?></title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="/public/css/app-v2.css">
</head>
<body>
<div class="auth-page">
  <div class="auth-card">
    <h1 class="auth-brand">EL3AB</h1>
    <p class="auth-subtitle">سجل دخولك وابدأ اللعب</p>

    <form id="login-form" class="stack-4">
      <div class="field">
        <label class="field-label" for="login-email">البريد الالكتروني</label>
        <input type="email" class="input" id="login-email" placeholder="email@example.com" required dir="ltr" autocomplete="email">
      </div>
      <div class="field">
        <label class="field-label" for="login-password">كلمة المرور</label>
        <input type="password" class="input" id="login-password" placeholder="••••••••" required dir="ltr" autocomplete="current-password">
      </div>
      <button type="submit" class="btn btn-primary btn-block btn-lg" id="login-btn">
        تسجيل الدخول
      </button>
    </form>

    <p class="auth-footer">
      ما عندك حساب؟ <a href="/register">انشئ حساب</a>
    </p>

    <div id="login-error" class="auth-error" style="display:none;"></div>
  </div>
</div>

<script src="/public/js/app.js"></script>
<script>
document.getElementById('login-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const btn = document.getElementById('login-btn');
  const errEl = document.getElementById('login-error');
  errEl.style.display = 'none';
  btn.disabled = true;
  btn.textContent = 'جاري الدخول...';

  const email = document.getElementById('login-email').value;
  const password = document.getElementById('login-password').value;

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

    if (data.error) {
      errEl.textContent = data.error;
      errEl.style.display = 'block';
    } else {
      App.setAuth(data.access_token, data.user);
      window.location.href = '/';
    }
  } catch (err) {
    errEl.textContent = 'حدث خطا في الاتصال';
    errEl.style.display = 'block';
  }

  btn.disabled = false;
  btn.textContent = 'تسجيل الدخول';
});

if (typeof App !== 'undefined' && App.isLoggedIn()) window.location.href = '/';
</script>
</body>
</html>
