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

const games = [
  { key: 'chess', name: 'شطرنج', nameEn: 'Chess', color: '#2563EB', secondary: '#F5B731', icon: '♟', gradient: 'linear-gradient(135deg, #1e40af, #3b82f6)' },
  { key: 'domino', name: 'دومينو', nameEn: 'Domino', color: '#10B981', secondary: '#06B6D4', icon: '🁣', gradient: 'linear-gradient(135deg, #065f46, #10b981)' },
  { key: 'ludo', name: 'لودو', nameEn: 'Ludo', color: '#8B5CF6', secondary: '#EC4899', icon: '🎲', gradient: 'linear-gradient(135deg, #5b21b6, #8b5cf6)' },
  { key: 'backgammon', name: 'طاولة', nameEn: 'Backgammon', color: '#F59E0B', secondary: '#EF4444', icon: '◎', gradient: 'linear-gradient(135deg, #92400e, #f59e0b)' }
];

export function mountTable(el) {
  el.innerHTML = `
    <div class="play-home">
      <div class="games-grid">
        ${games.map(g => `
          <div class="game-tile" data-game="${g.key}" style="--game-color:${g.color};--game-gradient:${g.gradient};">
            <div class="game-tile-bg" style="background:${g.gradient};"></div>
            <div class="game-tile-content">
              <div class="game-tile-icon">${assetImg(g.key + '_icon', g.icon, 48, 48)}</div>
              <div class="game-tile-name">${g.name}</div>
            </div>
          </div>
        `).join('')}
      </div>
    </div>
    <div id="game-menu" class="game-menu hidden"></div>
    <style>
      .play-home {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        padding: 24px 16px;
      }
      .games-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 14px;
        width: 100%;
        max-width: 340px;
      }
      .game-tile {
        position: relative;
        aspect-ratio: 1;
        border-radius: 20px;
        overflow: hidden;
        cursor: pointer;
        transition: transform 0.15s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.15s;
        box-shadow: 0 4px 16px rgba(0,0,0,0.3);
      }
      .game-tile:active {
        transform: scale(0.93);
        box-shadow: 0 2px 8px rgba(0,0,0,0.4);
      }
      .game-tile-bg {
        position: absolute;
        inset: 0;
        opacity: 0.9;
      }
      .game-tile-content {
        position: relative;
        z-index: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        gap: 8px;
      }
      .game-tile-icon {
        font-size: 42px;
        filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
      }
      .game-tile-name {
        font-size: 16px;
        font-weight: 800;
        color: white;
        text-shadow: 0 1px 3px rgba(0,0,0,0.4);
      }
      .game-menu {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #0f0f1e;
        border-top-left-radius: 24px;
        border-top-right-radius: 24px;
        padding: 24px 20px;
        padding-bottom: calc(24px + var(--tab-height, 60px) + var(--safe-bottom, 0px));
        z-index: 50;
        transform: translateY(0);
        transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
        box-shadow: 0 -8px 40px rgba(0,0,0,0.6);
      }
      .game-menu.hidden {
        transform: translateY(100%);
        pointer-events: none;
      }
      .game-menu-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
      }
      .game-menu-title {
        font-size: 20px;
        font-weight: 800;
        color: #f8fafc;
      }
      .game-menu-close {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: rgba(255,255,255,0.08);
        border: none;
        color: #94a3b8;
        font-size: 18px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .menu-btn {
        display: flex;
        align-items: center;
        gap: 14px;
        width: 100%;
        padding: 16px;
        border-radius: 14px;
        border: none;
        cursor: pointer;
        margin-bottom: 10px;
        transition: transform 0.1s, background 0.15s;
        text-align: right;
      }
      .menu-btn:active { transform: scale(0.97); }
      .menu-btn-primary {
        background: var(--game-gradient, linear-gradient(135deg, #2563eb, #3b82f6));
        color: white;
      }
      .menu-btn-secondary {
        background: rgba(255,255,255,0.05);
        border: 1px solid rgba(255,255,255,0.08);
        color: #f8fafc;
      }
      .menu-btn-icon {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        background: rgba(255,255,255,0.15);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        flex-shrink: 0;
      }
      .menu-btn-text {
        flex: 1;
      }
      .menu-btn-label {
        font-size: 15px;
        font-weight: 700;
      }
      .menu-btn-desc {
        font-size: 11px;
        opacity: 0.7;
        margin-top: 2px;
      }
      .menu-features {
        display: flex;
        gap: 8px;
        margin-top: 6px;
      }
      .feature-chip {
        padding: 6px 12px;
        border-radius: 8px;
        background: rgba(255,255,255,0.05);
        border: 1px solid rgba(255,255,255,0.06);
        color: #94a3b8;
        font-size: 11px;
        font-weight: 600;
        cursor: pointer;
        transition: background 0.15s;
      }
      .feature-chip:active { background: rgba(255,255,255,0.1); }
    </style>
  `;

  const menu = el.querySelector('#game-menu');

  // Juice: staggered bounce-in for tiles + floating idle
  const tiles = el.querySelectorAll('.game-tile');
  juice.stagger(Array.from(tiles), juice.bounceIn, 100, 80);
  setTimeout(() => {
    tiles.forEach((tile, i) => juice.floatY(tile, 4 + i, 2500 + i * 500));
  }, 600);

  tiles.forEach(tile => {
    tile.addEventListener('click', () => {
      audio.play('click');
      juice.hapticMedium();
      juice.pulseElement(tile, tile.style.getPropertyValue('--game-color'));
      const gameKey = tile.dataset.game;
      const game = games.find(g => g.key === gameKey);
      showGameMenu(menu, game);
    });
  });
}

function showGameMenu(menu, game) {
  menu.classList.remove('hidden');
  menu.style.animation = 'slideUpBounce 0.4s cubic-bezier(0.16, 1, 0.3, 1)';
  menu.innerHTML = `
    <div class="game-menu-header">
      <div class="game-menu-title">${game.icon} ${game.name}</div>
      <button class="game-menu-close" id="menu-close">✕</button>
    </div>

    <button class="menu-btn menu-btn-primary" id="btn-single" style="--game-gradient:${game.gradient};">
      <div class="menu-btn-icon">🎮</div>
      <div class="menu-btn-text">
        <div class="menu-btn-label">لاعب واحد</div>
        <div class="menu-btn-desc">العب ضد الكمبيوتر أو محلياً</div>
      </div>
    </button>

    <button class="menu-btn menu-btn-primary" id="btn-multi" style="--game-gradient:${game.gradient};opacity:0.85;">
      <div class="menu-btn-icon">⚔️</div>
      <div class="menu-btn-text">
        <div class="menu-btn-label">متعدد اللاعبين</div>
        <div class="menu-btn-desc">نافس لاعبين حقيقيين أونلاين</div>
      </div>
    </button>

    <div class="menu-features">
      <div class="feature-chip" id="btn-leaderboard">🏆 الترتيب</div>
      <div class="feature-chip" id="btn-history">📋 مبارياتي</div>
      ${game.key === 'chess' ? '<div class="feature-chip" id="btn-puzzles">🧩 أحجيات</div>' : ''}
    </div>
  `;

  menu.querySelector('#menu-close').addEventListener('click', () => {
    audio.play('click');
    menu.classList.add('hidden');
  });

  menu.querySelector('#btn-single').addEventListener('click', () => {
    audio.play('click');
    menu.classList.add('hidden');
    if (game.key === 'chess') {
      scene.push('play-bot-select', { game: game.key });
    } else {
      const gameScene = game.key + '-game';
      scene.push(gameScene, { mode: 'bot', game: game.key });
    }
  });

  menu.querySelector('#btn-multi').addEventListener('click', () => {
    audio.play('click');
    menu.classList.add('hidden');
    scene.push('play-time-select', { game: game.key, mode: 'human' });
  });

  menu.querySelector('#btn-leaderboard')?.addEventListener('click', () => {
    audio.play('click');
    menu.classList.add('hidden');
    bus.emit('navigate', { world: 'rank', scene: 'leaderboard' });
  });

  menu.querySelector('#btn-history')?.addEventListener('click', () => {
    audio.play('click');
    menu.classList.add('hidden');
    scene.push('chess-history');
  });

  menu.querySelector('#btn-puzzles')?.addEventListener('click', () => {
    audio.play('click');
    menu.classList.add('hidden');
    scene.push('puzzles');
  });
}
