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);
}

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>',
    shop: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 18c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/></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),
    shop: assetImg('tab_shop', svgFallback.shop, 22, 22),
    profile: assetImg('tab_profile', svgFallback.profile, 22, 22),
  };
  const labels = { rank: 'nav.rank', social: 'nav.social', play: 'nav.play', shop: 'nav.shop', 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;
    scene.switchWorld(world);
  });

  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);
}

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