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: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);flex:1;">${t('group.members')}</h2>
        ${canManage ? `<button class="btn btn-primary" id="add-member-btn" style="min-height:var(--tap-min);padding:6px 12px;font-size:12px;">+ ${t('group.add')}</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:var(--tap-min);color:var(--error);">${t('group.leave')}</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' ? `${emoji('crown', '👑', 12)} ${t('group.owner')}` : m.role === 'admin' ? `${emoji('star', '⭐', 12)} ${t('group.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:var(--bg-card);border-radius:10px;margin-bottom:6px;">
          <div style="width:40px;height:40px;border-radius:50%;background:var(--bg-hover);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:var(--text-primary);">${escapeHtml(p.display_name || 'Player')}${isMe ? ` ${t('common.you')}` : ''}</div>
            ${roleLabel ? `<div style="font-size:11px;color:var(--text-muted);">${roleLabel}</div>` : ''}
          </div>
          ${p.is_online ? '<div style="width:8px;height:8px;border-radius:50%;background:var(--success);"></div>' : ''}
          ${showRemove ? `<button class="btn btn-secondary remove-btn" data-id="${m.user_id}" style="min-height:var(--tap-min);padding:4px 10px;font-size:11px;color:var(--error);">${t('group.remove')}</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(t('group.remove_member'), {
          title: t('group.remove'),
          icon: '👤',
          confirmText: t('group.remove'),
          cancelText: t('common.cancel'),
          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(t('group.leave_confirm'), {
      title: t('group.leave'),
      icon: '🚪',
      confirmText: t('group.leave_btn'),
      cancelText: t('group.stay'),
      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:var(--bg-card);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:var(--text-primary);text-align:center;">${t('mp.add_friend')}</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;">${t('common.loading')}</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;">${t('social.no_friends')}</div>`;
      return;
    }

    list.innerHTML = friends.map(f => `
      <div style="display:flex;align-items:center;gap:10px;padding:10px;background:var(--bg-hover);border-radius:10px;">
        <div style="width:32px;height:32px;border-radius:50%;background:var(--bg-card);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:var(--text-primary);">${escapeHtml(f.display_name || 'Player')}</span>
        <button class="btn btn-primary add-one-btn" data-id="${f.id}" style="min-height:var(--tap-min);padding:4px 12px;font-size:11px;">${t('group.add')}</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 = t('common.done');
          btn.style.background = 'transparent';
          btn.style.color = 'var(--success)';
        } catch (e) {
          btn.textContent = e.message || t('social.error');
          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;
}
