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 * as store from '../../../core/store.js';
import * as modal from '../../../core/modal.js';
import { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

export async function mountGroupMembers(el, params = {}) {
  const { groupId, myRole } = params;
  if (!groupId) { scene.pop(); return; }

  const myId = store.get('auth.userId');
  const canManage = myRole === 'owner' || myRole === 'admin';

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;">
      <div style="padding:12px 16px;background:#0f0f1e;display:flex;align-items:center;gap:12px;">
        <button class="btn btn-secondary" id="back-btn" style="width:36px;height:36px;padding:0;">←</button>
        <h2 style="font-size:18px;font-weight:700;color:#f8fafc;flex:1;">الأعضاء</h2>
        ${canManage ? `<button class="btn btn-primary" id="add-member-btn" style="min-height:34px;padding:6px 12px;font-size:12px;">+ إضافة</button>` : ''}
      </div>
      <div id="members-list" style="flex:1;overflow-y:auto;padding:12px 16px;">
        <div style="text-align:center;padding:24px;color:var(--text-secondary);">${t('common.loading')}</div>
      </div>
      <div style="padding:12px 16px;border-top:1px solid rgba(255,255,255,0.06);">
        <button class="btn btn-secondary w-full" id="leave-btn" style="min-height:40px;color:var(--error);">مغادرة المجموعة</button>
      </div>
    </div>
  `;

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

  // Load members
  try {
    const detail = await net.get('groups.php', { action: 'detail', group_id: groupId });
    const members = detail.members || [];
    const container = el.querySelector('#members-list');

    container.innerHTML = members.map(m => {
      const p = m.profiles || {};
      const roleLabel = m.role === 'owner' ? '👑 مالك' : m.role === 'admin' ? '⭐ مشرف' : '';
      const isMe = m.user_id === myId;
      const showRemove = canManage && !isMe && m.role !== 'owner';

      return `
        <div class="member-row" style="display:flex;align-items:center;gap:12px;padding:12px;background:#1a1a2e;border-radius:10px;margin-bottom:6px;">
          <div style="width:40px;height:40px;border-radius:50%;background:#2a2a4a;display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;cursor:pointer;" data-profile="${m.user_id}">
            ${p.avatar_url ? `<img src="${p.avatar_url}" style="width:40px;height:40px;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 18)}
          </div>
          <div style="flex:1;cursor:pointer;" data-profile="${m.user_id}">
            <div style="font-size:14px;font-weight:500;color:#f8fafc;">${escapeHtml(p.display_name || 'Player')}${isMe ? ' (أنت)' : ''}</div>
            ${roleLabel ? `<div style="font-size:11px;color:#64748b;">${roleLabel}</div>` : ''}
          </div>
          ${p.is_online ? '<div style="width:8px;height:8px;border-radius:50%;background:#34D399;"></div>' : ''}
          ${showRemove ? `<button class="btn btn-secondary remove-btn" data-id="${m.user_id}" style="min-height:28px;padding:4px 10px;font-size:11px;color:var(--error);">إزالة</button>` : ''}
        </div>`;
    }).join('');

    // Profile clicks
    container.querySelectorAll('[data-profile]').forEach(el2 => {
      el2.addEventListener('click', () => {
        const pid = el2.dataset.profile;
        if (pid !== myId) {
          audio.play('click');
          scene.push('profile-view', { playerId: pid });
        }
      });
    });

    // Remove buttons
    container.querySelectorAll('.remove-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        const confirmed = await modal.confirm('إزالة هذا العضو من المجموعة؟', {
          title: 'إزالة عضو',
          icon: '👤',
          confirmText: 'إزالة',
          cancelText: 'إلغاء',
          danger: true
        });
        if (!confirmed) return;
        btn.disabled = true;
        try {
          await net.post('groups.php', { action: 'remove-member', group_id: groupId, user_id: btn.dataset.id });
          btn.closest('.member-row').remove();
          audio.play('click');
        } catch (e) {
          btn.disabled = false;
          bus.emit('toast', { text: e.message || t('common.error'), type: 'error' });
        }
      });
    });
  } catch (e) {
    el.querySelector('#members-list').innerHTML = `<div style="color:var(--error);text-align:center;padding:24px;">${t('common.error')}</div>`;
  }

  // Add member button
  const addBtn = el.querySelector('#add-member-btn');
  if (addBtn) {
    addBtn.addEventListener('click', () => {
      audio.play('click');
      showAddMemberPicker(el, groupId);
    });
  }

  // Leave group
  el.querySelector('#leave-btn').addEventListener('click', async () => {
    const confirmed = await modal.confirm('هل تريد مغادرة المجموعة؟', {
      title: 'مغادرة',
      icon: '🚪',
      confirmText: 'غادر',
      cancelText: 'ابقَ',
      danger: true
    });
    if (!confirmed) return;
    try {
      await net.post('groups.php', { action: 'leave', group_id: groupId });
      audio.play('click');
      scene.pop();
      scene.pop();
    } catch (e) {
      bus.emit('toast', { text: e.message || t('common.error'), type: 'error' });
    }
  });
}

async function showAddMemberPicker(el, groupId) {
  const existing = document.getElementById('add-member-overlay');
  if (existing) existing.remove();

  const overlay = document.createElement('div');
  overlay.id = 'add-member-overlay';
  overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:9999;display:flex;align-items:flex-end;justify-content:center;';
  overlay.innerHTML = `
    <div style="background:#1a1a2e;border-radius:20px 20px 0 0;padding:20px;width:100%;max-width:400px;max-height:60vh;display:flex;flex-direction:column;gap:12px;">
      <div style="font-size:15px;font-weight:700;color:#f8fafc;text-align:center;">إضافة صديق</div>
      <div id="add-friends-list" style="overflow-y:auto;flex:1;display:flex;flex-direction:column;gap:6px;">
        <div style="text-align:center;color:var(--text-secondary);font-size:13px;">جاري التحميل...</div>
      </div>
      <button class="btn btn-secondary w-full" id="close-add">${t('common.close')}</button>
    </div>
  `;

  overlay.querySelector('#close-add').addEventListener('click', () => overlay.remove());
  overlay.addEventListener('click', (e) => { if (e.target === overlay) overlay.remove(); });
  document.body.appendChild(overlay);

  try {
    const data = await net.get('friends.php', { action: 'list' });
    const friends = data.friends || [];
    const list = overlay.querySelector('#add-friends-list');

    if (!friends.length) {
      list.innerHTML = `<div style="text-align:center;color:var(--text-secondary);font-size:13px;">لا يوجد أصدقاء</div>`;
      return;
    }

    list.innerHTML = friends.map(f => `
      <div style="display:flex;align-items:center;gap:10px;padding:10px;background:#2a2a4a;border-radius:10px;">
        <div style="width:32px;height:32px;border-radius:50%;background:#1a1a2e;display:flex;align-items:center;justify-content:center;overflow:hidden;">
          ${f.avatar_url ? `<img src="${f.avatar_url}" style="width:32px;height:32px;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 14)}
        </div>
        <span style="flex:1;font-size:13px;color:#f8fafc;">${escapeHtml(f.display_name || 'Player')}</span>
        <button class="btn btn-primary add-one-btn" data-id="${f.id}" style="min-height:28px;padding:4px 12px;font-size:11px;">إضافة</button>
      </div>
    `).join('');

    list.querySelectorAll('.add-one-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        btn.disabled = true;
        btn.textContent = '...';
        try {
          await net.post('groups.php', { action: 'add-member', group_id: groupId, user_id: btn.dataset.id });
          btn.textContent = '✓';
          btn.style.background = 'transparent';
          btn.style.color = '#34D399';
        } catch (e) {
          btn.textContent = e.message || 'خطأ';
          btn.style.color = 'var(--error)';
        }
      });
    });
  } catch (e) {
    overlay.querySelector('#add-friends-list').innerHTML = `<div style="color:var(--error);font-size:13px;">${t('common.error')}</div>`;
  }
}

function escapeHtml(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}
