let allGames = [];
let currentGameAccounts = [];
let activeCategory = 'all';

const CATEGORIES = {
  'tai-khoan': { id: 'tai-khoan', name: 'Tài khoản', type: 'product' },
  'email': { id: 'email', name: 'Email', type: 'product' },
  'clone': { id: 'clone', name: 'Clone', type: 'product' },
  'tools': { id: 'tools', name: 'Tools', type: 'product' },
  'proxy': { id: 'proxy', name: 'Proxy & VPN', type: 'product' },
  'software': { id: 'software', name: 'Phần mềm', type: 'product' },
  'upgrade': { id: 'upgrade', name: 'Nâng cấp tài khoản', type: 'service' },
  'dev': { id: 'dev', name: 'Dịch vụ phần mềm', type: 'service' },
  'auto': { id: 'auto', name: 'Tool/Script Auto', type: 'service' },
  'vps': { id: 'vps', name: 'VPS', type: 'service' },
  'social': { id: 'social', name: 'Tăng tương tác', type: 'service' },
  'seo': { id: 'seo', name: 'Seo', type: 'service' },
  'marketing': { id: 'marketing', name: 'Marketing', type: 'service' },
  'blockchain': { id: 'blockchain', name: 'Blockchain', type: 'service' },
  'khac': { id: 'khac', name: 'Khác', type: 'product' }
};

const GAME_GRADIENTS = {
  'lien-quan': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  'toc-chien': 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  'lmht': 'linear-gradient(135deg, #0c3483 0%, #a2b6df 100%)',
  'dot-kich': 'linear-gradient(135deg, #ff6a00 0%, #ee0979 100%)',
  'free-fire': 'linear-gradient(135deg, #f83600 0%, #f9d423 100%)',
  'valorant': 'linear-gradient(135deg, #ff0844 0%, #ffb199 100%)',
  'roblox': 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
};

const DEFAULT_PLACEHOLDER = 'https://placehold.co/600x800/161a1e/9ca3af?text=SHOP+ACC';

document.addEventListener('DOMContentLoaded', async () => {
  if (document.getElementById('particles-canvas')) initParticles();
  initScrollAnimations();
  await loadGames();
  loadMarquee();
  initCounters();
  updateHeaderBalance();
  checkEmptySections();
  initRouter();
  
  // Search functionality
  const searchInput = document.getElementById('global-search');
  if (searchInput) {
    searchInput.addEventListener('input', (e) => {
      const query = e.target.value.toLowerCase();
      const filtered = allGames.filter(g => 
        g.name.toLowerCase().includes(query) || 
        g.category.toLowerCase().includes(query)
      );
      renderGames(filtered);
    });
  }
});

function initRouter() {
  window.addEventListener('hashchange', handleRoute);
  handleRoute();
}

function handleRoute() {
  const hash = window.location.hash;
  if (hash.startsWith('#game/')) {
    const gameId = hash.split('/')[1];
    const game = allGames.find(g => g.id === gameId);
    if (game) {
      showGameAccountsView(gameId, game.name);
    } else {
      // If games aren't loaded yet, we'll wait for loadGames to finish
      // This is handled by loadGames calling handleRoute after fetching
    }
  } else {
    showHomeView();
  }
}

function showHomeView() {
  const homeView = document.getElementById('home-view');
  const accountView = document.getElementById('account-view');

  if (homeView) homeView.style.display = 'block';
  if (accountView) accountView.style.display = 'none';
  
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

function showGameAccountsView(gameId, gameName) {
  const homeView = document.getElementById('home-view');
  const accountView = document.getElementById('account-view');

  if (homeView) homeView.style.display = 'none';
  if (accountView) accountView.style.display = 'block';

  loadGameAccounts(gameId, gameName);
}

function handleImageError(img) {
  img.onerror = null; // Prevent infinite loop
  img.src = DEFAULT_PLACEHOLDER;
  img.classList.add('img-error');
}

function checkEmptySections() {
  // Hide right sidebar if it's empty (e.g. ad-banner missing)
  const sidebarRight = document.querySelector('.sidebar-right');
  if (sidebarRight && sidebarRight.children.length === 0) {
    sidebarRight.style.display = 'none';
    const mainLayout = document.querySelector('.main-layout');
    if (mainLayout) mainLayout.style.gridTemplateColumns = '1fr';
  }
}

function updateHeaderBalance() {
  const user = JSON.parse(localStorage.getItem('user') || 'null');
  const balanceEl = document.querySelector('.balance-value');
  if (user && balanceEl) {
    balanceEl.textContent = formatMoney(user.balance);
  }
}

async function refreshUserBalance() {
  const token = localStorage.getItem('token');
  if (!token) return;
  try {
    const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
    const data = await res.json();
    if (data.id) {
      localStorage.setItem('user', JSON.stringify(data));
      updateHeaderBalance();
    }
  } catch {}
}

async function loadGames() {
  try {
    const res = await fetch('/api/games');
    allGames = await res.json();
    renderCategoryTabs();
    renderGames(allGames);
    // After loading games, check if we need to navigate to a specific game
    handleRoute();
  } catch (err) {
    const grid = document.getElementById('games-grid');
    if (grid) grid.innerHTML = '<p style="color:var(--danger)">Lỗi tải danh mục game</p>';
  }
}

function renderCategoryTabs() {
  const productCatsEl = document.getElementById('product-categories');
  const serviceCatsEl = document.getElementById('service-categories');
  
  if (!productCatsEl || !serviceCatsEl) return;

  const cats = Object.values(CATEGORIES);
  
  // Only show categories that have at least one game
  const usedCategoryIds = new Set(allGames.map(g => g.category));
  
  const products = cats.filter(c => c.type === 'product' && usedCategoryIds.has(c.id));
  const services = cats.filter(c => c.type === 'service' && usedCategoryIds.has(c.id));
  
  if (products.length > 0 || activeCategory === 'all') {
    productCatsEl.innerHTML = `
      <button class="pill ${activeCategory === 'all' ? 'active' : ''}" onclick="selectCategory('all')">Tất cả</button>
      ${products.map(c => `
        <button class="pill ${c.id === activeCategory ? 'active' : ''}" onclick="selectCategory('${c.id}')">${c.name}</button>
      `).join('')}
    `;
  }

  if (services.length > 0) {
    serviceCatsEl.innerHTML = services.map(c => `
      <button class="pill ${c.id === activeCategory ? 'active' : ''}" onclick="selectCategory('${c.id}')">${c.name}</button>
    `).join('');
  }

  // Hide the entire group if no pills are present
  const productGroup = productCatsEl.closest('.filter-group');
  const serviceGroup = serviceCatsEl.closest('.filter-group');
  
  if (productGroup) productGroup.style.display = (products.length === 0 && activeCategory === 'all') ? 'none' : 'flex';
  if (serviceGroup) serviceGroup.style.display = services.length === 0 ? 'none' : 'flex';
  
  // Hide sections if no data
  const gamesSection = document.getElementById('games');
  if (gamesSection && allGames.length === 0) {
    gamesSection.style.display = 'none';
  }
}

function selectCategory(catId) {
  activeCategory = catId;
  document.querySelectorAll('.pill').forEach(b => b.classList.remove('active'));
  
  // Find the button and add active class
  const buttons = document.querySelectorAll('.pill');
  buttons.forEach(btn => {
    if (btn.innerText.toLowerCase() === (catId === 'all' ? 'tất cả' : CATEGORIES[catId]?.name.toLowerCase())) {
      btn.classList.add('active');
    }
  });

  const filtered = catId === 'all' ? allGames : allGames.filter(g => g.category === catId);
  renderGames(filtered);
}

function getGameGradient(game) {
  if (game.coverGradient) return game.coverGradient;
  return GAME_GRADIENTS[game.id] || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
}

function renderGames(games) {
  const grid = document.getElementById('games-grid');
  if (!games.length) {
    grid.innerHTML = '<div class="empty-state"><i class="fas fa-search"></i><p>Không có sản phẩm nào</p></div>';
    return;
  }
  grid.innerHTML = games.map((g, i) => {
    const imgUrl = g.coverImage || g.image || DEFAULT_PLACEHOLDER;
    const minPrice = g.minPrice ? formatMoney(g.minPrice) : 'Liên hệ';
    
    return `
    <div class="game-card" onclick="window.location.hash = 'game/${g.id}'" style="animation-delay: ${i * 0.05}s">
      <div class="game-card-cover">
        <img src="${imgUrl}" alt="${g.name}" onerror="handleImageError(this)">
        <div class="game-card-badge">HOT</div>
        <div class="game-card-platform">${g.category?.toUpperCase() || 'GAME'}</div>
        <div class="game-card-overlay"></div>
        <div class="game-card-content">
          <h3>${g.name}</h3>
          <div class="game-card-meta">
            <span><i class="fas fa-star"></i> 5.0</span>
            <span>${g.totalSold || 0} Đã bán</span>
            <span class="ad-badge">VIP</span>
          </div>
          <div class="game-card-footer">
            <span class="game-price">${minPrice}+</span>
            <span class="game-stock-badge">Kho: ${g.totalStock || 0}</span>
          </div>
        </div>
      </div>
    </div>`;
  }).join('');
}

async function loadGameAccounts(gameId, gameName) {
  try {
    const res = await fetch(`/api/games/${gameId}/accounts`);
    currentGameAccounts = await res.json();
    const game = allGames.find(g => g.id === gameId);
    const titleEl = document.getElementById('accounts-title');
    if (titleEl) {
      titleEl.innerHTML = `
        <span class="accounts-game-icon">${game?.icon || '🎮'}</span>
        <span>${gameName.toUpperCase()}</span>
      `;
    }
    const backBtn = document.getElementById('accounts-back-btn');
    if (backBtn) backBtn.onclick = () => window.location.hash = '';
    renderFilterTabs(currentGameAccounts);
    renderAccounts(currentGameAccounts, gameId);
  } catch {}
}

function renderFilterTabs(accounts) {
  const tabs = document.getElementById('filter-tabs');
  if (!tabs) return;
  const types = ['all', ...new Set(accounts.map(a => a.type))];
  tabs.innerHTML = types.map((t, i) => {
    let label = t === 'all' ? '🔥 Tất cả' : t.toUpperCase();
    // Special handling for random/selection labels if needed
    if (t.toLowerCase().includes('random')) label = `🎲 ${t.toUpperCase()}`;
    
    return `
    <button class="filter-tab ${i === 0 ? 'active' : ''}" data-type="${t}" onclick="filterAccounts('${t}', this)">
      ${label}
    </button>
  `}).join('');
}

function filterAccounts(type, btn) {
  document.querySelectorAll('.filter-tab').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  const filtered = type === 'all' ? currentGameAccounts : currentGameAccounts.filter(a => a.type === type);
  const gameId = currentGameAccounts[0]?.gameId;
  renderAccounts(filtered, gameId);
}

function getAccountGradient(account) {
  const game = allGames.find(g => g.id === account.gameId);
  return getGameGradient(game || {});
}

function renderAccounts(accounts, gameId) {
  const grid = document.getElementById('accounts-grid');
  if (!grid) return;
  if (!accounts.length) { grid.innerHTML = '<div class="empty-state"><i class="fas fa-search"></i><p>Không có tài khoản nào</p></div>'; return; }
  grid.innerHTML = accounts.map((a, i) => {
    const gradient = getAccountGradient(a);
    const accImg = a.coverImage || a.image || DEFAULT_PLACEHOLDER;
    const bgStyle = accImg
      ? `background-image: url('${accImg}'); background-size: cover; background-position: center;`
      : `background: ${gradient};`;
    
    // Handle image error in background style is tricky, so we'll use an actual img tag for the cover
    return `
    <div class="account-card vip-acc-card" style="--card-gradient: ${gradient}; animation-delay: ${i * 0.08}s">
      <div class="account-card-cover">
        <img src="${accImg}" alt="${a.title}" onerror="handleImageError(this)" style="width:100%; height:100%; object-fit:cover;">
        <div class="account-cover-overlay"></div>
        <span class="account-card-badge">${a.type.toUpperCase()}</span>
        <div class="account-cover-price">${formatMoney(a.price)}</div>
      </div>
      <div class="account-card-body">
        <h3>${a.title}</h3>
        <p>${a.description}</p>
        ${a.info ? `<div class="account-card-info"><i class="fas fa-info-circle"></i> ${a.info}</div>` : ''}
      <div class="account-card-footer">
        <span class="account-stock ${a.stock <= 0 ? 'out' : ''}">${a.stock <= 0 ? '<i class="fas fa-times-circle"></i> Hết hàng' : '<i class="fas fa-check-circle"></i> Còn ' + a.stock + ' acc'}</span>
        <span class="account-sold"><i class="fas fa-shopping-basket"></i> ${a.sold} đã bán</span>
      </div>
        <button class="btn-buy btn-buy-vip" onclick="showAccountDetail('${a.id}')" ${a.stock <= 0 ? 'disabled' : ''}>${a.stock <= 0 ? 'Hết hàng' : '<i class="fas fa-shopping-cart"></i> Mua ngay'}</button>
      </div>
    </div>`;
  }).join('');
}

function showAccountDetail(id) {
  const acc = currentGameAccounts.find(a => a.id === id);
  if (!acc) return;
  const detailImg = acc.coverImage || acc.image || DEFAULT_PLACEHOLDER;
  const modal = document.getElementById('account-modal');
  const body = document.getElementById('modal-body');
  if (!modal || !body) return;
  body.innerHTML = `
    <div class="modal-cover">
      <img src="${detailImg}" onerror="handleImageError(this)">
      <div class="modal-cover-overlay"></div>
      <div class="modal-watermark">SHOP ACC</div>
      <div class="modal-cover-content">
        <span class="modal-badge">${acc.type.toUpperCase()}</span>
        <h2>${acc.title}</h2>
      </div>
    </div>
    <div class="modal-details">
      <div class="detail-row">
        <span class="detail-label"><i class="fas fa-tag"></i> Giá</span>
        <span class="detail-value price">${formatMoney(acc.price)}</span>
      </div>
      <div class="detail-row">
        <span class="detail-label"><i class="fas fa-check-circle" style="color:#10b981"></i> Còn lại</span>
        <span class="detail-value" style="color:#10b981">${acc.stock} acc</span>
      </div>
      <div class="detail-row">
        <span class="detail-label"><i class="fas fa-shopping-basket" style="color:var(--text-secondary)"></i> Đã bán</span>
        <span class="detail-value">${acc.sold}</span>
      </div>
      ${acc.info ? `<div class="detail-info"><i class="fas fa-star" style="color:#fbbf24"></i> ${acc.info}</div>` : ''}
      <p class="detail-desc">${acc.description}</p>
      <button class="btn btn-primary btn-block btn-ripple btn-lg" onclick="purchaseAccount('${acc.id}')">
        <i class="fas fa-shopping-cart"></i> Mua ngay - ${formatMoney(acc.price)}
      </button>
    </div>
  `;
  modal.style.display = 'flex';
}

function showModal(title, message, type = 'info') {
  const modal = document.getElementById('purchase-modal');
  const body = document.getElementById('purchase-modal-body');
  const iconClass = type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle';
  
  body.innerHTML = `
    <div class="purchase-modal-content">
      <div class="purchase-modal-icon ${type}"><i class="fas ${iconClass}"></i></div>
      <h2 class="modal-title">${title}</h2>
      <p class="modal-desc">${message}</p>
      <div class="modal-actions">
        <button class="btn btn-primary btn-block btn-lg" onclick="closePurchaseModal()">Đóng</button>
      </div>
    </div>
  `;
  modal.style.display = 'flex';
}

async function purchaseAccount(accountId) {
  const token = localStorage.getItem('token');
  const user = JSON.parse(localStorage.getItem('user') || 'null');
  if (!token || !user) {
    closeModal();
    window.location.href = '/login.html';
    return;
  }
  try {
    const res = await fetch('/api/order/create', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
      body: JSON.stringify({ accountId })
    });
    const data = await res.json();
    if (!res.ok) {
      if (data.error.includes('So du')) {
        closeModal();
        showPurchaseModal(data.error);
      } else {
        showModal('Thông báo', data.error, 'error');
      }
      return;
    }
    closeModal();
    showPurchaseSuccess(data.order);
    await refreshUserBalance();
    loadGameAccounts(currentGameAccounts[0]?.gameId, document.getElementById('accounts-title').textContent);
  } catch { showModal('Lỗi', 'Lỗi kết nối máy chủ', 'error'); }
}

function showPurchaseModal(error) {
  const modal = document.getElementById('purchase-modal');
  const body = document.getElementById('purchase-modal-body');
  body.innerHTML = `
    <div class="purchase-modal-content">
      <div class="purchase-modal-icon error"><i class="fas fa-exclamation-circle"></i></div>
      <h2 class="modal-title">Số dư không đủ</h2>
      <p class="modal-desc">Số dư của bạn không đủ để thực hiện giao dịch này. Vui lòng nạp thêm tiền.</p>
      <div class="modal-actions">
        <a href="/charge.html" class="btn btn-primary btn-block btn-lg">
          <i class="fas fa-wallet"></i> Nạp tiền ngay
        </a>
      </div>
    </div>
  `;
  modal.style.display = 'flex';
}

function showPurchaseSuccess(order) {
  const modal = document.getElementById('purchase-modal');
  const body = document.getElementById('purchase-modal-body');
  body.innerHTML = `
    <div class="purchase-modal-content">
      <div class="purchase-modal-icon success"><i class="fas fa-check-circle"></i></div>
      <h2 class="modal-title">Mua hàng thành công!</h2>
      <p class="modal-desc">Cảm ơn bạn đã tin tưởng. Thông tin tài khoản của bạn:</p>
      
      <div class="acc-credentials">
        <div class="cred-row">
          <span class="label">Tài khoản</span>
          <div class="value-box">
            <code>${order.gameUsername}</code>
            <button class="copy-mini" onclick="copyText('${order.gameUsername}', this)"><i class="far fa-copy"></i></button>
          </div>
        </div>
        <div class="cred-row">
          <span class="label">Mật khẩu</span>
          <div class="value-box">
            <code>${order.gamePassword}</code>
            <button class="copy-mini" onclick="copyText('${order.gamePassword}', this)"><i class="far fa-copy"></i></button>
          </div>
        </div>
      </div>
      
      <div class="modal-note">
        <i class="fas fa-info-circle"></i> Vui lòng đổi mật khẩu ngay sau khi nhận tài khoản. Bảo hành 24h.
      </div>
      
      <div class="modal-actions">
        <button class="btn btn-primary btn-block btn-lg" onclick="closePurchaseModal()">
          Xong
        </button>
      </div>
    </div>
  `;
  modal.style.display = 'flex';
}

function copyText(text, btn) {
  navigator.clipboard.writeText(text);
  const icon = btn.querySelector('i');
  icon.className = 'fas fa-check';
  setTimeout(() => { icon.className = 'far fa-copy'; }, 2000);
}

function closeModal() { document.getElementById('account-modal').style.display = 'none'; }
function closePurchaseModal() { document.getElementById('purchase-modal').style.display = 'none'; }

document.getElementById('account-modal').addEventListener('click', (e) => { if (e.target === e.currentTarget) closeModal(); });
document.getElementById('purchase-modal').addEventListener('click', (e) => { if (e.target === e.currentTarget) closePurchaseModal(); });

function loadMarquee() {
  const el = document.getElementById('marquee-content');
  if (!el) return;
  const messages = [
    'use*** đã mua acc Liên Quân 50K',
    'pla*** đã nạp 100,000đ',
    'gam*** đã mua acc Free Fire',
    'pro*** đã mua acc Valorant',
    'new*** đã nạp 50,000đ',
    'vip*** đã mua acc Roblox 50K',
    'boy*** đã mua acc Đột Kích 30K',
    'hot*** đã nạp 200,000đ'
  ];
  if (messages.length === 0) {
    el.closest('.marquee-container').style.display = 'none';
    return;
  }
  const doubled = [...messages, ...messages];
  el.innerHTML = doubled.map(m => `<span><i class="fas fa-check-circle"></i> ${m}</span>`).join('');
}

function initCounters() {
  const counters = document.querySelectorAll('.stat-number');
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const el = entry.target;
        const target = parseInt(el.dataset.target);
        animateCounter(el, target);
        observer.unobserve(el);
      }
    });
  }, { threshold: 0.5 });
  counters.forEach(c => observer.observe(c));
}

function animateCounter(el, target) {
  let current = 0;
  const step = target / 60;
  const interval = setInterval(() => {
    current += step;
    if (current >= target) { current = target; clearInterval(interval); }
    el.textContent = Math.floor(current);
  }, 16);
}

function initScrollAnimations() {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) entry.target.classList.add('visible');
    });
  }, { threshold: 0.1 });
  document.querySelectorAll('.animate-on-scroll').forEach(el => observer.observe(el));
}

function initParticles() {
  const canvas = document.getElementById('particles-canvas');
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  let particles = [];
  function resize() { canvas.width = canvas.offsetWidth; canvas.height = canvas.offsetHeight; }
  resize(); window.addEventListener('resize', resize);

  class Particle {
    constructor() { this.reset(); }
    reset() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;
      this.size = Math.random() * 2 + 0.5;
      this.speedX = (Math.random() - 0.5) * 0.5;
      this.speedY = (Math.random() - 0.5) * 0.5;
      this.opacity = Math.random() * 0.5 + 0.1;
    }
    update() {
      this.x += this.speedX; this.y += this.speedY;
      if (this.x < 0 || this.x > canvas.width || this.y < 0 || this.y > canvas.height) this.reset();
    }
    draw() {
      ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(99, 102, 241, ${this.opacity})`; ctx.fill();
    }
  }

  for (let i = 0; i < 80; i++) particles.push(new Particle());

  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    particles.forEach(p => { p.update(); p.draw(); });
    particles.forEach((a, i) => {
      particles.slice(i + 1).forEach(b => {
        const dist = Math.hypot(a.x - b.x, a.y - b.y);
        if (dist < 120) {
          ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y);
          ctx.strokeStyle = `rgba(99, 102, 241, ${0.1 * (1 - dist / 120)})`;
          ctx.lineWidth = 0.5; ctx.stroke();
        }
      });
    });
    requestAnimationFrame(animate);
  }
  animate();
}