import * as net from '../../../core/net.js';
import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as bus from '../../../core/bus.js';
import * as store from '../../../core/store.js';
import * as juice from '../../../core/juice.js';
import * as modal from '../../../core/modal.js';
import { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

let activeTab = 'friends';
let refreshTimer = null;
let inviteCheckTimer = null;

export function mountFriends(el) {
  activeTab = 'friends';
  if (refreshTimer) clearInterval(refreshTimer);
  if (inviteCheckTimer) clearInterval(inviteCheckTimer);

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;">
      <div style="padding:12px 16px;background:var(--bg-panel);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
          <h2 style="font-size:18px;font-weight:700;color:var(--text-primary);">${t('social.friends')}</h2>
          <button class="btn btn-secondary" id="btn-search" style="min-height:34px;padding:6px 14px;font-size:12px;">${emoji('search_icon', '🔍', 13)} ${t('social.search_btn')}</button>
        </div>
        <div style="display:flex;gap:6px;flex-wrap:wrap;">
          <button class="social-tab active" data-tab="friends">${t('social.friends_tab')}</button>
          <button class="social-tab" data-tab="pending">${t('social.pending_tab')} <span id="pending-count" style="display:none;font-size:10px;background:var(--error);color:#fff;border-radius:50%;padding:1px 5px;margin-right:2px;"></span></button>
          <button class="social-tab" data-tab="online">${t('social.online_tab')}</button>
          <button class="social-tab" data-tab="groups">${emoji('group', '👥', 12)} ${t('social.groups_tab')}</button>
          <button class="social-tab" data-tab="activity">${emoji('news', '📰', 12)} ${t('social.activity_tab')}</button>
        </div>
      </div>
      <!-- Invite banner -->
      <div id="invite-banner" style="display:none;"></div>
      <div id="social-content" style="flex:1;overflow-y:auto;padding:12px 16px;"></div>
    </div>
    <style>
      .social-tab{background:rgba(255,255,255,0.05);border:1px solid var(--border);color:var(--text-secondary);font-size:12px;font-weight:600;padding:7px 14px;border-radius:8px;cursor:pointer;font-family:inherit;transition:all 0.15s;}
      .social-tab.active{background:var(--chess-primary);border-color:var(--chess-primary);color:#fff;}
      .social-tab:active{transform:scale(0.95);}
      .friend-card{display:flex;align-items:center;gap:12px;padding:12px;background:var(--bg-card);border-radius:12px;margin-bottom:8px;transition:transform 0.1s;}
      .friend-card:active{transform:scale(0.98);}
      .friend-avatar{width:44px;height:44px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;font-size:18px;overflow:hidden;position:relative;flex-shrink:0;}
      .friend-avatar img{width:100%;height:100%;object-fit:cover;border-radius:50%;}
      .online-dot{position:absolute;bottom:0;right:0;width:12px;height:12px;border-radius:50%;background:var(--success);border:2px solid var(--bg-card);}
      .friend-actions{display:flex;gap:6px;flex-shrink:0;}
      .friend-action{width:34px;height:34px;border-radius:8px;background:rgba(255,255,255,0.05);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:14px;cursor:pointer;transition:transform 0.1s,background 0.15s;}
      .friend-action:active{transform:scale(0.85);background:rgba(255,255,255,0.1);}
    </style>
  `;

  el.querySelector('#btn-search').addEventListener('click', () => {
    audio.play('click');
    showSearch(el);
  });

  el.querySelectorAll('.social-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      audio.play('click');
      el.querySelectorAll('.social-tab').forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      activeTab = tab.dataset.tab;
      loadTab(el, activeTab);
    });
  });

  loadTab(el, 'friends');
  loadPendingCount(el);
  checkInvites(el);

  refreshTimer = setInterval(() => {
    if (activeTab === 'online') loadTab(el, 'online');
  }, 15000);

  inviteCheckTimer = setInterval(() => checkInvites(el), 5000);
}

async function checkInvites(el) {
  try {
    const data = await net.post('friends.php', { action: 'check-invites' });
    const invites = data.invites || [];
    const banner = el.querySelector('#invite-banner');
    if (!banner) return;

    if (invites.length === 0) {
      banner.style.display = 'none';
      return;
    }

    // Get inviter profiles
    const fromIds = [...new Set(invites.map(i => i.from_id).filter(Boolean))];
    let profiles = {};
    if (fromIds.length > 0) {
      try {
        const pData = await net.get('friends.php', { action: 'profiles', ids: fromIds.join(',') });
        (pData.profiles || []).forEach(p => { profiles[p.id] = p; });
      } catch (e) {}
    }

    banner.style.display = 'block';
    banner.innerHTML = invites.map(inv => {
      const from = profiles[inv.from_id] || {};
      const name = from.display_name || from.username || t('common.friend');
      const gameLabel = inv.game_key === 'ludo' ? t('game.ludo') : inv.game_key === 'domino' ? t('game.domino') : t('game.chess');
      return `
        <div style="display:flex;align-items:center;gap:10px;padding:10px 16px;background:linear-gradient(135deg,#1a2a1a,#0f1f0f);border-bottom:1px solid rgba(52,211,153,0.2);animation:slideDown 0.3s;">
          ${emoji('challenge_swords', '⚔️', 20)}
          <div style="flex:1;">
            <div style="font-size:13px;font-weight:600;color:var(--success);">${t('social.challenges_you', { name })}</div>
            <div style="font-size:11px;color:var(--text-muted);">${gameLabel}</div>
          </div>
          <button class="btn btn-primary" data-accept-invite="${inv.match_id}" style="min-height:30px;padding:5px 14px;font-size:11px;">${t('social.accept')}</button>
          <button class="btn btn-secondary" data-decline-invite="${inv.match_id}" style="min-height:30px;padding:5px 10px;font-size:11px;">✕</button>
        </div>
      `;
    }).join('');

    banner.querySelectorAll('[data-accept-invite]').forEach(btn => {
      btn.addEventListener('click', async () => {
        btn.disabled = true;
        btn.textContent = '...';
        try {
          const inv = invites.find(i => i.match_id === btn.dataset.acceptInvite);
          const res = await net.post('friends.php', { action: 'accept-invite', match_id: btn.dataset.acceptInvite, game_key: inv?.game_key || 'chess' });
          if (res.error) { btn.textContent = t('social.error'); return; }
          audio.play('reward');
          juice.hapticSuccess();
          scene.push('game-lobby', {
            matchId: res.match_id,
            color: res.color,
            gameKey: inv?.game_key || 'chess',
            timeControl: inv?.time_control || 'rapid_10_0',
            friendId: inv?.from_id,
            playerIndex: res.player_index,
            isHost: false
          });
        } catch (e) {
          btn.textContent = t('common.failed');
        }
      });
    });

    banner.querySelectorAll('[data-decline-invite]').forEach(btn => {
      btn.addEventListener('click', async () => {
        try {
          const inv = invites.find(i => i.match_id === btn.dataset.declineInvite);
          await net.post('friends.php', { action: 'decline-invite', match_id: btn.dataset.declineInvite, game_key: inv?.game_key || 'chess' });
          btn.closest('div[style*="display:flex"]').remove();
          if (banner.children.length === 0) banner.style.display = 'none';
        } catch (e) {}
      });
    });
  } catch (e) {}
}

async function loadPendingCount(el) {
  try {
    const data = await net.get('friends.php', { action: 'pending' });
    const count = (data.pending || []).length;
    const badge = el.querySelector('#pending-count');
    if (badge) {
      if (count > 0) {
        badge.textContent = count;
        badge.style.display = 'inline';
      } else {
        badge.style.display = 'none';
      }
    }
  } catch (e) {}
}

async function loadTab(el, tab) {
  const content = el.querySelector('#social-content');
  content.innerHTML = `<div style="text-align:center;padding:20px;color:var(--text-muted);">${t('common.loading')}</div>`;

  switch (tab) {
    case 'friends': await loadFriends(content); break;
    case 'pending': await loadPending(content, el); break;
    case 'online': await loadOnline(content); break;
    case 'groups': scene.push('groups'); return;
    case 'activity': await loadActivity(content); break;
  }
}

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

    if (friends.length === 0) {
      content.innerHTML = `
        <div style="text-align:center;padding:40px 20px;">
          <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('social.no_friends')}</div>
          <div style="font-size:12px;color:var(--text-muted);margin-bottom:16px;">${t('social.no_friends_hint')}</div>
          <button class="btn btn-primary" id="empty-search" style="font-size:13px;padding:10px 24px;">${emoji('search_icon', '🔍', 13)} ${t('social.search_players')}</button>
        </div>`;
      content.querySelector('#empty-search')?.addEventListener('click', () => {
        showSearch(content.closest('[style*="height:100%"]') || content.parentElement);
      });
      return;
    }

    const online = friends.filter(f => f.is_online);
    const offline = friends.filter(f => !f.is_online);
    const sorted = [...online, ...offline];

    content.innerHTML = `
      <div style="font-size:11px;color:var(--text-muted);margin-bottom:8px;">${t('social.friends_count', { n: friends.length })}${online.length > 0 ? ` — ${t('social.online_count', { n: online.length })}` : ''}</div>
      ${sorted.map(f => renderFriendCard(f)).join('')}
    `;
    bindFriendActions(content);
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--error);padding:24px;">${t('common.error_load')} — <span style="text-decoration:underline;cursor:pointer;" id="retry-friends">${t('social.retry_load')}</span></div>`;
    content.querySelector('#retry-friends')?.addEventListener('click', () => loadFriends(content));
  }
}

async function loadPending(content, rootEl) {
  try {
    const data = await net.get('friends.php', { action: 'pending' });
    const pending = data.pending || [];

    if (pending.length === 0) {
      content.innerHTML = `
        <div style="text-align:center;padding:40px;color:var(--text-muted);">
          <div style="font-size:32px;margin-bottom:8px;opacity:0.5;">${emoji('inbox', '📥', 32)}</div>
          <div>${t('social.no_pending')}</div>
        </div>`;
      return;
    }

    const requesterIds = pending.map(p => p.requester_id).filter(Boolean);
    let profiles = {};
    if (requesterIds.length > 0) {
      try {
        const profileData = await net.get('friends.php', { action: 'profiles', ids: requesterIds.join(',') });
        (profileData.profiles || []).forEach(p => { profiles[p.id] = p; });
      } catch (e) {}
    }

    content.innerHTML = `
      <div style="font-size:11px;color:var(--text-muted);margin-bottom:10px;">${t('social.pending_count', { n: pending.length })}</div>
      ${pending.map(p => {
        const profile = profiles[p.requester_id] || {};
        const name = profile.display_name || profile.username || p.requester_id?.substring(0, 8) || t('common.player');
        const avatar = profile.avatar_url;
        const level = profile.level || 1;
        return `
          <div class="friend-card" data-friendship="${p.id}">
            <div class="friend-avatar">
              ${avatar ? `<img src="${avatar}">` : emoji('person', '👤', 18)}
            </div>
            <div style="flex:1;min-width:0;">
              <div style="font-size:13px;font-weight:600;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${name}</div>
              <div style="font-size:11px;color:var(--text-muted);">${t('common.level', { n: level })} — ${t('social.sent_friend_request')}</div>
            </div>
            <div class="friend-actions">
              <div class="friend-action" data-accept="${p.id}" title="${t('social.accept')}" style="background:rgba(52,211,153,0.15);border-color:rgba(52,211,153,0.3);color:var(--success);font-weight:700;">✓</div>
              <div class="friend-action" data-reject="${p.id}" title="${t('common.cancel')}" style="background:rgba(239,68,68,0.1);border-color:rgba(239,68,68,0.2);color:var(--error);">✕</div>
            </div>
          </div>
        `;
      }).join('')}
    `;

    content.querySelectorAll('[data-accept]').forEach(btn => {
      btn.addEventListener('click', async () => {
        const card = btn.closest('.friend-card');
        const friendshipId = btn.dataset.accept;
        btn.style.opacity = '0.5';
        btn.style.pointerEvents = 'none';
        try {
          const res = await net.post('friends.php', { action: 'accept', friendship_id: friendshipId });
          if (res.error) {
            btn.style.opacity = '1';
            btn.style.pointerEvents = 'auto';
            return;
          }
          audio.play('reward');
          juice.hapticLight();
          card.querySelector('.friend-actions').innerHTML = `<span style="font-size:11px;color:var(--success);font-weight:600;">${t('common.accepted')}</span>`;
          card.style.borderRight = '3px solid var(--success)';
          loadPendingCount(rootEl);
        } catch (e) {
          btn.style.opacity = '1';
          btn.style.pointerEvents = 'auto';
        }
      });
    });

    content.querySelectorAll('[data-reject]').forEach(btn => {
      btn.addEventListener('click', async () => {
        const card = btn.closest('.friend-card');
        const friendshipId = btn.dataset.reject;
        try {
          await net.post('friends.php', { action: 'reject', friendship_id: friendshipId });
          audio.play('click');
          card.style.transition = 'opacity 0.3s, transform 0.3s';
          card.style.opacity = '0';
          card.style.transform = 'translateX(20px)';
          setTimeout(() => card.remove(), 300);
          loadPendingCount(rootEl);
        } catch (e) {}
      });
    });
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--error);">${t('common.error_load')}</div>`;
  }
}

async function loadOnline(content) {
  try {
    const data = await net.get('friends.php', { action: 'list' });
    const friends = (data.friends || []).filter(f => f.is_online);

    if (friends.length === 0) {
      content.innerHTML = `
        <div style="text-align:center;padding:40px;color:var(--text-muted);">
          <div style="font-size:32px;margin-bottom:8px;opacity:0.5;">${emoji('sleeping', '😴', 32)}</div>
          <div style="font-size:14px;margin-bottom:4px;">${t('social.no_online_friends')}</div>
          <div style="font-size:11px;color:var(--text-dim);">${t('social.will_appear_online')}</div>
        </div>`;
      return;
    }

    content.innerHTML = `
      <div style="font-size:11px;color:var(--success);margin-bottom:10px;">${t('social.online_now_count', { n: friends.length })}</div>
      ${friends.map(f => renderFriendCard(f)).join('')}
    `;
    bindFriendActions(content);
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--error);">${t('common.error_load')}</div>`;
  }
}

function renderFriendCard(f) {
  return `
    <div class="friend-card" data-uid="${f.id}" data-profile='${JSON.stringify({id:f.id, display_name:f.display_name, username:f.username, avatar_url:f.avatar_url, level:f.level, is_online:f.is_online}).replace(/'/g, '&#39;')}'>
      <div class="friend-avatar">
        ${f.avatar_url ? `<img src="${f.avatar_url}">` : emoji('person', '👤', 18)}
        ${f.is_online ? '<div class="online-dot"></div>' : ''}
      </div>
      <div style="flex:1;min-width:0;">
        <div style="font-size:13px;font-weight:600;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${f.display_name || f.username || t('common.player')}</div>
        <div style="font-size:11px;color:${f.is_online ? 'var(--success)' : 'var(--text-muted)'};">${f.is_online ? t('common.online') : t('common.offline')}${f.level ? ` — ${t('common.level', { n: f.level })}` : ''}</div>
      </div>
      <div class="friend-actions">
        <div class="friend-action" data-chat="${f.id}" title="${t('social.chat')}" style="background:rgba(37,99,235,0.15);border-color:rgba(37,99,235,0.3);color:var(--blue);">${emoji('chat_bubble', '💬', 14)}</div>
        ${f.is_online ? `<div class="friend-action" data-invite="${f.id}" title="${t('challenge.send')}" style="background:rgba(228,172,56,0.15);border-color:rgba(228,172,56,0.3);color:var(--gold);">${emoji('challenge_swords', '⚔️', 14)}</div>` : ''}
        <div class="friend-action" data-remove="${f.id}" title="${t('social.remove_friend')}" style="font-size:11px;color:var(--text-muted);">✕</div>
      </div>
    </div>
  `;
}

function bindFriendActions(content) {
  content.querySelectorAll('[data-chat]').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      audio.play('click');
      const card = btn.closest('.friend-card');
      let profile = null;
      try { profile = JSON.parse(card?.dataset?.profile || '{}'); } catch(e) {}
      scene.push('friend-chat', { friendId: btn.dataset.chat, profile });
    });
  });

  content.querySelectorAll('[data-invite]').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      audio.play('click');
      juice.hapticLight();
      const uid = btn.dataset.invite;
      const card = btn.closest('.friend-card');
      const name = card?.querySelector('[style*="font-weight:600"]')?.textContent || t('common.friend');
      showInviteDialog(content, uid, name);
    });
  });

  content.querySelectorAll('[data-remove]').forEach(btn => {
    btn.addEventListener('click', async () => {
      audio.play('click');
      const card = btn.closest('.friend-card');
      const name = card?.querySelector('[style*="font-weight:600"]')?.textContent || t('common.friend');
      const confirmed = await modal.confirm(t('social.remove_confirm', { name }), {
        title: t('social.remove_friend'),
        icon: '👋',
        confirmText: t('social.remove_friend'),
        cancelText: t('common.cancel'),
        danger: true
      });
      if (!confirmed) return;
      try {
        await net.post('friends.php', { action: 'remove', target_id: btn.dataset.remove });
        card.style.transition = 'opacity 0.3s, transform 0.3s';
        card.style.opacity = '0';
        card.style.transform = 'translateX(20px)';
        setTimeout(() => card.remove(), 300);
      } catch (e) {}
    });
  });
}

function showInviteDialog(content, targetId, targetName) {
  const existing = document.getElementById('invite-dialog');
  if (existing) existing.remove();

  const dialog = document.createElement('div');
  dialog.id = '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:320px;text-align:center;">
      <div style="font-size:24px;margin-bottom:8px;">${emoji('challenge_swords', '⚔️', 24)}</div>
      <div style="font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:4px;">${t('challenge.send')} — ${targetName}</div>
      <div style="font-size:12px;color:var(--text-muted);margin-bottom:16px;">${t('challenge.select_game')}</div>

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;">
        <button class="inv-game active" data-game="chess" style="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="inv-game" data-game="ludo" style="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>
        <button class="inv-game" data-game="domino" style="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="inv-game" data-game="backgammon" style="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('backgammon', '🎯', 13)} ${t('game.backgammon')}</button>
      </div>

      <div id="time-options" style="display:flex;gap:6px;justify-content:center;margin-bottom:16px;flex-wrap:wrap;">
        <button class="inv-time active" data-tc="bullet_1_0" style="padding:6px 12px;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.1min')}</button>
        <button class="inv-time" data-tc="blitz_3_0" style="padding:6px 12px;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.3min')}</button>
        <button class="inv-time" data-tc="blitz_5_0" style="padding:6px 12px;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="inv-time" data-tc="rapid_10_0" style="padding:6px 12px;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="send-invite" style="width:100%;font-size:14px;padding:12px;">${t('challenge.send')}</button>
      <button id="cancel-invite" 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 = 'bullet_1_0';

  dialog.querySelectorAll('.inv-game').forEach(btn => {
    btn.addEventListener('click', () => {
      dialog.querySelectorAll('.inv-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;
      const timeDiv = dialog.querySelector('#time-options');
      timeDiv.style.display = selectedGame === 'chess' ? 'flex' : 'none';
    });
  });

  dialog.querySelectorAll('.inv-time').forEach(btn => {
    btn.addEventListener('click', () => {
      dialog.querySelectorAll('.inv-time').forEach(b => {
        b.style.background = 'rgba(255,255,255,0.05)';
        b.style.borderColor = '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('#send-invite').addEventListener('click', async () => {
    const sendBtn = dialog.querySelector('#send-invite');
    sendBtn.disabled = true;
    sendBtn.textContent = t('common.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;
      }

      audio.play('reward');
      juice.hapticSuccess();
      sendBtn.textContent = t('challenge.sent');
      sendBtn.style.background = 'var(--success)';

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

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

function showSearch(el) {
  const content = el.querySelector('#social-content');
  content.innerHTML = `
    <div style="margin-bottom:16px;">
      <div style="display:flex;gap:8px;">
        <input class="input" id="search-input" type="text" placeholder="${t('social.search_placeholder')}" style="flex:1;min-height:40px;font-size:14px;" autocomplete="off">
        <button class="btn btn-primary" id="search-go" style="min-height:40px;padding:8px 16px;font-size:13px;">${t('social.search_btn')}</button>
      </div>
      <div style="font-size:11px;color:var(--text-dim);margin-top:4px;">${t('social.search_hint')}</div>
    </div>
    <div id="search-results"></div>
  `;

  const input = content.querySelector('#search-input');
  const btn = content.querySelector('#search-go');
  input.focus();

  let debounceTimer = null;
  const doSearch = async () => {
    const query = input.value.trim();
    if (query.length < 2) {
      content.querySelector('#search-results').innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:12px;font-size:12px;">${t('social.search_min_chars')}</div>`;
      return;
    }
    const results = content.querySelector('#search-results');
    results.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:12px;">${t('social.searching')}</div>`;

    try {
      const data = await net.get('friends.php', { action: 'search', query });
      const players = data.players || [];
      if (players.length === 0) {
        results.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:24px;font-size:13px;">${t('social.no_results')}</div>`;
        return;
      }
      results.innerHTML = players.map(p => `
        <div class="friend-card">
          <div class="friend-avatar">
            ${p.avatar_url ? `<img src="${p.avatar_url}">` : emoji('person', '👤', 18)}
            ${p.is_online ? '<div class="online-dot"></div>' : ''}
          </div>
          <div style="flex:1;min-width:0;">
            <div style="font-size:13px;font-weight:600;color:var(--text-primary);">${p.display_name || p.username || t('common.player')}</div>
            <div style="font-size:11px;color:var(--text-muted);">${p.is_online ? t('common.online') : t('common.offline')} — ${t('common.level', { n: p.level || 1 })}</div>
          </div>
          <button class="btn btn-primary" data-add="${p.id}" style="min-height:32px;padding:6px 12px;font-size:11px;flex-shrink:0;">${t('social.add_btn')}</button>
        </div>
      `).join('');

      results.querySelectorAll('[data-add]').forEach(addBtn => {
        addBtn.addEventListener('click', async () => {
          addBtn.disabled = true;
          addBtn.textContent = '...';
          try {
            const res = await net.post('friends.php', { action: 'request', target_id: addBtn.dataset.add });
            if (res.error) {
              addBtn.textContent = res.error === 'Already friends' ? t('common.already_friends') : res.error === 'Request already pending' ? t('common.already_sent') : res.error;
              addBtn.style.background = 'var(--text-muted)';
              return;
            }
            audio.play('reward');
            juice.hapticLight();
            addBtn.textContent = t('common.sent');
            addBtn.style.background = 'var(--success)';
            addBtn.style.borderColor = 'var(--success)';
          } catch (e) {
            const msg = e.message || '';
            if (msg.includes('duplicate') || msg.includes('already') || msg.includes('Already')) {
              addBtn.textContent = t('common.already_sent');
              addBtn.style.background = 'var(--text-muted)';
            } else {
              addBtn.textContent = t('common.failed');
              addBtn.disabled = false;
              setTimeout(() => { addBtn.textContent = t('social.add_btn'); }, 2000);
            }
          }
        });
      });
    } catch (e) {
      results.innerHTML = `<div style="text-align:center;color:var(--error);">${t('social.search_failed')}</div>`;
    }
  };

  btn.addEventListener('click', doSearch);
  input.addEventListener('keydown', (e) => { if (e.key === 'Enter') doSearch(); });
  input.addEventListener('input', () => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(doSearch, 500);
  });
}

async function loadActivity(content) {
  try {
    const data = await net.get('activity.php');
    const activities = data.activity || [];
    if (activities.length === 0) {
      content.innerHTML = `
        <div style="text-align:center;padding:40px;color:var(--text-muted);">
          <div style="font-size:32px;margin-bottom:8px;opacity:0.5;">${emoji('news', '📰', 32)}</div>
          <div>${t('social.no_activity')}</div>
        </div>`;
      return;
    }
    const labels = {
      game_win: t('social.game_win'),
      game_loss: t('social.game_loss'),
      game_draw: t('social.game_draw'),
      achievement_unlock: t('social.achievement_unlock'),
      level_up: t('social.level_up'),
      tournament_join: t('social.tournament_join'),
      tournament_win: t('social.tournament_win'),
      friend_add: t('social.friend_add')
    };
    const icons = {
      game_win: emoji('trophy', '🏆', 14), game_loss: emoji('broken_heart', '💔', 14), game_draw: emoji('handshake', '🤝', 14),
      achievement_unlock: emoji('medal', '🎖️', 14), level_up: emoji('level_up', '⬆️', 14),
      tournament_join: emoji('medal_gold', '🏅', 14), tournament_win: emoji('medal_gold', '🥇', 14), friend_add: emoji('wave', '👋', 14)
    };
    content.innerHTML = activities.map(a => {
      const actor = a.actor || {};
      const label = labels[a.action] || a.action;
      const icon = icons[a.action] || emoji('pin', '📌', 14);
      return `<div style="display:flex;gap:10px;padding:10px;background:var(--bg-card);border-radius:10px;margin-bottom:6px;">
        <div style="width:36px;height:36px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;">
          ${actor.avatar_url ? `<img src="${actor.avatar_url}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">` : icon}
        </div>
        <div style="flex:1;min-width:0;">
          <div style="font-size:13px;color:var(--text-primary);"><strong>${actor.display_name || actor.username || '?'}</strong> ${label}</div>
          ${a.created_at ? `<div style="font-size:10px;color:var(--text-dim);margin-top:2px;">${timeAgo(a.created_at)}</div>` : ''}
        </div>
      </div>`;
    }).join('');
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:32px;">${t('social.no_activity_short')}</div>`;
  }
}

function timeAgo(dateStr) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return t('common.now');
  if (mins < 60) return t('common.minutes_ago', { n: mins });
  const hours = Math.floor(mins / 60);
  if (hours < 24) return t('common.hours_ago', { n: hours });
  const days = Math.floor(hours / 24);
  if (days < 7) return t('common.days_ago', { n: days });
  return new Date(dateStr).toLocaleDateString('ar');
}

export function unmountFriends() {
  if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; }
  if (inviteCheckTimer) { clearInterval(inviteCheckTimer); inviteCheckTimer = null; }
}
