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:#0f0f1e;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
          <h2 style="font-size:18px;font-weight:700;color:#f8fafc;">${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)} بحث</button>
        </div>
        <div style="display:flex;gap:6px;flex-wrap:wrap;">
          <button class="social-tab active" data-tab="friends">الأصدقاء</button>
          <button class="social-tab" data-tab="pending">الطلبات <span id="pending-count" style="display:none;font-size:10px;background:#EF4444;color:#fff;border-radius:50%;padding:1px 5px;margin-right:2px;"></span></button>
          <button class="social-tab" data-tab="online">متصلين</button>
          <button class="social-tab" data-tab="groups">${emoji('group', '👥', 12)} المجموعات</button>
          <button class="social-tab" data-tab="activity">${emoji('news', '📰', 12)} أخبار</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 rgba(255,255,255,0.08);color:#94a3b8;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:#2563EB;border-color:#2563EB;color:#fff;}
      .social-tab:active{transform:scale(0.95);}
      .friend-card{display:flex;align-items:center;gap:12px;padding:12px;background:#1a1a2e;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:#2a2a4a;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:#34D399;border:2px solid #1a1a2e;}
      .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 rgba(255,255,255,0.08);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 || 'صديق';
      const gameLabel = inv.game_key === 'ludo' ? 'لودو' : inv.game_key === 'domino' ? 'دومينو' : 'شطرنج';
      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;">
          <span style="font-size:20px;">⚔️</span>
          <div style="flex:1;">
            <div style="font-size:13px;font-weight:600;color:#34D399;">${name} يتحداك!</div>
            <div style="font-size:11px;color:#64748b;">${gameLabel}</div>
          </div>
          <button class="btn btn-primary" data-accept-invite="${inv.match_id}" style="min-height:30px;padding:5px 14px;font-size:11px;">قبول</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 = 'خطأ'; 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 = 'فشل';
        }
      });
    });

    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:#64748b;">جاري التحميل...</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:#f8fafc;margin-bottom:6px;">لا يوجد أصدقاء بعد</div>
          <div style="font-size:12px;color:#64748b;margin-bottom:16px;">ابحث عن لاعبين وأرسل لهم طلب صداقة</div>
          <button class="btn btn-primary" id="empty-search" style="font-size:13px;padding:10px 24px;">${emoji('search_icon', '🔍', 13)} ابحث عن لاعبين</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:#64748b;margin-bottom:8px;">${friends.length} أصدقاء${online.length > 0 ? ` — ${online.length} متصل` : ''}</div>
      ${sorted.map(f => renderFriendCard(f)).join('')}
    `;
    bindFriendActions(content);
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:#ef4444;padding:24px;">فشل التحميل — <span style="text-decoration:underline;cursor:pointer;" id="retry-friends">حاول مرة أخرى</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:#64748b;">
          <div style="font-size:32px;margin-bottom:8px;opacity:0.5;">${emoji('inbox', '📥', 32)}</div>
          <div>لا توجد طلبات معلقة</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:#64748b;margin-bottom:10px;">${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) || 'لاعب';
        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:#f8fafc;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${name}</div>
              <div style="font-size:11px;color:#64748b;">مستوى ${level} — أرسل لك طلب صداقة</div>
            </div>
            <div class="friend-actions">
              <div class="friend-action" data-accept="${p.id}" title="قبول" style="background:rgba(52,211,153,0.15);border-color:rgba(52,211,153,0.3);color:#34D399;font-weight:700;">✓</div>
              <div class="friend-action" data-reject="${p.id}" title="رفض" style="background:rgba(239,68,68,0.1);border-color:rgba(239,68,68,0.2);color:#EF4444;">✕</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:#34D399;font-weight:600;">✓ تم القبول</span>';
          card.style.borderRight = '3px solid #34D399';
          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:#ef4444;">فشل التحميل</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:#64748b;">
          <div style="font-size:32px;margin-bottom:8px;opacity:0.5;">${emoji('sleeping', '😴', 32)}</div>
          <div style="font-size:14px;margin-bottom:4px;">لا يوجد أصدقاء متصلين الآن</div>
          <div style="font-size:11px;color:#475569;">سيظهرون هنا عند دخولهم</div>
        </div>`;
      return;
    }

    content.innerHTML = `
      <div style="font-size:11px;color:#34D399;margin-bottom:10px;">${friends.length} متصل الآن</div>
      ${friends.map(f => renderFriendCard(f)).join('')}
    `;
    bindFriendActions(content);
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:#ef4444;">فشل التحميل</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:#f8fafc;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${f.display_name || f.username || 'لاعب'}</div>
        <div style="font-size:11px;color:${f.is_online ? '#34D399' : '#64748b'};">${f.is_online ? 'متصل الآن' : 'غير متصل'}${f.level ? ` — مستوى ${f.level}` : ''}</div>
      </div>
      <div class="friend-actions">
        <div class="friend-action" data-chat="${f.id}" title="محادثة" style="background:rgba(37,99,235,0.15);border-color:rgba(37,99,235,0.3);color:#3B82F6;">💬</div>
        ${f.is_online ? `<div class="friend-action" data-invite="${f.id}" title="تحدّي" style="background:rgba(228,172,56,0.15);border-color:rgba(228,172,56,0.3);color:#E4AC38;">${emoji('challenge_swords', '⚔️', 14)}</div>` : ''}
        <div class="friend-action" data-remove="${f.id}" title="إزالة" style="font-size:11px;color:#64748b;">✕</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 || 'صديق';
      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 || 'هذا الصديق';
      const confirmed = await modal.confirm(`إزالة ${name} من الأصدقاء؟`, {
        title: 'إزالة صديق',
        icon: '👋',
        confirmText: 'إزالة',
        cancelText: 'إلغاء',
        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:#1a1a2e;border-radius:16px;padding:24px;width:100%;max-width:320px;text-align:center;">
      <div style="font-size:24px;margin-bottom:8px;">⚔️</div>
      <div style="font-size:16px;font-weight:700;color:#f8fafc;margin-bottom:4px;">تحدّي ${targetName}</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="inv-game 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="inv-game" 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="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:#E4AC38;border:none;color:#1a1a1a;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">1 دقيقة</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 rgba(255,255,255,0.08);color:#94a3b8;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">3 دقائق</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 rgba(255,255,255,0.08);color:#94a3b8;font-size:11px;font-weight:600;cursor:pointer;font-family:inherit;">5 دقائق</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 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="send-invite" style="width:100%;font-size:14px;padding:12px;">أرسل التحدي</button>
      <button id="cancel-invite" 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 = 'bullet_1_0';

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

  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 = '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('#send-invite').addEventListener('click', async () => {
    const sendBtn = dialog.querySelector('#send-invite');
    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;
      }

      audio.play('reward');
      juice.hapticSuccess();
      sendBtn.textContent = '✓ تم إرسال التحدي!';
      sendBtn.style.background = '#34D399';

      // 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 = 'فشل — حاول مرة أخرى';
      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="اسم المستخدم أو الاسم..." 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;">بحث</button>
      </div>
      <div style="font-size:11px;color:#475569;margin-top:4px;">ابحث بأي جزء من الاسم (حرفين على الأقل)</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:#64748b;padding:12px;font-size:12px;">أدخل حرفين على الأقل</div>';
      return;
    }
    const results = content.querySelector('#search-results');
    results.innerHTML = '<div style="text-align:center;color:#64748b;padding:12px;">جاري البحث...</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:#64748b;padding:24px;font-size:13px;">لم يتم العثور على نتائج — جرب اسم آخر</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:#f8fafc;">${p.display_name || p.username || 'لاعب'}</div>
            <div style="font-size:11px;color:#64748b;">${p.is_online ? 'متصل' : 'غير متصل'} — مستوى ${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;">+ أضف</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' ? 'صديق بالفعل' : res.error === 'Request already pending' ? 'مرسل سابقاً' : res.error;
              addBtn.style.background = '#64748b';
              return;
            }
            audio.play('reward');
            juice.hapticLight();
            addBtn.textContent = '✓ تم الإرسال';
            addBtn.style.background = '#34D399';
            addBtn.style.borderColor = '#34D399';
          } catch (e) {
            const msg = e.message || '';
            if (msg.includes('duplicate') || msg.includes('already') || msg.includes('Already')) {
              addBtn.textContent = 'مرسل سابقاً';
              addBtn.style.background = '#64748b';
            } else {
              addBtn.textContent = 'فشل';
              addBtn.disabled = false;
              setTimeout(() => { addBtn.textContent = '+ أضف'; }, 2000);
            }
          }
        });
      });
    } catch (e) {
      results.innerHTML = '<div style="text-align:center;color:#ef4444;">فشل البحث</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:#64748b;">
          <div style="font-size:32px;margin-bottom:8px;opacity:0.5;">${emoji('news', '📰', 32)}</div>
          <div>لا توجد أخبار — العب لتظهر أخبارك هنا</div>
        </div>`;
      return;
    }
    const labels = {
      game_win: 'فاز بمباراة',
      game_loss: 'خسر مباراة',
      game_draw: 'تعادل',
      achievement_unlock: 'حصل على إنجاز',
      level_up: 'ارتقى لمستوى جديد',
      tournament_join: 'انضم لبطولة',
      tournament_win: 'فاز ببطولة',
      friend_add: 'أضاف صديقاً جديداً'
    };
    const icons = {
      game_win: '🏆', game_loss: '💔', game_draw: '🤝',
      achievement_unlock: '🎖️', level_up: '⬆️',
      tournament_join: '🏅', tournament_win: '🥇', friend_add: '👋'
    };
    content.innerHTML = activities.map(a => {
      const actor = a.actor || {};
      const label = labels[a.action] || a.action;
      const icon = icons[a.action] || '📌';
      return `<div style="display:flex;gap:10px;padding:10px;background:#1a1a2e;border-radius:10px;margin-bottom:6px;">
        <div style="width:36px;height:36px;border-radius:50%;background:#2a2a4a;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:#f8fafc;"><strong>${actor.display_name || actor.username || '?'}</strong> ${label}</div>
          ${a.created_at ? `<div style="font-size:10px;color:#475569;margin-top:2px;">${timeAgo(a.created_at)}</div>` : ''}
        </div>
      </div>`;
    }).join('');
  } catch (e) {
    content.innerHTML = `<div style="text-align:center;color:#64748b;padding:32px;">لا توجد أخبار</div>`;
  }
}

function timeAgo(dateStr) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'الآن';
  if (mins < 60) return `منذ ${mins} دقيقة`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `منذ ${hours} ساعة`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `منذ ${days} يوم`;
  return new Date(dateStr).toLocaleDateString('ar');
}
