import * as store from './store.js';
import * as bus from './bus.js';
import * as scene from './scene.js';
import { t } from './i18n.js';
import { emoji, assetImg } from './theme.js';

let hudEl, tabBar;

export function init() {
  hudEl = document.getElementById('hud');
  renderHud();
  renderTabBar();

  bus.on('store:player', updateHud);
  bus.on('store:notifications.unreadCount', updateBell);
  bus.on('world:changed', updateTabs);
  bus.on('gamemode:enter', () => {
    hudEl.classList.add('hidden');
    tabBar.classList.add('hidden');
  });
  bus.on('gamemode:exit', () => {
    hudEl.classList.remove('hidden');
    tabBar.classList.remove('hidden');
  });
  bus.on('coins:earned', animateCoins);
  bus.on('xp:earned', animateXp);
  bus.on('tournament:pending-updated', updateTournamentBadge);
  bus.on('tournament:paired', () => updateTournamentBadge([1]));
}

function renderHud() {
  const player = store.get('player');
  const avatarContent = player?.avatar_url
    ? `<img src="${player.avatar_url}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">`
    : `<span style="font-size:16px;color:var(--text-secondary);">${emoji('person', '👤', 16)}</span>`;
  const level = player?.level || 1;

  hudEl.innerHTML = `
    <div class="hud-profile" id="hud-profile">
      <div class="hud-avatar">${avatarContent}</div>
      <div class="hud-level-badge">${level}</div>
    </div>
    <div class="hud-stats">
      <div class="hud-stat hud-coins">
        <span class="icon">${emoji('hud_coin', '●', 16)}</span>
        <span id="hud-coins">${formatNum(player?.coins || 0)}</span>
      </div>
      <div class="hud-stat hud-gems">
        <span class="icon">${emoji('hud_gem', '◆', 16)}</span>
        <span id="hud-gems">${formatNum(player?.gems || 0)}</span>
      </div>
    </div>
    <div class="hud-actions">
      <div class="hud-btn" id="hud-notif">
        ${emoji('bell', '🔔', 18)}
        <div class="hud-badge" id="hud-badge"></div>
      </div>
    </div>
  `;

  document.getElementById('hud-profile')?.addEventListener('click', () => {
    bus.emit('navigate', { world: 'profile' });
  });
  document.getElementById('hud-notif')?.addEventListener('click', () => {
    bus.emit('navigate', { world: 'social', scene: 'notifications' });
  });
}

function renderTabBar() {
  tabBar = document.createElement('div');
  tabBar.className = 'tab-bar';
  const worlds = scene.getWorlds();
  const svgFallback = {
    rank: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 7h7l-5.5 4.5 2 7L12 16l-6.5 4.5 2-7L2 9h7z"/></svg>',
    social: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M16 11c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3zm-8 0c1.66 0 3-1.34 3-3S9.66 5 8 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>',
    play: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>',
    tournaments: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 5h-2V3H7v2H5c-1.1 0-2 .9-2 2v1c0 2.55 1.92 4.63 4.39 4.94.63 1.5 1.98 2.63 3.61 2.96V19H7v2h10v-2h-4v-3.1c1.63-.33 2.98-1.46 3.61-2.96C19.08 12.63 21 10.55 21 8V7c0-1.1-.9-2-2-2zM5 8V7h2v3.82C5.84 10.4 5 9.3 5 8zm14 0c0 1.3-.84 2.4-2 2.82V7h2v1z"/></svg>',
    profile: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>'
  };
  const icons = {
    rank: assetImg('tab_rank', svgFallback.rank, 22, 22),
    social: assetImg('tab_social', svgFallback.social, 22, 22),
    play: assetImg('tab_play', svgFallback.play, 22, 22),
    tournaments: assetImg('tab_tournaments', svgFallback.tournaments, 22, 22),
    profile: assetImg('tab_profile', svgFallback.profile, 22, 22),
  };
  const labels = { rank: 'nav.rank', social: 'nav.social', play: 'nav.play', tournaments: 'nav.tournaments', profile: 'nav.profile' };
  const current = scene.getCurrentWorld();

  tabBar.innerHTML = worlds.map(w => `
    <div class="tab-item ${w === current ? 'active' : ''}" data-world="${w}">
      <div class="tab-icon">${icons[w]}</div>
      <span>${t(labels[w])}</span>
    </div>
  `).join('');

  tabBar.addEventListener('click', (e) => {
    const item = e.target.closest('.tab-item');
    if (!item) return;
    const world = item.dataset.world;
    const isAlreadyActive = item.classList.contains('active');
    scene.switchWorld(world, isAlreadyActive);
  });

  document.body.appendChild(tabBar);
}

function updateTabs({ to }) {
  tabBar.querySelectorAll('.tab-item').forEach(el => {
    el.classList.toggle('active', el.dataset.world === to);
  });
}

function updateHud() {
  const player = store.get('player');
  if (!player) return;
  const coins = document.getElementById('hud-coins');
  const gems = document.getElementById('hud-gems');
  if (coins) coins.textContent = formatNum(player.coins || 0);
  if (gems) gems.textContent = formatNum(player.gems || 0);

  const levelBadge = hudEl.querySelector('.hud-level-badge');
  if (levelBadge) levelBadge.textContent = player.level || 1;

  const avatarEl = hudEl.querySelector('.hud-avatar');
  if (avatarEl && player.avatar_url) {
    avatarEl.innerHTML = `<img src="${player.avatar_url}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">`;
  }
}

function updateBell(count) {
  const badge = document.getElementById('hud-badge');
  if (badge) badge.textContent = count > 0 ? (count > 99 ? '99+' : count) : '';
}

function animateCoins({ amount }) {
  const el = document.getElementById('hud-coins');
  if (el) el.classList.add('pulse');
  setTimeout(() => el?.classList.remove('pulse'), 1000);
  updateHud();
}

function animateXp() {
  updateHud();
}

function formatNum(n) {
  if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
  if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
  return String(n);
}

function updateTournamentBadge(pending) {
  const tourTab = tabBar?.querySelector('[data-world="tournaments"]');
  if (!tourTab) return;
  let badge = tourTab.querySelector('.tour-badge');
  const count = Array.isArray(pending) ? pending.length : 0;
  if (count > 0) {
    if (!badge) {
      badge = document.createElement('div');
      badge.className = 'tour-badge';
      badge.style.cssText = 'position:absolute;top:2px;right:8px;width:8px;height:8px;background:#E4AC38;border-radius:50%;';
      tourTab.style.position = 'relative';
      tourTab.appendChild(badge);
    }
  } else if (badge) {
    badge.remove();
  }
}

export function show() { hudEl?.classList.remove('hidden'); tabBar?.classList.remove('hidden'); }
export function hide() { hudEl?.classList.add('hidden'); tabBar?.classList.add('hidden'); }
