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

export async function mountFriends(el) {
  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <h2 style="font-size:20px;font-weight:700;">${t('social.friends')}</h2>
      <div id="friends-list">
        <div class="skeleton" style="height:60px;margin-bottom:var(--s-2);"></div>
        <div class="skeleton" style="height:60px;margin-bottom:var(--s-2);"></div>
        <div class="skeleton" style="height:60px;"></div>
      </div>
    </div>
  `;

  try {
    const data = await net.get('friends.php', { action: 'list' });
    renderFriends(el, data.friends || data || []);
  } catch (e) {
    el.querySelector('#friends-list').innerHTML = `<p style="color:var(--text-secondary);text-align:center;">${t('common.empty')}</p>`;
  }
}

function renderFriends(el, friends) {
  const list = el.querySelector('#friends-list');
  if (friends.length === 0) {
    list.innerHTML = `
      <div style="text-align:center;padding:48px 24px;">
        <div style="font-size:56px;margin-bottom:16px;opacity:0.6;">👥</div>
        <div style="font-size:16px;font-weight:700;color:#f8fafc;margin-bottom:6px;">لا يوجد أصدقاء بعد</div>
        <div style="font-size:13px;color:#64748b;margin-bottom:20px;">أضف أصدقاء للعب معهم ومتابعة نتائجهم</div>
        <button class="btn btn-primary" style="font-size:14px;" onclick="navigator.clipboard.writeText(window.location.origin);this.textContent='✓ تم نسخ الرابط';">📤 شارك رابط الدعوة</button>
      </div>`;
    return;
  }

  list.innerHTML = friends.map(f => `
    <div class="card" style="display:flex;align-items:center;gap:var(--s-3);padding:var(--s-3);margin-bottom:var(--s-2);">
      <div style="width:40px;height:40px;border-radius:50%;background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;font-size:16px;">
        ${f.avatar_url ? `<img src="${f.avatar_url}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">` : '👤'}
      </div>
      <div style="flex:1;">
        <div style="font-size:14px;font-weight:600;">${f.display_name || f.username}</div>
        <div style="font-size:11px;color:${f.is_online ? 'var(--success)' : 'var(--text-muted)'};">${f.is_online ? t('social.online') : 'Offline'}</div>
      </div>
      ${f.is_online ? `<button class="btn btn-secondary" style="font-size:11px;padding:var(--s-1) var(--s-3);min-height:32px;" data-challenge="${f.id}">⚔️</button>` : ''}
    </div>
  `).join('');

  list.querySelectorAll('[data-challenge]').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      bus.emit('navigate', { world: 'play', scene: 'play-time-select', params: { mode: 'friend', friendId: btn.dataset.challenge } });
    });
  });
}
