// Reusable Player Panel Component
// Used by Chess, Ludo, Domino — consistent player display across all games

import * as audio from './audio.js';
import * as mp from './multiplayer.js';
import { getTier } from '../modules/rewards/scenes/ranks.js';
import { emoji } from './theme.js';
import { t } from './i18n.js';

export function render(container, player, options = {}) {
  const { position = 'top', isActive = false, showRating = true, showLevel = true, isSelf = false } = options;

  const tier = showRating ? getTier(player.rating || player.elo_rapid || 1200) : null;

  const panel = document.createElement('div');
  panel.className = `player-panel ${isActive ? 'active' : ''} ${position}`;
  panel.dataset.playerId = player.id || '';
  panel.innerHTML = `
    <div class="pp-avatar">
      ${player.avatar_url
        ? `<img src="${player.avatar_url}" alt="">`
        : `<span class="pp-avatar-fallback">${isSelf ? emoji('person', '👤', 16) : emoji('gamepad', '🎮', 16)}</span>`
      }
      <div class="pp-status-dot ${player.isOnline !== false ? 'online' : ''}"></div>
    </div>
    <div class="pp-info">
      <div class="pp-name">${player.display_name || player.username || (isSelf ? t('common.you') : t('common.opponent'))}</div>
      <div class="pp-meta">
        ${showLevel ? `<span class="pp-level">Lv.${player.level || 1}</span>` : ''}
        ${tier ? `<span class="pp-tier" style="color:${tier.color};">${tier.icon}</span>` : ''}
        ${showRating ? `<span class="pp-rating">${player.rating || player.elo_rapid || 1200}</span>` : ''}
      </div>
    </div>
    ${isActive ? '<div class="pp-turn-indicator"></div>' : ''}
  `;

  // Tap to inspect opponent (not self)
  if (!isSelf && player.id) {
    panel.style.cursor = 'pointer';
    panel.addEventListener('click', () => {
      audio.play('click');
      mp.fetchOpponentProfile(player.id).then(profile => {
        if (profile && !profile.error) {
          showPlayerPopup(container, profile);
        }
      });
    });
  }

  container.appendChild(panel);
  return panel;
}

export function setActive(panel, active) {
  if (!panel) return;
  panel.classList.toggle('active', active);
  const indicator = panel.querySelector('.pp-turn-indicator');
  if (active && !indicator) {
    const dot = document.createElement('div');
    dot.className = 'pp-turn-indicator';
    panel.appendChild(dot);
  } else if (!active && indicator) {
    indicator.remove();
  }
}

export function setConnectionStatus(panel, status) {
  if (!panel) return;
  const dot = panel.querySelector('.pp-status-dot');
  if (!dot) return;
  dot.className = 'pp-status-dot ' + status; // 'online', 'weak', 'offline'
}

function showPlayerPopup(container, profile) {
  const existing = document.getElementById('pp-popup');
  if (existing) { existing.remove(); return; }

  const popup = document.createElement('div');
  popup.id = 'pp-popup';
  popup.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:var(--bg-card);border:1px solid rgba(255,255,255,0.1);border-radius:16px;padding:20px;z-index:200;box-shadow:0 12px 40px rgba(0,0,0,0.7);text-align:center;min-width:220px;';
  popup.innerHTML = `
    <div style="width:56px;height:56px;border-radius:50%;background:var(--bg-hover);margin:0 auto 10px;display:flex;align-items:center;justify-content:center;font-size:26px;overflow:hidden;">
      ${profile.avatar_url ? `<img src="${profile.avatar_url}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 26)}
    </div>
    <div style="font-size:16px;font-weight:700;color:var(--text-primary);">${profile.display_name || profile.username}</div>
    <div style="font-size:12px;color:var(--text-muted);margin:4px 0 16px;">Level ${profile.level || 1} · ${profile.elo_rapid || 1200} ELO</div>
    <div style="display:flex;gap:8px;justify-content:center;">
      <button id="pp-add" style="padding:8px 18px;background:var(--chess-primary);border:none;border-radius:8px;color:#fff;font-size:12px;font-weight:600;cursor:pointer;">${t('social.add_btn')}</button>
      <button id="pp-close" style="padding:8px 18px;background:var(--border);border:1px solid rgba(255,255,255,0.08);border-radius:8px;color:var(--text-secondary);font-size:12px;cursor:pointer;">${t('common.close')}</button>
    </div>
  `;
  document.body.appendChild(popup);

  popup.querySelector('#pp-close').addEventListener('click', () => popup.remove());
  popup.querySelector('#pp-add').addEventListener('click', async () => {
    const success = await mp.addFriendFromGame(profile.id);
    if (success) {
      popup.querySelector('#pp-add').textContent = t('common.done');
      popup.querySelector('#pp-add').style.background = 'var(--success)';
    }
    setTimeout(() => popup.remove(), 1000);
  });

  setTimeout(() => {
    const handler = (e) => { if (!popup.contains(e.target)) { popup.remove(); document.removeEventListener('click', handler); } };
    document.addEventListener('click', handler);
  }, 200);
}

// CSS for player panels (inject once)
export function injectStyles() {
  if (document.getElementById('pp-styles')) return;
  const style = document.createElement('style');
  style.id = 'pp-styles';
  style.textContent = `
    .player-panel { display:flex;align-items:center;gap:10px;padding:8px 12px;border-radius:10px;border:2px solid transparent;transition:all 0.3s; }
    .player-panel.active { border-color:var(--gold);background:rgba(228,172,56,0.05); }
    .pp-avatar { position:relative;width:36px;height:36px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;overflow:visible; }
    .pp-avatar img { width:100%;height:100%;object-fit:cover;border-radius:50%; }
    .pp-avatar-fallback { font-size:16px; }
    .pp-status-dot { position:absolute;bottom:-1px;right:-1px;width:10px;height:10px;border-radius:50%;border:2px solid var(--bg-panel);background:var(--text-muted); }
    .pp-status-dot.online { background:var(--success); }
    .pp-status-dot.weak { background:var(--amber); }
    .pp-status-dot.offline { background:var(--error); }
    .pp-info { flex:1; }
    .pp-name { font-size:13px;font-weight:600;color:var(--text-primary); }
    .pp-meta { display:flex;gap:6px;align-items:center;margin-top:2px; }
    .pp-level { font-size:10px;color:var(--text-muted); }
    .pp-tier { font-size:12px; }
    .pp-rating { font-size:11px;color:var(--text-secondary);font-family:Inter,monospace; }
    .pp-turn-indicator { width:8px;height:8px;border-radius:50%;background:var(--gold);animation:pulse 1s ease-in-out infinite; }
  `;
  document.head.appendChild(style);
}
