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:var(--bg-panel);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:var(--text-primary);">${t('group.create_title')}</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;">${t('group.name_label')}</label>
          <input class="input" id="group-name" type="text" placeholder="${t('group.name_label')}..." maxlength="50" style="width:100%;">
        </div>

        <div>
          <label style="font-size:13px;color:var(--text-secondary);display:block;margin-bottom:6px;">${t('group.select_friends')}</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;">${t('group.create_btn')}</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;">${t('social.no_friends')}</div>`;
    } else {
      picker.innerHTML = friends.map(f => `
        <label data-id="${f.id}" style="display:flex;align-items:center;gap:10px;padding:10px;background:var(--bg-card);border-radius:10px;cursor:pointer;transition:background 0.1s;">
          <input type="checkbox" value="${f.id}" style="width:18px;height:18px;accent-color:var(--chess-primary);">
          <div style="width:36px;height:36px;border-radius:50%;background:var(--bg-hover);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:var(--text-primary);">${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: t('group.name_min'), type: 'error' });
      return;
    }

    const btn = el.querySelector('#create-btn');
    btn.disabled = true;
    btn.textContent = t('group.creating');

    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: t('group.created'), 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 = t('group.create_btn');
    }
  });
}

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