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

export async function mountView(el) {
  try {
    const fresh = await net.get('profile.php');
    if (fresh && !fresh.error) store.set('player', fresh);
  } catch (e) {}
  const player = store.get('player') || {};

  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <!-- Player Card -->
      <div class="card" style="text-align:center;padding:var(--s-6);">
        <div class="profile-avatar-wrap" id="avatar-wrap">
          <div class="profile-avatar">
            ${player.avatar_url ? `<img src="${player.avatar_url}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">` : emoji('person', '👤', 40)}
          </div>
          <div class="profile-avatar-edit">${emoji('camera', '📷', 14)}</div>
        </div>
        <input type="file" id="avatar-input" accept="image/*" style="display:none;">
        <div id="avatar-uploading" style="display:none;margin:var(--s-2) auto 0;font-size:12px;color:var(--text-secondary);">جاري الرفع...</div>
        <div style="font-size:18px;font-weight:700;margin-top:var(--s-3);">${player.display_name || player.username || 'Player'}</div>
        <div style="font-size:13px;color:var(--text-secondary);margin-top:2px;">Level ${player.level || 1}</div>
      </div>

      <!-- Stats -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">${t('profile.stats')}</div>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:var(--s-3);text-align:center;">
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--gold);font-family:var(--font-lat);">${player.games_played || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">مباريات</div>
          </div>
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--win);font-family:var(--font-lat);">${player.games_won || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">فوز</div>
          </div>
          <div>
            <div style="font-size:20px;font-weight:700;color:var(--cyan);font-family:var(--font-lat);">${player.current_streak || 0}</div>
            <div style="font-size:11px;color:var(--text-secondary);">سلسلة</div>
          </div>
        </div>
      </div>

      <!-- Ratings -->
      <div class="card">
        <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">التصنيف</div>
        <div style="display:flex;flex-direction:column;gap:var(--s-2);">
          ${renderRating('شطرنج (سريع)', player.elo_rapid)}
          ${renderRating('شطرنج (خاطف)', player.elo_blitz)}
          ${renderRating('شطرنج (رصاصة)', player.elo_bullet)}
        </div>
      </div>

      <!-- Actions -->
      <div style="display:flex;gap:var(--s-3);">
        <button class="btn btn-secondary w-full" id="btn-settings">${t('profile.settings')}</button>
        <button class="btn btn-secondary w-full" id="btn-logout" style="color:var(--error);">خروج</button>
      </div>
    </div>
  `;

  const avatarInput = el.querySelector('#avatar-input');
  const avatarWrap = el.querySelector('#avatar-wrap');
  let isUploading = false;

  avatarWrap.addEventListener('click', () => {
    if (isUploading) return;
    audio.play('click');
    avatarInput.click();
  });

  avatarInput.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    if (!file || isUploading) return;
    if (file.size > 5 * 1024 * 1024) {
      bus.emit('toast', { text: 'الصورة كبيرة جداً (الحد 5MB)', type: 'error' });
      return;
    }
    isUploading = true;
    avatarWrap.style.opacity = '0.5';
    const uploading = el.querySelector('#avatar-uploading');
    uploading.style.display = 'block';
    try {
      const formData = new FormData();
      formData.append('avatar', file);
      const token = store.get('auth.token');
      const res = await fetch('/api/avatar.php', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: formData
      });
      const data = await res.json();
      if (data.avatar_url) {
        store.set('player', { ...store.get('player'), avatar_url: data.avatar_url });
        bus.emit('store:player');
        mountView(el);
        return;
      } else {
        bus.emit('toast', { text: data.error || 'فشل رفع الصورة', type: 'error' });
      }
    } catch (err) {
      bus.emit('toast', { text: 'فشل رفع الصورة', type: 'error' });
    }
    isUploading = false;
    avatarWrap.style.opacity = '1';
    uploading.style.display = 'none';
  });

  el.querySelector('#btn-settings').addEventListener('click', () => {
    audio.play('click');
    scene.push('profile-settings');
  });

  el.querySelector('#btn-logout').addEventListener('click', () => {
    audio.play('click');
    bus.emit('auth:logout');
  });
}

function renderRating(label, rating) {
  return `
    <div style="display:flex;justify-content:space-between;align-items:center;">
      <span style="font-size:13px;color:var(--text-secondary);">${label}</span>
      <span style="font-size:15px;font-weight:700;font-family:var(--font-lat);">${rating || 1200}</span>
    </div>
  `;
}
