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

const timeControls = [
  { key: 'bullet_1_0', label: '1+0', category: 'Bullet' },
  { key: 'bullet_2_1', label: '2+1', category: 'Bullet' },
  { key: 'blitz_3_0', label: '3+0', category: 'Blitz' },
  { key: 'blitz_5_0', label: '5+0', category: 'Blitz' },
  { key: 'blitz_5_3', label: '5+3', category: 'Blitz' },
  { key: 'rapid_10_0', label: '10+0', category: 'Rapid' },
  { key: 'rapid_15_10', label: '15+10', category: 'Rapid' },
  { key: 'rapid_30_0', label: '30+0', category: 'Rapid' }
];

export function mountTimeSelect(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_time')}</h2>
      </div>
      <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:var(--s-3);">
        ${timeControls.map(tc => `
          <button class="btn btn-secondary time-btn" data-key="${tc.key}" style="flex-direction:column;height:64px;">
            <span style="font-size:16px;font-weight:700;font-family:var(--font-lat);">${tc.label}</span>
            <span style="font-size:10px;color:var(--text-secondary);">${tc.category}</span>
          </button>
        `).join('')}
      </div>
    </div>
  `;

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

  el.querySelectorAll('.time-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      const timeControl = btn.dataset.key;
      const fullParams = { ...params, timeControl };

      if (params.mode === 'bot' || params.mode === 'local') {
        const gameScene = params.game === 'chess' ? 'chess-game' : params.game + '-game';
        scene.push(gameScene, fullParams);
      } else {
        scene.push('play-queue', fullParams);
      }
    });
  });
}
