import * as bus from '../../../core/bus.js';
import * as store from '../../../core/store.js';
import * as scene from '../../../core/scene.js';
import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import { t } from '../../../core/i18n.js';
import { assetImg } from '../../../core/theme.js';

export function mountLogin(el) {
  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:var(--s-6);">
      <div style="margin-bottom:var(--s-4);">${assetImg('logo', '<span style="font-size:42px;font-weight:900;color:var(--gold);font-family:var(--font-lat);">EL3AB</span>', 120, 60)}</div>
      <p style="color:var(--text-secondary);margin-bottom:var(--s-8);font-size:14px;">${t('auth.login')}</p>
      <form id="login-form" style="width:100%;max-width:320px;display:flex;flex-direction:column;gap:var(--s-3);">
        <input class="input" type="email" id="login-email" placeholder="${t('auth.email')}" autocomplete="email" required>
        <input class="input" type="password" id="login-pass" placeholder="${t('auth.password')}" autocomplete="current-password" required>
        <div id="login-error" style="color:var(--error);font-size:13px;min-height:20px;"></div>
        <button type="submit" class="btn btn-primary w-full" id="login-btn">${t('auth.login.btn')}</button>
      </form>
      <p style="margin-top:var(--s-6);color:var(--text-secondary);font-size:14px;">
        ${t('auth.no_account')} <a href="#" id="goto-register" style="color:var(--gold);text-decoration:none;font-weight:700;">${t('auth.register')}</a>
      </p>
    </div>
  `;

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

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const email = el.querySelector('#login-email').value.trim();
    const pass = el.querySelector('#login-pass').value;
    if (!email || !pass) return;

    btn.disabled = true;
    btn.textContent = t('auth.logging_in');
    errEl.textContent = '';

    try {
      const data = await net.post('auth.php', { action: 'login', email, password: pass });
      if (data.error) throw new Error(data.error);

      store.set('auth.token', data.access_token);
      store.set('auth.refreshToken', data.refresh_token);
      store.set('auth.userId', data.user.id);

      const profile = await net.get('profile.php');
      if (profile && !profile.error) store.set('player', profile);

      audio.play('coin', 'reward');
      bus.emit('auth:success');
    } catch (err) {
      errEl.textContent = err.message || t('common.error');
      btn.disabled = false;
      btn.textContent = t('auth.login.btn');
    }
  });

  el.querySelector('#goto-register').addEventListener('click', (e) => {
    e.preventDefault();
    audio.play('click');
    scene.replace('auth-register');
  });
}
