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';

const SUPABASE_URL = 'https://safe-supabase-kong.caprover.al-arcade.com';

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>

      <div style="width:100%;max-width:320px;margin-top:var(--s-4);display:flex;flex-direction:column;gap:var(--s-3);">
        <div style="display:flex;align-items:center;gap:var(--s-3);margin:var(--s-2) 0;">
          <div style="flex:1;height:1px;background:var(--bg-elevated);"></div>
          <span style="color:var(--text-secondary);font-size:12px;">أو</span>
          <div style="flex:1;height:1px;background:var(--bg-elevated);"></div>
        </div>
        <button class="btn w-full" id="google-btn" style="background:#fff;color:#333;font-weight:600;min-height:44px;display:flex;align-items:center;justify-content:center;gap:var(--s-2);">
          <svg width="18" height="18" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
          ${t('auth.google_btn')}
        </button>
        <button class="btn btn-secondary w-full" id="guest-btn" style="min-height:44px;font-weight:600;">
          ${t('auth.guest_btn')}
        </button>
      </div>

      <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>
      <p style="margin-top:var(--s-8);font-size:12px;">
        <a href="/privacy-policy" target="_blank" style="color:var(--text-secondary);text-decoration:none;">${t('settings.privacy_policy')}</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');
  });

  el.querySelector('#google-btn').addEventListener('click', () => {
    audio.play('click');
    const redirect = encodeURIComponent(window.location.origin + '/');
    window.location.href = `${SUPABASE_URL}/auth/v1/authorize?provider=google&redirect_to=${redirect}`;
  });

  el.querySelector('#guest-btn').addEventListener('click', () => {
    audio.play('click');
    store.set('auth.isGuest', true);
    store.set('auth.guestId', crypto.randomUUID());
    store.set('player', { username: 'ضيف', level: 1, coins: 0, gems: 0 });
    bus.emit('auth:guestSuccess');
  });
}
