import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as net from '../../../core/net.js';
import { t } from '../../../core/i18n.js';

export async function mountBotSelect(el, params) {
  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);">
      <div style="display:flex;align-items:center;gap:var(--s-3);">
        <button class="btn btn-secondary" id="back-btn" style="width:36px;height:36px;padding:0;">←</button>
        <h2 style="font-size:18px;font-weight:700;">${t('play.select_bot')}</h2>
      </div>
      <div id="bots-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:var(--s-3);">
        <div class="skeleton" style="height:120px;"></div>
        <div class="skeleton" style="height:120px;"></div>
        <div class="skeleton" style="height:120px;"></div>
        <div class="skeleton" style="height:120px;"></div>
      </div>
    </div>
  `;

  el.querySelector('#back-btn').addEventListener('click', () => {
    audio.play('click');
    scene.pop();
  });

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

function renderBots(el, bots, params) {
  const grid = el.querySelector('#bots-grid');
  grid.innerHTML = bots.map(bot => `
    <div class="card bot-card" data-id="${bot.id}" style="cursor:pointer;padding:var(--s-3);">
      <div style="width:48px;height:48px;border-radius:var(--r-full);background:var(--bg-elevated);margin:0 auto var(--s-2);display:flex;align-items:center;justify-content:center;font-size:20px;overflow:hidden;">
        ${bot.portrait_url ? `<img src="https://stockfishapi.caprover.al-arcade.com${bot.portrait_url}" style="width:100%;height:100%;object-fit:cover;">` : '♟'}
      </div>
      <div style="text-align:center;">
        <div style="font-size:14px;font-weight:600;">${bot.name_ar || bot.name}</div>
        <div style="font-size:11px;color:var(--text-secondary);">${bot.style_ar || bot.style}</div>
        <div style="font-size:11px;color:var(--gold);margin-top:2px;">${bot.elo_min}-${bot.elo_max}</div>
      </div>
    </div>
  `).join('');

  grid.querySelectorAll('.bot-card').forEach(card => {
    card.addEventListener('click', () => {
      audio.play('click');
      const botId = card.dataset.id;
      scene.push('play-time-select', { ...params, mode: 'bot', botId });
    });
  });
}
