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

let pollTimer = null;
let friendId = null;
let friendProfile = null;
let messages = [];
let isLoading = false;

export function mountChat(el, params = {}) {
  friendId = params.friendId;
  friendProfile = params.profile || null;
  messages = [];
  isLoading = false;
  if (pollTimer) clearInterval(pollTimer);

  const name = friendProfile?.display_name || friendProfile?.username || t('common.friend');
  const avatar = friendProfile?.avatar_url;

  el.innerHTML = `
    <div class="chat-layout">
      <!-- Header -->
      <div class="chat-header">
        <button id="chat-back" class="chat-back-btn">→</button>
        <div class="chat-header-avatar">
          ${avatar ? `<img src="${avatar}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 16)}
        </div>
        <div class="chat-header-info">
          <div class="chat-header-name">${name}</div>
          <div class="chat-header-status" id="chat-status">${friendProfile?.is_online ? t('common.online') : t('common.offline')}</div>
        </div>
        <button id="chat-invite" class="chat-action-btn">${emoji('challenge_swords', '⚔️', 16)}</button>
        <button id="chat-profile" class="chat-action-btn">${emoji('person', '👤', 14)}</button>
      </div>

      <!-- Messages -->
      <div class="chat-messages" id="chat-messages">
        <div class="chat-loading" id="chat-loading">${emoji('loading', '⏳', 16)} ${t('common.loading')}</div>
      </div>

      <!-- Input -->
      <div class="chat-input-bar">
        <input type="text" id="chat-input" class="chat-input" placeholder="${t('chat.placeholder')}" maxlength="500" autocomplete="off">
        <button id="chat-send" class="chat-send-btn">${emoji('send', '📤', 18)}</button>
      </div>
    </div>
    <style>
      .chat-layout { display:flex;flex-direction:column;height:100%;background:var(--bg-deep); }
      .chat-header { display:flex;align-items:center;gap:10px;padding:10px 14px;background:var(--bg-panel);border-bottom:1px solid var(--border); }
      .chat-back-btn { background:none;border:none;color:var(--text-secondary);font-size:20px;cursor:pointer;padding:4px 8px;font-family:inherit; }
      .chat-header-avatar { width:36px;height:36px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0; }
      .chat-header-info { flex:1;min-width:0; }
      .chat-header-name { font-size:14px;font-weight:600;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
      .chat-header-status { font-size:11px;color:var(--text-muted); }
      .chat-action-btn { width:36px;height:36px;border-radius:50%;background:var(--bg-card);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:transform 0.1s; }
      .chat-action-btn:active { transform:scale(0.9); }
      .chat-messages { flex:1;overflow-y:auto;padding:12px 14px;display:flex;flex-direction:column;gap:6px; }
      .chat-loading { text-align:center;color:var(--text-muted);font-size:13px;padding:24px; }
      .chat-bubble { max-width:80%;padding:10px 14px;border-radius:16px;font-size:13px;line-height:1.5;word-wrap:break-word;animation:bubbleIn 0.2s ease; }
      .chat-bubble.mine { align-self:flex-end;background:var(--chess-primary);color:#fff;border-bottom-left-radius:16px;border-bottom-right-radius:4px; }
      .chat-bubble.theirs { align-self:flex-start;background:var(--bg-card);color:var(--text-light);border-bottom-left-radius:4px;border-bottom-right-radius:16px; }
      .chat-bubble.system { align-self:center;background:rgba(228,172,56,0.1);color:var(--gold);font-size:12px;border-radius:12px;padding:6px 14px; }
      .chat-bubble .chat-time { font-size:10px;opacity:0.6;margin-top:2px; }
      .chat-bubble.mine .chat-time { text-align:left; }
      .chat-bubble.theirs .chat-time { text-align:right; }
      .chat-input-bar { display:flex;gap:8px;padding:10px 14px;background:var(--bg-panel);border-top:1px solid var(--border);padding-bottom:max(10px, env(safe-area-inset-bottom, 0px)); }
      .chat-input { flex:1;background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:10px 16px;color:var(--text-primary);font-size:14px;font-family:inherit;outline:none;transition:border-color 0.2s; }
      .chat-input:focus { border-color:rgba(37,99,235,0.5); }
      .chat-send-btn { width:44px;height:44px;border-radius:50%;background:var(--chess-primary);border:none;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:transform 0.1s,opacity 0.2s; }
      .chat-send-btn:active { transform:scale(0.9); }
      .chat-send-btn:disabled { opacity:0.4;cursor:default; }
      .chat-day-divider { text-align:center;font-size:11px;color:var(--text-dim);padding:8px 0;position:relative; }
      .chat-day-divider::before,.chat-day-divider::after { content:'';position:absolute;top:50%;width:30%;height:1px;background:var(--border); }
      .chat-day-divider::before { right:0; }
      .chat-day-divider::after { left:0; }
      @keyframes bubbleIn { from{opacity:0;transform:translateY(8px)scale(0.95)}to{opacity:1;transform:none} }
    </style>
  `;

  // Bind events
  el.querySelector('#chat-back').addEventListener('click', () => {
    cleanup();
    scene.pop();
  });

  el.querySelector('#chat-invite').addEventListener('click', () => {
    audio.play('click');
    showInviteFromChat(el);
  });

  el.querySelector('#chat-profile').addEventListener('click', () => {
    audio.play('click');
    scene.push('profile-view', { playerId: friendId });
  });

  const input = el.querySelector('#chat-input');
  const sendBtn = el.querySelector('#chat-send');

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

  // Load history
  loadMessages(el);

  // Poll for new messages every 3s
  pollTimer = setInterval(() => pollNewMessages(el), 3000);
}

async function loadMessages(el) {
  try {
    const data = await net.get('chat.php', { action: 'history', friend_id: friendId });
    messages = data.messages || [];
    renderMessages(el);
  } catch (e) {
    const container = el.querySelector('#chat-messages');
    container.innerHTML = `<div class="chat-loading" style="color:var(--error);">${t('chat.failed_load')}</div>`;
  }
}

async function pollNewMessages(el) {
  if (isLoading || !friendId) return;
  try {
    const lastTime = messages.length > 0 ? messages[messages.length - 1].created_at : null;
    const data = await net.get('chat.php', { action: 'history', friend_id: friendId, limit: 20, after: lastTime });
    const newMsgs = data.messages || [];

    if (newMsgs.length > messages.length) {
      const oldIds = new Set(messages.map(m => m.id));
      const fresh = newMsgs.filter(m => !oldIds.has(m.id));
      if (fresh.length > 0) {
        messages = newMsgs;
        renderMessages(el, true);
        if (fresh.some(m => m.sender_id !== store.get('auth.userId'))) {
          audio.play('notification');
        }
      }
    }
  } catch (e) {}
}

async function sendMessage(el) {
  const input = el.querySelector('#chat-input');
  const content = input.value.trim();
  if (!content || isLoading) return;

  isLoading = true;
  input.value = '';

  try {
    const res = await net.post('chat.php', {
      action: 'send',
      friend_id: friendId,
      content
    });

    if (res.error) {
      input.value = content;
      return;
    }

    const msg = res.message;
    if (msg && msg.id) {
      messages.push(msg);
    } else {
      messages.push({
        id: 'temp-' + Date.now(),
        sender_id: store.get('auth.userId'),
        content,
        message_type: 'text',
        created_at: new Date().toISOString()
      });
    }

    renderMessages(el, true);
    audio.play('click');
    juice.hapticLight();
  } catch (e) {
    input.value = content;
  } finally {
    isLoading = false;
  }
}

function renderMessages(el, scrollToBottom = false) {
  const container = el.querySelector('#chat-messages');
  if (!container) return;

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

  if (messages.length === 0) {
    container.innerHTML = `
      <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;opacity:0.6;">
        <div style="font-size:32px;">${emoji('wave', '👋', 32)}</div>
        <div style="font-size:13px;color:var(--text-muted);">${t('chat.start_conversation')}</div>
      </div>
    `;
    return;
  }

  let html = '';
  let lastDate = '';

  for (const msg of messages) {
    const msgDate = new Date(msg.created_at).toLocaleDateString('ar-EG');
    if (msgDate !== lastDate) {
      lastDate = msgDate;
      html += `<div class="chat-day-divider">${msgDate}</div>`;
    }

    const isMine = msg.sender_id === myId;
    const time = new Date(msg.created_at).toLocaleTimeString('ar-EG', { hour: '2-digit', minute: '2-digit' });

    if (msg.message_type === 'system') {
      html += `<div class="chat-bubble system">${escapeHtml(msg.content)}</div>`;
    } else if (msg.message_type === 'invite') {
      const meta = typeof msg.metadata === 'string' ? JSON.parse(msg.metadata || '{}') : (msg.metadata || {});
      const gameLabel = meta.game_key === 'ludo' ? emoji('dice', '🎲', 13) + ' ' + t('game.ludo') : emoji('chess_pawn', '♟', 13) + ' ' + t('game.chess');
      html += `
        <div class="chat-bubble ${isMine ? 'mine' : 'theirs'}" style="background:${isMine ? 'rgba(37,99,235,0.3)' : 'rgba(228,172,56,0.15)'};border:1px solid ${isMine ? 'rgba(37,99,235,0.3)' : 'rgba(228,172,56,0.3)'};">
          <div style="font-size:12px;font-weight:600;margin-bottom:4px;">${emoji('challenge_swords', '⚔️', 13)} ${t('chat.challenge_title', { name: gameLabel })}</div>
          <div style="font-size:12px;opacity:0.8;">${escapeHtml(msg.content)}</div>
          <div class="chat-time">${time}</div>
        </div>
      `;
    } else {
      html += `
        <div class="chat-bubble ${isMine ? 'mine' : 'theirs'}">
          ${escapeHtml(msg.content)}
          <div class="chat-time">${time}</div>
        </div>
      `;
    }
  }

  container.innerHTML = html;

  if (scrollToBottom) {
    container.scrollTop = container.scrollHeight;
  }
}

function showInviteFromChat(el) {
  const existing = document.getElementById('chat-invite-dialog');
  if (existing) { existing.remove(); return; }

  const name = friendProfile?.display_name || friendProfile?.username || t('common.friend');

  const dialog = document.createElement('div');
  dialog.id = 'chat-invite-dialog';
  dialog.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:999;display:flex;align-items:center;justify-content:center;padding:24px;';
  dialog.innerHTML = `
    <div style="background:var(--bg-card);border-radius:16px;padding:24px;width:100%;max-width:300px;text-align:center;">
      <div style="font-size:24px;margin-bottom:8px;">${emoji('challenge_swords', '⚔️', 24)}</div>
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:4px;">${t('chat.challenge_title', { name })}</div>
      <div style="font-size:12px;color:var(--text-muted);margin-bottom:16px;">${t('chat.choose_game')}</div>

      <div style="display:flex;gap:8px;justify-content:center;margin-bottom:12px;">
        <button class="cig active" data-game="chess" style="flex:1;padding:10px;border-radius:10px;background:var(--chess-primary);border:2px solid var(--chess-primary);color:#fff;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">${emoji('chess_pawn', '♟', 13)} ${t('game.chess')}</button>
        <button class="cig" data-game="domino" style="flex:1;padding:10px;border-radius:10px;background:var(--bg-card);border:2px solid var(--border);color:var(--text-secondary);font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">${emoji('domino_tile', '🁣', 13)} ${t('game.domino')}</button>
        <button class="cig" data-game="ludo" style="flex:1;padding:10px;border-radius:10px;background:var(--bg-card);border:2px solid var(--border);color:var(--text-secondary);font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">${emoji('dice', '🎲', 13)} ${t('game.ludo')}</button>
      </div>

      <div id="cig-time" style="display:flex;gap:6px;justify-content:center;margin-bottom:16px;flex-wrap:wrap;">
        <button class="cit" data-tc="bullet_1_0" style="padding:6px 10px;border-radius:8px;background:rgba(255,255,255,0.05);border:1px solid var(--border);color:var(--text-secondary);font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">${t('time.1min')}</button>
        <button class="cit active" data-tc="blitz_3_0" style="padding:6px 10px;border-radius:8px;background:var(--gold);border:none;color:var(--bg-dark);font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">${t('time.3min')}</button>
        <button class="cit" data-tc="blitz_5_0" style="padding:6px 10px;border-radius:8px;background:rgba(255,255,255,0.05);border:1px solid var(--border);color:var(--text-secondary);font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">${t('time.5min')}</button>
        <button class="cit" data-tc="rapid_10_0" style="padding:6px 10px;border-radius:8px;background:rgba(255,255,255,0.05);border:1px solid var(--border);color:var(--text-secondary);font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">${t('time.10min')}</button>
      </div>

      <button class="btn btn-primary" id="cig-send" style="width:100%;font-size:14px;padding:12px;">${t('challenge.send')}</button>
      <button id="cig-cancel" style="margin-top:8px;background:none;border:none;color:var(--text-muted);font-size:12px;cursor:pointer;font-family:inherit;">${t('common.cancel')}</button>
    </div>
  `;

  document.body.appendChild(dialog);

  let selectedGame = 'chess';
  let selectedTc = 'blitz_3_0';

  dialog.querySelectorAll('.cig').forEach(btn => {
    btn.addEventListener('click', () => {
      dialog.querySelectorAll('.cig').forEach(b => { b.style.background = 'var(--bg-card)'; b.style.borderColor = 'var(--border)'; b.style.color = 'var(--text-secondary)'; b.classList.remove('active'); });
      btn.style.background = 'var(--chess-primary)'; btn.style.borderColor = 'var(--chess-primary)'; btn.style.color = '#fff'; btn.classList.add('active');
      selectedGame = btn.dataset.game;
      dialog.querySelector('#cig-time').style.display = (selectedGame === 'ludo' || selectedGame === 'domino') ? 'none' : 'flex';
    });
  });

  dialog.querySelectorAll('.cit').forEach(btn => {
    btn.addEventListener('click', () => {
      dialog.querySelectorAll('.cit').forEach(b => { b.style.background = 'rgba(255,255,255,0.05)'; b.style.border = '1px solid var(--border)'; b.style.color = 'var(--text-secondary)'; b.classList.remove('active'); });
      btn.style.background = 'var(--gold)'; btn.style.border = 'none'; btn.style.color = 'var(--bg-dark)'; btn.classList.add('active');
      selectedTc = btn.dataset.tc;
    });
  });

  dialog.querySelector('#cig-send').addEventListener('click', async () => {
    const sendBtn = dialog.querySelector('#cig-send');
    sendBtn.disabled = true;
    sendBtn.textContent = t('common.sending');

    try {
      const res = await net.post('friends.php', {
        action: 'invite',
        target_id: friendId,
        game_key: selectedGame,
        time_control: selectedTc
      });

      if (res.error) { sendBtn.textContent = res.error; sendBtn.disabled = false; return; }

      // Send a chat message about the invite
      await net.post('chat.php', {
        action: 'send',
        friend_id: friendId,
        content: t('challenge.sent_msg', { game: selectedGame === 'ludo' ? t('game.ludo') : selectedGame === 'domino' ? t('game.domino') : t('game.chess') }),
        message_type: 'invite',
        metadata: { game_key: selectedGame, time_control: selectedTc, match_id: res.match_id }
      });

      audio.play('reward');
      juice.hapticSuccess();
      dialog.remove();

      // Navigate to lobby
      scene.push('game-lobby', {
        matchId: res.match_id,
        color: res.color,
        gameKey: selectedGame,
        timeControl: selectedTc,
        friendId,
        friendProfile,
        isHost: true
      });
    } catch (e) {
      sendBtn.textContent = t('challenge.failed_retry');
      sendBtn.disabled = false;
    }
  });

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

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

function cleanup() {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  friendId = null;
  friendProfile = null;
  messages = [];
}

export function unmountChat() {
  cleanup();
}
