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:var(--bg-panel);display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--border);">
        <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:var(--text-primary);">${t('common.loading')}</div>
        </div>
        <button class="btn btn-secondary" id="invite-game-btn" style="min-height:var(--tap-min);padding:5px 10px;font-size:12px;">${emoji('swords', '⚔️', 13)} ${t('group.play')}</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:var(--bg-panel);border-top:1px solid var(--border);display:flex;gap:8px;align-items:center;">
        <input class="input" id="msg-input" type="text" placeholder="${t('chat.placeholder')}" style="flex:1;min-height:38px;" maxlength="500">
        <button class="btn btn-primary" id="send-btn" style="min-height:var(--tap-min);padding:0 14px;">${t('common.send')}</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:var(--text-primary);">${escapeHtml(groupData.name)}</div>
      <div style="font-size:11px;color:var(--text-muted);">${members.length} ${t('group.members')}</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);">${t('group.load_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' ? t('game.ludo') : meta.game_key === 'domino' ? t('game.domino') : t('game.chess');
      systemText = `${emoji('swords', '⚔️', 12)} ${t('group.play_invite')} ${gameLabel} (${meta.required_players} ${t('group.players')})`;
    }
    return `<div style="text-align:center;padding:6px;font-size:11px;color:var(--text-muted);">${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:var(--chess-primary);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:var(--fs-xs);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:var(--bg-hover);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:var(--bg-card);border-radius:12px 12px 12px 4px;padding:8px 12px;">
        <div style="font-size:var(--fs-xs);font-weight:600;color:var(--text-muted);margin-bottom:2px;">${escapeHtml(name)}</div>
        <div style="font-size:13px;color:var(--text-light);word-wrap:break-word;">${escapeHtml(msg.content)}</div>
        <div style="font-size:var(--fs-xs);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' ? t('game.ludo') : inv.game_key === 'domino' ? t('game.domino') : t('game.chess');
      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);">
          ${emoji('challenge_swords', '⚔️', 16)}
          <div style="flex:1;">
            <div style="font-size:12px;font-weight:600;color:var(--success);">${gameLabel} — ${accepted.length}/${inv.required_players}</div>
          </div>
          ${isAccepted || isInviter ? `<span style="font-size:11px;color:var(--text-muted);">${t('group.accepted')}</span>` : `<button class="btn btn-primary accept-invite-btn" data-match="${inv.match_id}" data-game="${inv.game_key}" style="min-height:var(--tap-min);padding:4px 12px;font-size:11px;">${t('group.join')}</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 {
              // mode:'live' is required — without it mountGame defaults to
              // 'bot' and the group invite silently started a game against the
              // computer instead of against the person who invited you.
              scene.push('chess-game', {
                mode: 'live',
                matchId: res.match_id,
                color: res.color,
                timeControl: res.time_control
              });
            }
          } else {
            btn.textContent = t('group.accepted');
            btn.style.background = 'transparent';
            btn.style.color = 'var(--text-muted)';
          }
        } catch (e) {
          btn.textContent = t('social.error');
          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:var(--bg-card);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:var(--text-primary);text-align:center;">${t('group.play_invite')}</div>
      <button class="game-pick" data-game="chess" data-players="2" style="display:flex;align-items:center;gap:12px;padding:14px;background:var(--bg-hover);border-radius:12px;border:none;cursor:pointer;width:100%;">
        ${emoji('chess_pawn', '♟️', 24)}
        <div style="text-align:right;flex:1;">
          <div style="font-size:14px;font-weight:600;color:var(--text-primary);">${t('game.chess')}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('group.players')}</div>
        </div>
      </button>
      <button class="game-pick" data-game="ludo" data-players="4" style="display:flex;align-items:center;gap:12px;padding:14px;background:var(--bg-hover);border-radius:12px;border:none;cursor:pointer;width:100%;">
        ${emoji('dice', '🎲', 24)}
        <div style="text-align:right;flex:1;">
          <div style="font-size:14px;font-weight:600;color:var(--text-primary);">${t('game.ludo')}</div>
          <div style="font-size:11px;color:var(--text-muted);">2-4 ${t('group.players')}</div>
        </div>
      </button>
      <button class="game-pick" data-game="domino" data-players="2" style="display:flex;align-items:center;gap:12px;padding:14px;background:var(--bg-hover);border-radius:12px;border:none;cursor:pointer;width:100%;">
        ${emoji('domino_tile', '🁣', 24)}
        <div style="text-align:right;flex:1;">
          <div style="font-size:14px;font-weight:600;color:var(--text-primary);">${t('game.domino')}</div>
          <div style="font-size:11px;color:var(--text-muted);">${t('group.players')}</div>
        </div>
      </button>
      <button id="cancel-pick" class="btn btn-secondary w-full" style="min-height:var(--tap-min);">${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: t('group.invite_sent'), 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; }
}

export const unmountGroupChat = cleanup;

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