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

export function mountChallenge(el) {
  el.innerHTML = `
    <div class="cf-layout">
      <div class="cf-header">
        <button id="cf-back" class="cf-back-btn">→</button>
        <div class="cf-title">${emoji('challenge_swords', '⚔️', 18)} تحدّي صديق</div>
      </div>
      <div class="cf-body" id="cf-body">
        <div style="text-align:center;padding:32px;color:#64748b;font-size:13px;">${emoji('loading', '⏳', 14)} جاري تحميل الأصدقاء...</div>
      </div>
    </div>
    <style>
      .cf-layout { display:flex;flex-direction:column;height:100%;background:#0a0a14; }
      .cf-header { display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.06); }
      .cf-back-btn { background:none;border:none;color:#94a3b8;font-size:20px;cursor:pointer;padding:4px 8px;font-family:inherit; }
      .cf-title { font-size:16px;font-weight:700;color:#f8fafc; }
      .cf-body { flex:1;overflow-y:auto;padding:16px; }
      .cf-card { display:flex;align-items:center;gap:12px;padding:14px;background:#1a1a2e;border-radius:14px;margin-bottom:10px;cursor:pointer;transition:transform 0.1s,background 0.15s;border:1px solid rgba(255,255,255,0.04); }
      .cf-card:active { transform:scale(0.98);background:#222244; }
      .cf-card-avatar { width:48px;height:48px;border-radius:50%;background:#2a2a4a;display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;position:relative; }
      .cf-card-avatar img { width:100%;height:100%;object-fit:cover;border-radius:50%; }
      .cf-card-online { position:absolute;bottom:1px;right:1px;width:12px;height:12px;border-radius:50%;background:#34D399;border:2px solid #1a1a2e; }
      .cf-card-info { flex:1;min-width:0; }
      .cf-card-name { font-size:14px;font-weight:600;color:#f8fafc;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
      .cf-card-sub { font-size:11px;color:#64748b;margin-top:2px; }
      .cf-card-action { padding:8px 16px;border-radius:10px;background:linear-gradient(135deg,#7c3aed,#a855f7);border:none;color:#fff;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;transition:transform 0.1s; }
      .cf-card-action:active { transform:scale(0.9); }
      .cf-section-title { font-size:12px;font-weight:600;color:#64748b;margin-bottom:8px;padding-right:4px; }
    </style>
  `;

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

  loadFriendsForChallenge(el);
}

async function loadFriendsForChallenge(el) {
  const body = el.querySelector('#cf-body');

  try {
    const data = await net.get('friends.php', { action: 'list' });
    const friends = data.friends || [];

    if (friends.length === 0) {
      body.innerHTML = `
        <div style="text-align:center;padding:48px 24px;">
          <div style="font-size:48px;margin-bottom:12px;opacity:0.5;">${emoji('people', '👥', 48)}</div>
          <div style="font-size:15px;font-weight:700;color:#f8fafc;margin-bottom:6px;">لا يوجد أصدقاء بعد</div>
          <div style="font-size:12px;color:#64748b;margin-bottom:16px;">أضف أصدقاء أولاً لتتمكن من تحديهم</div>
          <button class="btn btn-primary" id="cf-go-social" style="font-size:13px;padding:10px 24px;">${emoji('search_icon', '🔍', 13)} ابحث عن لاعبين</button>
        </div>`;
      body.querySelector('#cf-go-social')?.addEventListener('click', () => scene.push('friends'));
      return;
    }

    const online = friends.filter(f => f.is_online);
    const offline = friends.filter(f => !f.is_online);

    let html = '';

    if (online.length > 0) {
      html += `<div class="cf-section-title">${emoji('green_circle', '🟢', 11)} متصلين الآن (${online.length})</div>`;
      html += online.map(f => renderChallengeCard(f, true)).join('');
    }

    if (offline.length > 0) {
      html += `<div class="cf-section-title" style="margin-top:${online.length > 0 ? '16px' : '0'};">${emoji('gray_circle', '⚪', 11)} غير متصلين</div>`;
      html += offline.map(f => renderChallengeCard(f, false)).join('');
    }

    body.innerHTML = html;

    // Bind challenge buttons
    body.querySelectorAll('[data-challenge]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        audio.play('click');
        juice.hapticLight();
        const uid = btn.dataset.challenge;
        const card = btn.closest('.cf-card');
        const name = card?.querySelector('.cf-card-name')?.textContent || 'صديق';
        const friend = friends.find(f => f.id === uid);
        showChallengeOptions(el, uid, name, friend);
      });
    });

    // Bind card tap -> open chat
    body.querySelectorAll('.cf-card').forEach(card => {
      card.addEventListener('click', () => {
        const uid = card.dataset.uid;
        const friend = friends.find(f => f.id === uid);
        if (friend) {
          audio.play('click');
          scene.push('friend-chat', { friendId: uid, profile: friend });
        }
      });
    });

  } catch (e) {
    body.innerHTML = `<div style="text-align:center;color:#ef4444;padding:24px;">فشل التحميل — <button id="cf-retry" style="color:#3b82f6;background:none;border:none;text-decoration:underline;cursor:pointer;font-family:inherit;">حاول مرة أخرى</button></div>`;
    body.querySelector('#cf-retry')?.addEventListener('click', () => loadFriendsForChallenge(el));
  }
}

function renderChallengeCard(f, isOnline) {
  return `
    <div class="cf-card" data-uid="${f.id}">
      <div class="cf-card-avatar">
        ${f.avatar_url ? `<img src="${f.avatar_url}">` : emoji('person', '👤', 22)}
        ${isOnline ? '<div class="cf-card-online"></div>' : ''}
      </div>
      <div class="cf-card-info">
        <div class="cf-card-name">${f.display_name || f.username || 'لاعب'}</div>
        <div class="cf-card-sub">${isOnline ? 'متصل الآن' : 'غير متصل'}${f.level ? ` • مستوى ${f.level}` : ''}</div>
      </div>
      <button class="cf-card-action" data-challenge="${f.id}">${emoji('challenge_swords', '⚔️', 12)} تحدّي</button>
    </div>
  `;
}

function showChallengeOptions(el, targetId, targetName, friendProfile) {
  const existing = document.getElementById('cf-options-dialog');
  if (existing) existing.remove();

  const dialog = document.createElement('div');
  dialog.id = 'cf-options-dialog';
  dialog.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:999;display:flex;align-items:flex-end;justify-content:center;padding:0;';
  dialog.innerHTML = `
    <div style="background:#1a1a2e;border-radius:20px 20px 0 0;padding:24px 20px;width:100%;max-width:400px;animation:slideUp 0.25s ease;">
      <div style="width:40px;height:4px;background:rgba(255,255,255,0.15);border-radius:2px;margin:0 auto 16px;"></div>
      <div style="text-align:center;margin-bottom:16px;">
        <div style="font-size:15px;font-weight:700;color:#f8fafc;">تحدّي ${targetName}</div>
        <div style="font-size:12px;color:#64748b;margin-top:4px;">اختر اللعبة ونوع الوقت</div>
      </div>

      <!-- Game selection -->
      <div style="display:flex;gap:8px;margin-bottom:14px;">
        <button class="cfo-game active" data-game="chess" style="flex:1;padding:12px;border-radius:12px;background:#2563EB;border:2px solid #2563EB;color:#fff;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s;">♟ شطرنج</button>
        <button class="cfo-game" data-game="ludo" style="flex:1;padding:12px;border-radius:12px;background:#1a1a2e;border:2px solid rgba(255,255,255,0.08);color:#94a3b8;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s;">🎲 لودو</button>
        <button class="cfo-game" data-game="domino" style="flex:1;padding:12px;border-radius:12px;background:#1a1a2e;border:2px solid rgba(255,255,255,0.08);color:#94a3b8;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s;">🁣 دومينو</button>
      </div>

      <!-- Time control -->
      <div id="cfo-time" style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:20px;">
        <button class="cfo-tc" data-tc="bullet_1_0">⚡ 1 د</button>
        <button class="cfo-tc active" data-tc="blitz_3_0">🔥 3 د</button>
        <button class="cfo-tc" data-tc="blitz_5_0">💨 5 د</button>
        <button class="cfo-tc" data-tc="rapid_10_0">🕐 10 د</button>
      </div>

      <button class="btn btn-primary" id="cfo-send" style="width:100%;min-height:50px;font-size:15px;font-weight:700;border-radius:14px;">⚔️ أرسل التحدي</button>
      <button id="cfo-cancel" style="width:100%;margin-top:10px;background:none;border:none;color:#64748b;font-size:13px;cursor:pointer;font-family:inherit;padding:10px;">إلغاء</button>
    </div>
    <style>
      @keyframes slideUp { from{transform:translateY(100%)}to{transform:none} }
      .cfo-tc { padding:10px 8px;border-radius:10px;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.08);color:#94a3b8;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s; }
      .cfo-tc.active { background:#E4AC38;border-color:#E4AC38;color:#1a1a1a; }
      .cfo-tc:active { transform:scale(0.93); }
    </style>
  `;

  document.body.appendChild(dialog);

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

  dialog.querySelectorAll('.cfo-game').forEach(btn => {
    btn.addEventListener('click', () => {
      dialog.querySelectorAll('.cfo-game').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('#cfo-time').style.display = (selectedGame === 'ludo' || selectedGame === 'domino') ? 'none' : 'grid';
    });
  });

  dialog.querySelectorAll('.cfo-tc').forEach(btn => {
    btn.addEventListener('click', () => {
      dialog.querySelectorAll('.cfo-tc').forEach(b => { b.classList.remove('active'); b.style.background = 'rgba(255,255,255,0.05)'; b.style.borderColor = 'rgba(255,255,255,0.08)'; b.style.color = '#94a3b8'; });
      btn.classList.add('active'); btn.style.background = '#E4AC38'; btn.style.borderColor = '#E4AC38'; btn.style.color = '#1a1a1a';
      selectedTc = btn.dataset.tc;
    });
  });

  dialog.querySelector('#cfo-send').addEventListener('click', async () => {
    const sendBtn = dialog.querySelector('#cfo-send');
    sendBtn.disabled = true;
    sendBtn.textContent = '⏳ جاري الإرسال...';

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

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

      // Also send a chat message
      net.post('chat.php', {
        action: 'send',
        friend_id: targetId,
        content: `أرسل تحدي ${selectedGame === 'ludo' ? 'لودو' : selectedGame === 'domino' ? 'دومينو' : 'شطرنج'}`,
        message_type: 'invite',
        metadata: { game_key: selectedGame, time_control: selectedTc, match_id: res.match_id }
      }).catch(() => {});

      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: targetId,
        friendProfile: friendProfile || {},
        isHost: true
      });
    } catch (e) {
      sendBtn.textContent = 'فشل — حاول مرة أخرى';
      sendBtn.disabled = false;
    }
  });

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