<?php $pageTitle = 'EL3AB - المتجر'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<div class="space-y-6">

  <div class="text-center">
    <h2 style="font-size:22px;font-weight:700;">المتجر</h2>
    <p class="text-muted text-sm">اشتري مظاهر وعناصر</p>
  </div>

  <!-- Balance -->
  <div class="card">
    <div class="card-body" style="display:flex;align-items:center;justify-content:space-around;padding:16px;">
      <div class="text-center">
        <div style="display:flex;align-items:center;gap:6px;justify-content:center;">
          <svg class="icon" style="color:var(--gold)"><use href="/public/icons/sprite.svg#icon-coin"></use></svg>
          <span style="font-size:18px;font-weight:700;" id="shop-coins">0</span>
        </div>
        <p class="text-muted text-xs">عملات</p>
      </div>
      <div class="text-center">
        <div style="display:flex;align-items:center;gap:6px;justify-content:center;">
          <svg class="icon" style="color:var(--purple)"><use href="/public/icons/sprite.svg#icon-gem"></use></svg>
          <span style="font-size:18px;font-weight:700;" id="shop-gems">0</span>
        </div>
        <p class="text-muted text-xs">جواهر</p>
      </div>
    </div>
  </div>

  <!-- Category Tabs -->
  <div class="tab-group" id="shop-tabs">
    <button class="tab active" data-cat="board_theme">رقعة اللعب</button>
    <button class="tab" data-cat="piece_set">طقم القطع</button>
    <button class="tab" data-cat="avatar_frame">إطار الصورة</button>
    <button class="tab" data-cat="trail_effect">تأثيرات الحركة</button>
  </div>

  <!-- Items Grid -->
  <div class="space-y-3" id="shop-items">
    <div class="card"><div class="empty-state">جاري التحميل...</div></div>
  </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', async () => {
  if (!App.isLoggedIn()) {
    window.location.href = '/login';
    return;
  }

  let currentType = 'board_theme';

  document.querySelectorAll('#shop-tabs .tab').forEach(tab => {
    tab.addEventListener('click', () => {
      document.querySelectorAll('#shop-tabs .tab').forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      currentType = tab.dataset.cat;
      loadShopItems(currentType);
    });
  });

  const profileData = await App.fetch('/api/profile');
  if (profileData && profileData.profile) {
    document.getElementById('shop-coins').textContent = (profileData.profile.coins || 0).toLocaleString();
    document.getElementById('shop-gems').textContent = profileData.profile.gems || 0;
  }

  loadShopItems(currentType);
});

async function loadShopItems(type) {
  const data = await App.fetch('/api/shop?type=' + type);
  const container = document.getElementById('shop-items');

  if (!data || !data.items || data.items.length === 0) {
    container.innerHTML = '<div class="card"><div class="empty-state">لا يوجد عناصر في هذا القسم</div></div>';
    return;
  }

  container.innerHTML = data.items.map(item => {
    const owned = item.owned ? ' style="opacity:0.6;"' : '';
    const hasGems = item.price_gems && item.price_gems > 0;
    const hasCoins = item.price_coins && item.price_coins > 0;
    const rarityColors = { common: 'var(--text-muted)', uncommon: 'var(--green)', rare: 'var(--cyan)', epic: 'var(--purple)', legendary: 'var(--gold)' };
    const rarityColor = rarityColors[item.rarity] || 'var(--text-muted)';
    return `
      <div class="card card-hover"${owned}>
        <div class="card-body" style="display:flex;align-items:center;gap:16px;">
          <div class="avatar" style="background:var(--bg-3);border:2px solid ${rarityColor};">
            ${item.preview_url ? `<img src="${item.preview_url}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;" />` : `<svg class="icon-lg" style="color:${rarityColor}"><use href="/public/icons/sprite.svg#icon-star"></use></svg>`}
          </div>
          <div style="flex:1;">
            <p style="font-size:15px;font-weight:600;">${item.name_ar || item.name}</p>
            <p class="text-muted text-xs">${item.description || ''}</p>
            <span class="text-xs" style="color:${rarityColor}">${item.rarity}</span>
          </div>
          ${item.owned ? (item.equipped ? '<span class="badge badge-success">مُجهّز</span>' : `<button class="btn btn-sm btn-outline" onclick="equipItem('${item.id}')">تجهيز</button>`) : `
            <button class="btn btn-sm btn-gold" onclick="buyItem('${item.id}')">
              <svg class="icon-sm" style="color:var(--gold)"><use href="/public/icons/sprite.svg#icon-coin"></use></svg>
              ${item.price_coins || 0}
            </button>
          `}
        </div>
      </div>
    `;
  }).join('');
}

async function buyItem(itemId) {
  const res = await App.fetch('/api/shop', {
    method: 'POST',
    body: JSON.stringify({ action: 'buy', item_id: itemId })
  });
  if (res && res.ok) {
    App.toast('تم الشراء بنجاح!', 'success');
    const profileData = await App.fetch('/api/profile');
    if (profileData && profileData.profile) {
      document.getElementById('shop-coins').textContent = (profileData.profile.coins || 0).toLocaleString();
      document.getElementById('shop-gems').textContent = profileData.profile.gems || 0;
    }
    const active = document.querySelector('#shop-tabs .tab.active');
    loadShopItems(active.dataset.cat);
  } else {
    App.toast(res?.error || 'خطأ في الشراء', 'error');
  }
}

async function equipItem(itemId) {
  const res = await App.fetch('/api/shop', {
    method: 'POST',
    body: JSON.stringify({ action: 'equip', item_id: itemId, equip: true })
  });
  if (res && res.ok) {
    App.toast('تم التجهيز!', 'success');
    const active = document.querySelector('#shop-tabs .tab.active');
    loadShopItems(active.dataset.cat);
  } else {
    App.toast(res?.error || 'خطأ في التجهيز', 'error');
  }
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>
