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';
import { STOCKFISH_URL } from '../../../core/config.js';

const DIFFICULTY_COLORS = ['var(--success)', 'var(--success)', 'var(--amber)', 'var(--amber)', 'var(--orange)', 'var(--orange)', 'var(--error)'];

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:var(--bot-back-btn-size);height:var(--bot-back-btn-size);padding:0;font-size:var(--bot-back-btn-font);">←</button>
        <h2 style="font-size:var(--bot-title-font);font-weight:700;">${t('play.select_bot')}</h2>
      </div>
      <div id="bots-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:var(--bot-grid-gap);">
        <div class="skeleton" style="height:140px;border-radius:var(--r-xl);"></div>
        <div class="skeleton" style="height:140px;border-radius:var(--r-xl);"></div>
        <div class="skeleton" style="height:140px;border-radius:var(--r-xl);"></div>
        <div class="skeleton" style="height:140px;border-radius:var(--r-xl);"></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, idx) => {
    const diffColor = DIFFICULTY_COLORS[Math.min(idx, DIFFICULTY_COLORS.length - 1)];
    const initial = (bot.name_ar || bot.name || '?')[0];
    return `
    <div class="card bot-card" data-id="${bot.id}" style="cursor:pointer;padding:var(--s-3);position:relative;overflow:hidden;">
      <div style="position:absolute;top:0;left:0;right:0;height:var(--bot-card-accent-height);background:${diffColor};"></div>
      <div style="width:var(--bot-card-avatar-size);height:var(--bot-card-avatar-size);border-radius:var(--r-full);background:var(--bg-elevated);margin:var(--s-2) auto var(--s-2);display:flex;align-items:center;justify-content:center;font-size:20px;overflow:hidden;border:var(--bot-card-avatar-border) solid ${diffColor};">
        ${bot.portrait_url ? `<img src="${STOCKFISH_URL}${bot.portrait_url}" style="width:100%;height:100%;object-fit:cover;" onerror="this.style.display='none';this.parentNode.querySelector('.bot-fallback').style.display='flex'"><span class="bot-fallback" style="display:none;font-size:22px;font-weight:800;color:${diffColor};">${initial}</span>` : `<span style="font-size:22px;font-weight:800;color:${diffColor};">${initial}</span>`}
      </div>
      <div style="text-align:center;">
        <div style="font-size:var(--bot-card-name-font);font-weight:700;">${bot.name_ar || bot.name}</div>
        <div style="font-size:var(--bot-card-sub-font);color:var(--text-secondary);margin-top:2px;">${bot.style_ar || bot.style}</div>
        <div style="font-size:var(--bot-card-sub-font);color:${diffColor};font-weight:600;margin-top:4px;font-family:var(--font-lat);">${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 });
    });
  });
}
