import * as net from '../../../core/net.js';
import { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

export async function mountActivity(el) {
  el.innerHTML = `
    <div style="padding:16px;display:flex;flex-direction:column;gap:12px;">
      <h2 style="font-size:18px;font-weight:700;color:var(--text-primary);">${emoji('news', '📰', 18)} ${t('social.activity_tab')}</h2>
      <div id="activity-list"></div>
    </div>
  `;

  try {
    const data = await net.get('activity.php');
    renderActivity(el, data.activity || []);
  } catch (e) {
    el.querySelector('#activity-list').innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:32px;">${t('social.no_activity_short')}</div>`;
  }
}

function renderActivity(el, activities) {
  const list = el.querySelector('#activity-list');
  if (activities.length === 0) {
    list.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:32px;">${t('social.no_activity_short')}</div>`;
    return;
  }

  const actionLabels = {
    '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'),
    'friend_add': t('social.friend_add')
  };

  list.innerHTML = activities.map(a => {
    const actor = a.actor || {};
    const label = actionLabels[a.action] || a.action;
    const time = timeAgo(a.created_at);

    return `
      <div style="display:flex;gap:10px;padding:10px;background:var(--bg-card);border-radius:10px;">
        <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%;border-radius:50%;object-fit:cover;">` : emoji('person', '👤', 14)}
        </div>
        <div style="flex:1;">
          <div style="font-size:13px;color:var(--text-primary);"><strong>${actor.display_name || actor.username || '?'}</strong> ${label}</div>
          <div style="font-size:10px;color:var(--text-muted);margin-top:2px;">${time}</div>
        </div>
      </div>
    `;
  }).join('');
}

function timeAgo(date) {
  if (!date) return '';
  const diff = Date.now() - new Date(date).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 });
  return t('common.days_ago', { n: Math.floor(hours / 24) });
}
