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

const RARITY_COLORS = { common: 'var(--text-secondary)', uncommon: 'var(--success)', rare: 'var(--blue)', epic: 'var(--purple)', legendary: 'var(--gold)' };

export async function mountBrowse(el) {
  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <h2 style="font-size:20px;font-weight:700;">${t('shop.title')}</h2>
      <div id="shop-grid" style="display:grid;grid-template-columns:repeat(2,1fr);gap:var(--s-3);">
        <div class="skeleton" style="height:140px;"></div>
        <div class="skeleton" style="height:140px;"></div>
        <div class="skeleton" style="height:140px;"></div>
        <div class="skeleton" style="height:140px;"></div>
      </div>
    </div>
  `;

  try {
    const data = await net.get('shop.php', { action: 'list' });
    renderItems(el, data.items || data || []);
  } catch (e) {
    el.querySelector('#shop-grid').innerHTML = `<p style="color:var(--text-secondary);text-align:center;grid-column:1/-1;">${t('common.empty')}</p>`;
  }
}

function renderItems(el, items) {
  const grid = el.querySelector('#shop-grid');
  if (items.length === 0) {
    grid.innerHTML = `<p style="color:var(--text-secondary);text-align:center;grid-column:1/-1;">${t('common.empty')}</p>`;
    return;
  }

  grid.innerHTML = items.map(item => `
    <div class="card shop-item" data-id="${item.id}" style="cursor:pointer;padding:var(--s-3);border-color:${RARITY_COLORS[item.rarity] || 'var(--border)'}33;${item.owned ? 'opacity:0.7;' : ''}position:relative;">
      ${item.owned ? `<div style="position:absolute;top:6px;right:6px;background:var(--success);color:#fff;font-size:9px;font-weight:700;padding:2px 6px;border-radius:4px;">Owned</div>` : ''}
      <div style="height:60px;background:var(--bg-elevated);border-radius:var(--r-sm);margin-bottom:var(--s-2);display:flex;align-items:center;justify-content:center;font-size:24px;">
        ${emoji('art', '🎨', 24)}
      </div>
      <div style="font-size:13px;font-weight:600;margin-bottom:2px;">${item.name || item.id}</div>
      <div style="font-size:10px;color:${RARITY_COLORS[item.rarity] || 'var(--text-muted)'};margin-bottom:var(--s-1);">${item.rarity || 'common'}</div>
      <div style="font-size:12px;font-weight:700;color:var(--gold);">
        ${item.owned ? '' : (item.price_coins ? `${item.price_coins} ${emoji('coin', '🪙', 14)}` : '') + (item.price_gems ? ` ${item.price_gems} ${emoji('gem', '💎', 14)}` : '')}
      </div>
    </div>
  `).join('');

  grid.querySelectorAll('.shop-item').forEach(card => {
    card.addEventListener('click', () => {
      audio.play('click');
      const id = card.dataset.id;
      const item = items.find(i => i.id === id);
      if (item && !item.owned) purchasePrompt(el, item);
    });
  });
}

async function purchasePrompt(el, item) {
  const player = store.get('player');
  const canAffordCoins = (player?.coins || 0) >= (item.price_coins || 0);
  const canAffordGems = (item.price_gems || 0) === 0 || (player?.gems || 0) >= (item.price_gems || 0);
  const canAfford = canAffordCoins && canAffordGems;

  const overlay = document.getElementById('overlay');
  overlay.classList.add('active');
  overlay.innerHTML = `
    <div class="card" style="max-width:300px;width:90%;padding:var(--s-6);text-align:center;">
      <div style="font-size:18px;font-weight:700;margin-bottom:var(--s-2);">${item.name || item.id}</div>
      <div style="font-size:14px;color:var(--gold);margin-bottom:var(--s-4);">${item.price_coins || 0} ${emoji('coin', '🪙', 16)}</div>
      ${canAfford
        ? `<button class="btn btn-primary w-full" id="buy-btn">${t('common.confirm')}</button>`
        : `<p style="color:var(--error);font-size:13px;">رصيد غير كافي</p>`
      }
      <button class="btn btn-secondary w-full" id="cancel-buy" style="margin-top:var(--s-2);">${t('common.cancel')}</button>
    </div>
  `;

  overlay.querySelector('#cancel-buy').addEventListener('click', () => {
    overlay.classList.remove('active');
    overlay.innerHTML = '';
  });

  if (canAfford) {
    overlay.querySelector('#buy-btn').addEventListener('click', async () => {
      try {
        await net.post('shop.php', { action: 'purchase', cosmetic_id: item.id });
        audio.play('coin', 'reward');
        store.set('player.coins', (player.coins || 0) - (item.price_coins || 0));
        overlay.innerHTML = `<div class="card" style="padding:var(--s-6);text-align:center;"><div style="font-size:36px;margin-bottom:var(--s-2);">${emoji('checkmark', '✅', 36)}</div><div>تم الشراء!</div></div>`;
        setTimeout(() => { overlay.classList.remove('active'); overlay.innerHTML = ''; }, 1500);
      } catch (e) {
        overlay.innerHTML = `<div class="card" style="padding:var(--s-6);text-align:center;color:var(--error);">${t('common.error')}</div>`;
        setTimeout(() => { overlay.classList.remove('active'); overlay.innerHTML = ''; }, 1500);
      }
    });
  }
}
