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 { t } from '../../../core/i18n.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)} ${t('challenge.title')}</div>
      </div>
      <div class="cf-body" id="cf-body">
        <div style="text-align:center;padding:32px;color:var(--text-muted);font-size:13px;">${emoji('loading', '⏳', 14)} ${t('challenge.loading_friends')}</div>
      </div>
    </div>
    <style>
      .cf-layout { display:flex;flex-direction:column;height:100%;background:var(--bg-deep); }
      .cf-header { display:flex;align-items:center;gap:12px;padding:12px 16px;background:var(--bg-panel);border-bottom:1px solid var(--border); }
      .cf-back-btn { background:none;border:none;color:var(--text-secondary);font-size:20px;cursor:pointer;padding:4px 8px;font-family:inherit; }
      .cf-title { font-size:16px;font-weight:700;color:var(--text-primary); }
      .cf-body { flex:1;overflow-y:auto;padding:16px; }
      .cf-card { display:flex;align-items:center;gap:12px;padding:14px;background:var(--bg-card);border-radius:14px;margin-bottom:10px;cursor:pointer;transition:transform 0.1s,background 0.15s;border:1px solid var(--border); }
      .cf-card:active { transform:scale(0.98);background:var(--bg-hover); }
      .cf-card-avatar { width:48px;height:48px;border-radius:50%;background:var(--bg-hover);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:var(--success);border:2px solid var(--bg-card); }
      .cf-card-info { flex:1;min-width:0; }
      .cf-card-name { font-size:14px;font-weight:600;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
      .cf-card-sub { font-size:11px;color:var(--text-muted);margin-top:2px; }
      .cf-card-action { padding:8px 16px;border-radius:10px;background:linear-gradient(135deg,var(--violet),var(--purple-light));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:var(--text-muted);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:var(--text-primary);margin-bottom:6px;">${t('challenge.no_friends')}</div>
          <div style="font-size:12px;color:var(--text-muted);margin-bottom:16px;">${t('challenge.no_friends_hint')}</div>
          <button class="btn btn-primary" id="cf-go-social" style="font-size:13px;padding:10px 24px;">${emoji('search_icon', '🔍', 13)} ${t('social.search_players')}</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)} ${t('challenge.online_now', { n: 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)} ${t('challenge.offline')}</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 || t('common.friend');
        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:var(--error);padding:24px;">${t('common.error_load')} — <button id="cf-retry" style="color:var(--blue);background:none;border:none;text-decoration:underline;cursor:pointer;font-family:inherit;">${t('social.retry_load')}</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 || t('common.player')}</div>
        <div class="cf-card-sub">${isOnline ? t('common.online') : t('common.offline')}${f.level ? ` • ${t('common.level', { n: f.level })}` : ''}</div>
      </div>
      <button class="cf-card-action" data-challenge="${f.id}">${emoji('challenge_swords', '⚔️', 12)} ${t('challenge.title')}</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:var(--bg-card);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:var(--border-hover);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:var(--text-primary);">${t('challenge.title')} ${targetName}</div>
        <div style="font-size:12px;color:var(--text-muted);margin-top:4px;">${t('challenge.select_game')}</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:var(--chess-primary);border:2px solid var(--chess-primary);color:#fff;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s;">${emoji('chess_pawn', '♟', 14)} ${t('game.chess')}</button>
        <button class="cfo-game" data-game="ludo" style="flex:1;padding:12px;border-radius:12px;background:var(--bg-card);border:2px solid var(--border);color:var(--text-secondary);font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s;">${emoji('dice', '🎲', 14)} ${t('game.ludo')}</button>
        <button class="cfo-game" data-game="domino" style="flex:1;padding:12px;border-radius:12px;background:var(--bg-card);border:2px solid var(--border);color:var(--text-secondary);font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s;">${emoji('domino_tile', '🁣', 14)} ${t('game.domino')}</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">${emoji('lightning', '⚡', 12)} ${t('time.1min')}</button>
        <button class="cfo-tc active" data-tc="blitz_3_0">${emoji('fire', '🔥', 12)} ${t('time.3min')}</button>
        <button class="cfo-tc" data-tc="blitz_5_0">${emoji('wind', '💨', 12)} ${t('time.5min')}</button>
        <button class="cfo-tc" data-tc="rapid_10_0">${emoji('clock', '🕐', 12)} ${t('time.10min')}</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;">${emoji('challenge_swords', '⚔️', 15)} ${t('challenge.send')}</button>
      <button id="cfo-cancel" style="width:100%;margin-top:10px;background:none;border:none;color:var(--text-muted);font-size:13px;cursor:pointer;font-family:inherit;padding:10px;">${t('common.cancel')}</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 var(--border);color:var(--text-secondary);font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;transition:all 0.15s; }
      .cfo-tc.active { background:var(--gold);border-color:var(--gold);color:var(--bg-dark); }
      .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 = '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('#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 = 'var(--border)'; b.style.color = 'var(--text-secondary)'; });
      btn.classList.add('active'); btn.style.background = 'var(--gold)'; btn.style.borderColor = 'var(--gold)'; btn.style.color = 'var(--bg-dark)';
      selectedTc = btn.dataset.tc;
    });
  });

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

    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; }
      if (!res.match_id) { sendBtn.textContent = t('challenge.failed_create'); sendBtn.disabled = false; return; }

      // Also send a chat message
      net.post('chat.php', {
        action: 'send',
        friend_id: targetId,
        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 }
      }).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 = t('challenge.failed_retry');
      sendBtn.disabled = false;
    }
  });

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