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 { SUPABASE_URL } from '../../../core/config.js';

export function mountRegister(el) {
  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:var(--s-6);">
      <div style="font-size:36px;font-weight:800;color:var(--gold);margin-bottom:var(--s-2);">EL3AB</div>
      <p style="color:var(--text-secondary);margin-bottom:var(--s-8);font-size:14px;">${t('auth.register')}</p>
      <form id="register-form" style="width:100%;max-width:320px;display:flex;flex-direction:column;gap:var(--s-3);">
        <input class="input" type="text" id="reg-username" placeholder="${t('auth.username')}" autocomplete="username" required minlength="3" maxlength="20">
        <input class="input" type="email" id="reg-email" placeholder="${t('auth.email')}" autocomplete="email" required>
        <input class="input" type="password" id="reg-pass" placeholder="${t('auth.password')}" autocomplete="new-password" required minlength="6">
        <label style="display:flex;align-items:flex-start;gap:var(--s-2);font-size:13px;color:var(--text-secondary);cursor:pointer;">
          <input type="checkbox" id="reg-age" required style="margin-top:2px;accent-color:var(--gold);">
          <span>${t('auth.age_confirm')}</span>
        </label>
        <p style="font-size:12px;color:var(--text-secondary);text-align:center;">
          ${t('auth.agree_terms')} <a href="/terms" target="_blank" style="color:var(--gold);text-decoration:none;">${t('settings.terms')}</a> · <a href="/privacy-policy" target="_blank" style="color:var(--gold);text-decoration:none;">${t('settings.privacy_policy')}</a>
        </p>
        <div id="reg-error" style="color:var(--error);font-size:13px;min-height:20px;"></div>
        <button type="submit" class="btn btn-primary w-full" id="reg-btn">${t('auth.register.btn')}</button>
      </form>
      <div style="width:100%;max-width:320px;margin-top:var(--s-4);">
        <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;">${t('common.or')}</span>
          <div style="flex:1;height:1px;background:var(--bg-elevated);"></div>
        </div>
        <button class="btn w-full" id="google-reg-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_register')}
        </button>
      </div>

      <p style="margin-top:var(--s-6);color:var(--text-secondary);font-size:13px;">
        ${t('auth.have_account')} <a href="#" id="goto-login" style="color:var(--gold);text-decoration:none;font-weight:600;">${t('auth.login')}</a>
      </p>
    </div>
  `;

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

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = el.querySelector('#reg-username').value.trim();
    const email = el.querySelector('#reg-email').value.trim();
    const pass = el.querySelector('#reg-pass').value;
    if (!username || !email || !pass) return;
    if (!/^[a-zA-Z0-9؀-ۿ_.-]{3,20}$/.test(username)) {
      errEl.textContent = t('auth.invalid_username');
      return;
    }

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

    try {
      const data = await net.post('auth.php', { action: 'signup', email, password: pass, username });
      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('levelUp', 'reward');
      bus.emit('auth:success');
    } catch (err) {
      errEl.textContent = err.message || t('common.error');
      btn.disabled = false;
      btn.textContent = t('auth.register.btn');
    }
  });

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

  el.querySelector('#google-reg-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}`;
  });
}
