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';
import { emoji } from '../../../core/theme.js';

export async function mountGroupCreate(el) {
  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;">إنشاء مجموعة</h2>
      </div>
      <div style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:16px;">
        <div>
          <label style="font-size:13px;color:var(--text-secondary);display:block;margin-bottom:6px;">اسم المجموعة</label>
          <input class="input" id="group-name" type="text" placeholder="اسم المجموعة..." maxlength="50" style="width:100%;">
        </div>

        <div>
          <label style="font-size:13px;color:var(--text-secondary);display:block;margin-bottom:6px;">اختر أصدقاء للإضافة</label>
          <div id="friends-picker" style="display:flex;flex-direction:column;gap:6px;">
            <div style="text-align:center;padding:12px;color:var(--text-secondary);font-size:13px;">${t('common.loading')}</div>
          </div>
        </div>

        <button class="btn btn-primary w-full" id="create-btn" style="min-height:48px;font-size:15px;font-weight:700;">إنشاء المجموعة</button>
      </div>
    </div>
  `;

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

  const selectedIds = new Set();

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

    if (!friends.length) {
      picker.innerHTML = `<div style="text-align:center;padding:12px;color:var(--text-secondary);font-size:13px;">لا يوجد أصدقاء</div>`;
    } else {
      picker.innerHTML = friends.map(f => `
        <label data-id="${f.id}" style="display:flex;align-items:center;gap:10px;padding:10px;background:#1a1a2e;border-radius:10px;cursor:pointer;transition:background 0.1s;">
          <input type="checkbox" value="${f.id}" style="width:18px;height:18px;accent-color:#2563EB;">
          <div style="width:36px;height:36px;border-radius:50%;background:#2a2a4a;display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;">
            ${f.avatar_url ? `<img src="${f.avatar_url}" style="width:36px;height:36px;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 16)}
          </div>
          <span style="font-size:13px;font-weight:500;color:#f8fafc;">${escapeHtml(f.display_name || f.username || 'Player')}</span>
        </label>
      `).join('');

      picker.querySelectorAll('input[type="checkbox"]').forEach(cb => {
        cb.addEventListener('change', () => {
          if (cb.checked) selectedIds.add(cb.value);
          else selectedIds.delete(cb.value);
        });
      });
    }
  } catch (e) {
    el.querySelector('#friends-picker').innerHTML = `<div style="color:var(--error);font-size:13px;">${t('common.error')}</div>`;
  }

  el.querySelector('#create-btn').addEventListener('click', async () => {
    const name = el.querySelector('#group-name').value.trim();
    if (!name || name.length < 2) {
      bus.emit('toast', { text: 'أدخل اسم المجموعة (حرفين على الأقل)', type: 'error' });
      return;
    }

    const btn = el.querySelector('#create-btn');
    btn.disabled = true;
    btn.textContent = 'جاري الإنشاء...';

    try {
      const res = await net.post('groups.php', {
        action: 'create',
        name,
        member_ids: [...selectedIds]
      });
      if (res.error) throw new Error(res.error);
      audio.play('click');
      bus.emit('toast', { text: 'تم إنشاء المجموعة!', type: 'success' });
      scene.pop();
      scene.push('group-chat', { groupId: res.group?.id });
    } catch (e) {
      bus.emit('toast', { text: e.message || t('common.error'), type: 'error' });
      btn.disabled = false;
      btn.textContent = 'إنشاء المجموعة';
    }
  });
}

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