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

let realtimeSub = null;
let inviteTimer = null;

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

  const myId = store.get('auth.userId');

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;">
      <div style="padding:10px 16px;background:#0f0f1e;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,0.06);">
        <button class="btn btn-secondary" id="back-btn" style="width:34px;height:34px;padding:0;font-size:14px;">←</button>
        <div id="group-header" style="flex:1;cursor:pointer;">
          <div style="font-size:15px;font-weight:600;color:#f8fafc;">جاري التحميل...</div>
        </div>
        <button class="btn btn-secondary" id="invite-game-btn" style="min-height:32px;padding:5px 10px;font-size:12px;">${emoji('swords', '⚔️', 13)} لعب</button>
      </div>
      <div id="invite-banner" style="display:none;"></div>
      <div id="chat-messages" style="flex:1;overflow-y:auto;padding:12px 16px;display:flex;flex-direction:column;gap:6px;"></div>
      <div style="padding:10px 16px;background:#0f0f1e;border-top:1px solid rgba(255,255,255,0.06);display:flex;gap:8px;align-items:center;">
        <input class="input" id="msg-input" type="text" placeholder="اكتب رسالة..." style="flex:1;min-height:38px;" maxlength="500">
        <button class="btn btn-primary" id="send-btn" style="min-height:38px;padding:0 14px;">إرسال</button>
      </div>
    </div>
  `;

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

  // Load group detail
  let groupData = null;
  let members = [];
  let mutedIds = [];
  const memberMap = {};

  try {
    const detail = await net.get('groups.php', { action: 'detail', group_id: groupId });
    groupData = detail.group;
    members = detail.members || [];
    members.forEach(m => { memberMap[m.user_id] = m.profiles || {}; });

    const header = el.querySelector('#group-header');
    header.innerHTML = `
      <div style="font-size:15px;font-weight:600;color:#f8fafc;">${escapeHtml(groupData.name)}</div>
      <div style="font-size:11px;color:#64748b;">${members.length} أعضاء</div>
    `;
    header.addEventListener('click', () => {
      audio.play('click');
      scene.push('group-members', { groupId, myRole: detail.my_role });
    });
  } catch (e) {
    el.querySelector('#group-header').innerHTML = `<div style="color:var(--error);">خطأ في تحميل المجموعة</div>`;
    return;
  }

  // Load chat history
  try {
    const chatData = await net.get('groups.php', { action: 'chat-history', group_id: groupId });
    mutedIds = chatData.muted_ids || [];
    renderMessages(el.querySelector('#chat-messages'), chatData.messages || [], myId, memberMap, mutedIds);
    scrollToBottom(el);
  } catch (e) {}

  // Subscribe to realtime for new messages
  realtimeSub = realtime.subscribe('chat_messages', `channel_id=eq.${groupId}`, (payload) => {
    if (payload.type === 'INSERT') {
      const msg = payload.new;
      if (!msg || mutedIds.includes(msg.sender_id)) return;
      if (msg.sender_id === myId) return;
      appendMessage(el.querySelector('#chat-messages'), msg, myId, memberMap);
      scrollToBottom(el);
    }
  });

  // Send message
  const input = el.querySelector('#msg-input');
  const sendBtn = el.querySelector('#send-btn');

  async function sendMessage() {
    const content = input.value.trim();
    if (!content) return;
    input.value = '';
    sendBtn.disabled = true;
    try {
      await net.post('groups.php', { action: 'chat-send', group_id: groupId, content });
    } catch (e) {
      bus.emit('toast', { text: t('common.error'), type: 'error' });
      input.value = content;
    }
    sendBtn.disabled = false;
    input.focus();
  }

  sendBtn.addEventListener('click', sendMessage);
  input.addEventListener('keydown', (e) => { if (e.key === 'Enter') sendMessage(); });

  // Invite game button
  el.querySelector('#invite-game-btn').addEventListener('click', () => {
    audio.play('click');
    showGamePicker(el, groupId);
  });

  // Check for active game invites
  checkGroupInvites(el, groupId, myId);
  inviteTimer = setInterval(() => checkGroupInvites(el, groupId, myId), 5000);
}

function renderMessages(container, messages, myId, memberMap, mutedIds) {
  container.innerHTML = messages
    .filter(m => !mutedIds.includes(m.sender_id))
    .map(m => messageHtml(m, myId, memberMap))
    .join('');
}

function appendMessage(container, msg, myId, memberMap) {
  const div = document.createElement('div');
  div.innerHTML = messageHtml(msg, myId, memberMap);
  container.appendChild(div.firstElementChild);
}

function messageHtml(msg, myId, memberMap) {
  const isMine = msg.sender_id === myId;

  if (msg.message_type === 'system') {
    const meta = typeof msg.metadata === 'string' ? JSON.parse(msg.metadata) : (msg.metadata || {});
    let systemText = msg.content;
    if (msg.content === '__system:game_invite') {
      const gameLabel = meta.game_key === 'ludo' ? 'لودو' : meta.game_key === 'domino' ? 'دومينو' : 'شطرنج';
      systemText = `${emoji('swords', '⚔️', 12)} دعوة لعب ${gameLabel} (${meta.required_players} لاعبين)`;
    }
    return `<div style="text-align:center;padding:6px;font-size:11px;color:#64748b;">${systemText}</div>`;
  }

  const profile = memberMap[msg.sender_id] || msg.profiles || {};
  const name = profile.display_name || 'Player';
  const time = new Date(msg.created_at).toLocaleTimeString('ar', { hour: '2-digit', minute: '2-digit' });

  if (isMine) {
    return `
      <div style="display:flex;justify-content:flex-end;">
        <div style="max-width:75%;background:#2563EB;border-radius:12px 12px 4px 12px;padding:8px 12px;">
          <div style="font-size:13px;color:#fff;word-wrap:break-word;">${escapeHtml(msg.content)}</div>
          <div style="font-size:9px;color:rgba(255,255,255,0.5);margin-top:2px;">${time}</div>
        </div>
      </div>`;
  }

  return `
    <div style="display:flex;gap:8px;align-items:flex-end;">
      <div style="width:28px;height:28px;border-radius:50%;background:#2a2a4a;display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;">
        ${profile.avatar_url ? `<img src="${profile.avatar_url}" style="width:28px;height:28px;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 12)}
      </div>
      <div style="max-width:70%;background:#1a1a2e;border-radius:12px 12px 12px 4px;padding:8px 12px;">
        <div style="font-size:10px;font-weight:600;color:#64748b;margin-bottom:2px;">${escapeHtml(name)}</div>
        <div style="font-size:13px;color:#e2e8f0;word-wrap:break-word;">${escapeHtml(msg.content)}</div>
        <div style="font-size:9px;color:#4a5568;margin-top:2px;">${time}</div>
      </div>
    </div>`;
}

function scrollToBottom(el) {
  const chat = el.querySelector('#chat-messages');
  if (chat) chat.scrollTop = chat.scrollHeight;
}

async function checkGroupInvites(el, groupId, myId) {
  const banner = el.querySelector('#invite-banner');
  if (!banner) return;

  try {
    const data = await net.get('groups.php', { action: 'check-group-invites', group_id: groupId });
    const invites = data.invites || [];
    if (!invites.length) { banner.style.display = 'none'; return; }

    banner.style.display = 'block';
    banner.innerHTML = invites.map(inv => {
      const gameLabel = inv.game_key === 'ludo' ? 'لودو' : inv.game_key === 'domino' ? 'دومينو' : 'شطرنج';
      const accepted = inv.accepted || [];
      const isAccepted = accepted.includes(myId);
      const isInviter = accepted[0] === myId;
      return `
        <div style="display:flex;align-items:center;gap:8px;padding:8px 16px;background:linear-gradient(135deg,#1a2a1a,#0f1f0f);border-bottom:1px solid rgba(52,211,153,0.2);">
          <span style="font-size:16px;">⚔️</span>
          <div style="flex:1;">
            <div style="font-size:12px;font-weight:600;color:#34D399;">${gameLabel} — ${accepted.length}/${inv.required_players}</div>
          </div>
          ${isAccepted || isInviter ? `<span style="font-size:11px;color:#64748b;">✓ قبلت</span>` : `<button class="btn btn-primary accept-invite-btn" data-match="${inv.match_id}" data-game="${inv.game_key}" style="min-height:28px;padding:4px 12px;font-size:11px;">انضم</button>`}
        </div>`;
    }).join('');

    banner.querySelectorAll('.accept-invite-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        btn.disabled = true;
        btn.textContent = '...';
        try {
          const res = await net.post('groups.php', {
            action: 'accept-group-invite',
            match_id: btn.dataset.match,
            game_key: btn.dataset.game
          });
          if (res.started) {
            cleanup();
            if (btn.dataset.game === 'ludo') {
              scene.push('ludo-game', { matchId: res.match_id, playerIndex: res.player_index });
            } else {
              scene.push('chess-game', { matchId: res.match_id, color: res.color });
            }
          } else {
            btn.textContent = '✓ قبلت';
            btn.style.background = 'transparent';
            btn.style.color = '#64748b';
          }
        } catch (e) {
          btn.textContent = 'خطأ';
          btn.disabled = false;
        }
      });
    });
  } catch (e) {}
}

function showGamePicker(el, groupId) {
  const existing = document.getElementById('game-picker-overlay');
  if (existing) existing.remove();

  const overlay = document.createElement('div');
  overlay.id = 'game-picker-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:24px;width:100%;max-width:400px;display:flex;flex-direction:column;gap:12px;">
      <div style="font-size:16px;font-weight:700;color:#f8fafc;text-align:center;">دعوة لعب في المجموعة</div>
      <button class="game-pick" data-game="chess" data-players="2" style="display:flex;align-items:center;gap:12px;padding:14px;background:#2a2a4a;border-radius:12px;border:none;cursor:pointer;width:100%;">
        <span style="font-size:24px;">♟️</span>
        <div style="text-align:right;flex:1;">
          <div style="font-size:14px;font-weight:600;color:#f8fafc;">شطرنج</div>
          <div style="font-size:11px;color:#64748b;">لاعبين</div>
        </div>
      </button>
      <button class="game-pick" data-game="ludo" data-players="4" style="display:flex;align-items:center;gap:12px;padding:14px;background:#2a2a4a;border-radius:12px;border:none;cursor:pointer;width:100%;">
        <span style="font-size:24px;">🎲</span>
        <div style="text-align:right;flex:1;">
          <div style="font-size:14px;font-weight:600;color:#f8fafc;">لودو</div>
          <div style="font-size:11px;color:#64748b;">2-4 لاعبين</div>
        </div>
      </button>
      <button class="game-pick" data-game="domino" data-players="2" style="display:flex;align-items:center;gap:12px;padding:14px;background:#2a2a4a;border-radius:12px;border:none;cursor:pointer;width:100%;">
        <span style="font-size:24px;">🁣</span>
        <div style="text-align:right;flex:1;">
          <div style="font-size:14px;font-weight:600;color:#f8fafc;">دومينو</div>
          <div style="font-size:11px;color:#64748b;">لاعبين</div>
        </div>
      </button>
      <button id="cancel-pick" class="btn btn-secondary w-full" style="min-height:40px;">${t('common.cancel')}</button>
    </div>
  `;

  overlay.querySelector('#cancel-pick').addEventListener('click', () => overlay.remove());
  overlay.addEventListener('click', (e) => { if (e.target === overlay) overlay.remove(); });

  overlay.querySelectorAll('.game-pick').forEach(btn => {
    btn.addEventListener('click', async () => {
      const gameKey = btn.dataset.game;
      const requiredPlayers = parseInt(btn.dataset.players);
      overlay.remove();
      try {
        await net.post('groups.php', {
          action: 'invite-game',
          group_id: groupId,
          game_key: gameKey,
          required_players: requiredPlayers
        });
        bus.emit('toast', { text: 'تم إرسال دعوة اللعب!', type: 'success' });
      } catch (e) {
        bus.emit('toast', { text: e.message || t('common.error'), type: 'error' });
      }
    });
  });

  document.body.appendChild(overlay);
}

function cleanup() {
  if (realtimeSub) { realtimeSub(); realtimeSub = null; }
  if (inviteTimer) { clearInterval(inviteTimer); inviteTimer = null; }
}

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