import { state } from '../core/state.js';
import { navigate } from '../core/router.js';
import { haptics } from '../core/haptics.js';
import { audio } from '../core/audio.js';
import { shake } from '../core/animate.js';

export default {
  render() {
    return `
      <div class="login-page">
        <div class="login-card">
          <h1 class="login-brand">EL3AB</h1>
          <p class="login-subtitle">سجل دخولك وابدأ اللعب</p>

          <form id="login-form">
            <div class="input-group">
              <label class="input-label">البريد الالكتروني</label>
              <input type="email" class="input" id="login-email" placeholder="email@example.com" required dir="ltr" autocomplete="email">
            </div>
            <div class="input-group">
              <label class="input-label">كلمة المرور</label>
              <input type="password" class="input" id="login-pass" 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="login-footer">ما عندك حساب؟ <a href="/register">انشئ حساب</a></p>
          <div id="login-error" class="login-error" style="display:none"></div>
        </div>
      </div>
    `;
  },

  mount(el) {
    const form = el.querySelector('#login-form');
    const btn = el.querySelector('#login-btn');
    const errEl = el.querySelector('#login-error');

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      haptics.tap();
      errEl.style.display = 'none';
      btn.disabled = true;
      btn.textContent = 'جاري الدخول...';

      const email = el.querySelector('#login-email').value;
      const password = el.querySelector('#login-pass').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';
          shake(errEl);
          haptics.error();
          audio.error();
        } else {
          state.setAuth(data.access_token, data.user);
          audio.coin();
          haptics.success();
          navigate('/', {}, true);
          window.location.reload();
        }
      } catch {
        errEl.textContent = 'حدث خطأ في الاتصال';
        errEl.style.display = 'block';
        shake(errEl);
        haptics.error();
      }

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

  destroy() {}
};
