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';

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 || 'صديق';
  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 ? 'متصل الآن' : 'غير متصل'}</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)} جاري التحميل...</div>
      </div>

      <!-- Input -->
      <div class="chat-input-bar">
        <input type="text" id="chat-input" class="chat-input" 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:#0a0a14; }
      .chat-header { display:flex;align-items:center;gap:10px;padding:10px 14px;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.06); }
      .chat-back-btn { background:none;border:none;color:#94a3b8;font-size:20px;cursor:pointer;padding:4px 8px;font-family:inherit; }
      .chat-header-avatar { width:36px;height:36px;border-radius:50%;background:#2a2a4a;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:#f8fafc;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
      .chat-header-status { font-size:11px;color:#64748b; }
      .chat-action-btn { width:36px;height:36px;border-radius:50%;background:#1a1a2e;border:1px solid rgba(255,255,255,0.08);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:#64748b;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:#2563EB;color:#fff;border-bottom-left-radius:16px;border-bottom-right-radius:4px; }
      .chat-bubble.theirs { align-self:flex-start;background:#1a1a2e;color:#e2e8f0;border-bottom-left-radius:4px;border-bottom-right-radius:16px; }
      .chat-bubble.system { align-self:center;background:rgba(228,172,56,0.1);color:#E4AC38;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:#0f0f1e;border-top:1px solid rgba(255,255,255,0.06);padding-bottom:max(10px, env(safe-area-inset-bottom, 0px)); }
      .chat-input { flex:1;background:#1a1a2e;border:1px solid rgba(255,255,255,0.08);border-radius:20px;padding:10px 16px;color:#f8fafc;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:#2563EB;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:#475569;padding:8px 0;position:relative; }
      .chat-day-divider::before,.chat-day-divider::after { content:'';position:absolute;top:50%;width:30%;height:1px;background:rgba(255,255,255,0.06); }
      .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:#ef4444;">فشل تحميل الرسائل</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 });
    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:#64748b;">ابدأ المحادثة مع صديقك!</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' ? '🎲 لودو' : '♟ شطرنج';
      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)} تحدي ${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 || true) {
    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 || 'صديق';

  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:#1a1a2e;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:#f8fafc;margin-bottom:4px;">تحدّي ${name}</div>
      <div style="font-size:12px;color:#64748b;margin-bottom:16px;">اختر اللعبة</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:#2563EB;border:2px solid #2563EB;color:#fff;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">♟ شطرنج</button>
        <button class="cig" data-game="ludo" style="flex:1;padding:10px;border-radius:10px;background:#1a1a2e;border:2px solid rgba(255,255,255,0.08);color:#94a3b8;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">🎲 لودو</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 rgba(255,255,255,0.08);color:#94a3b8;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">1 د</button>
        <button class="cit active" data-tc="blitz_3_0" style="padding:6px 10px;border-radius:8px;background:#E4AC38;border:none;color:#1a1a1a;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">3 د</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 rgba(255,255,255,0.08);color:#94a3b8;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">5 د</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 rgba(255,255,255,0.08);color:#94a3b8;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">10 د</button>
      </div>

      <button class="btn btn-primary" id="cig-send" style="width:100%;font-size:14px;padding:12px;">أرسل التحدي</button>
      <button id="cig-cancel" style="margin-top:8px;background:none;border:none;color:#64748b;font-size:12px;cursor:pointer;font-family:inherit;">إلغاء</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 = '#1a1a2e'; b.style.borderColor = 'rgba(255,255,255,0.08)'; b.style.color = '#94a3b8'; b.classList.remove('active'); });
      btn.style.background = '#2563EB'; btn.style.borderColor = '#2563EB'; btn.style.color = '#fff'; btn.classList.add('active');
      selectedGame = btn.dataset.game;
      dialog.querySelector('#cig-time').style.display = selectedGame === 'ludo' ? '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 rgba(255,255,255,0.08)'; b.style.color = '#94a3b8'; b.classList.remove('active'); });
      btn.style.background = '#E4AC38'; btn.style.border = 'none'; btn.style.color = '#1a1a1a'; 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 = 'جاري الإرسال...';

    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: `أرسل تحدي ${selectedGame === 'ludo' ? 'لودو' : 'شطرنج'}`,
        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 = 'فشل — حاول مرة أخرى';
      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();
}
