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, emoji, getColor } from '../../../core/theme.js';
import * as juice from '../../../core/juice.js';

function getGames() {
  const chessPri = getColor('chess_primary', '#2563EB');
  const chessSec = getColor('chess_secondary', '#F5B731');
  const dominoPri = getColor('domino_primary', '#10B981');
  const dominoSec = getColor('domino_secondary', '#06B6D4');
  const ludoPri = getColor('ludo_primary', '#8B5CF6');
  const ludoSec = getColor('ludo_secondary', '#EC4899');
  const bgPri = getColor('backgammon_primary', '#F59E0B');
  const bgSec = getColor('backgammon_secondary', '#EF4444');

  return [
    { key: 'chess', name: 'شطرنج', nameEn: 'Chess', color: chessPri, secondary: chessSec, icon: '♟', gradient: `linear-gradient(135deg, ${chessPri}, ${chessSec})` },
    { key: 'domino', name: 'دومينو', nameEn: 'Domino', color: dominoPri, secondary: dominoSec, icon: '🁣', gradient: `linear-gradient(135deg, ${dominoPri}, ${dominoSec})` },
    { key: 'ludo', name: 'لودو', nameEn: 'Ludo', color: ludoPri, secondary: ludoSec, icon: '🎲', gradient: `linear-gradient(135deg, ${ludoPri}, ${ludoSec})` },
    { key: 'backgammon', name: 'طاولة', nameEn: 'Backgammon', color: bgPri, secondary: bgSec, icon: '◎', gradient: `linear-gradient(135deg, ${bgPri}, ${bgSec})` }
  ];
}

export function mountTable(el) {
  const games = getGames();
  const player = store.get('player');
  const username = player?.display_name || player?.username || 'Player';

  el.innerHTML = `
    <div class="play-home">
      <!-- Player greeting -->
      <div style="width:100%;max-width:340px;margin-bottom:12px;display:flex;align-items:center;justify-content:space-between;">
        <div style="font-size:16px;font-weight:700;color:#f8fafc;">أهلاً ${username} 👋</div>
        <div style="font-size:11px;color:#64748b;">المستوى ${player?.level || 1}</div>
      </div>

      <!-- Quick actions row -->
      <div id="daily-widget" style="display:flex;gap:8px;width:100%;max-width:340px;margin-bottom:16px;">
        <button class="quick-btn" id="btn-challenge-friend">
          <span class="qb-icon" style="background:linear-gradient(135deg,#7c3aed,#a855f7);">${emoji('challenge_swords', '⚔️', 20)}</span>
          <span class="qb-label">تحدّي صديق</span>
        </button>
        <button class="quick-btn" id="btn-achievements">
          <span class="qb-icon" style="background:linear-gradient(135deg,#854d0e,#ca8a04);">${emoji('trophy', '🏆', 20)}</span>
          <span class="qb-label">إنجازات</span>
        </button>
        <button class="quick-btn breathe-glow" id="btn-daily-reward">
          <span class="qb-icon" style="background:linear-gradient(135deg,#92400e,#e4ac38);">${emoji('gift', '🎁', 20)}</span>
          <span class="qb-label">هدية</span>
        </button>
      </div>

      <!-- Games -->
      <div class="games-grid">
        ${games.map(g => {
          const disabled = false;
          return `
          <div class="game-tile ${disabled ? 'game-tile-disabled' : ''}" 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>
              ${disabled ? '<div class="game-tile-soon">قريباً</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: flex-start;
        height: 100%;
        padding: 16px 16px 0;
        overflow-y: auto;
      }
      .quick-btn { display:flex;flex-direction:column;align-items:center;gap:4px;flex:1;background:none;border:none;cursor:pointer;padding:6px;transition:transform 0.1s; }
      .quick-btn:active { transform:scale(0.9); }
      .qb-icon { width:42px;height:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;box-shadow:0 3px 10px rgba(0,0,0,0.3); }
      .qb-label { font-size:10px;font-weight:600;color:#94a3b8; }
      .games-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
        width: 100%;
        max-width: 340px;
      }
      .game-tile {
        position: relative;
        aspect-ratio: 1.1;
        border-radius: 18px;
        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-disabled {
        opacity: 0.4;
        pointer-events: none;
        filter: grayscale(0.5);
      }
      .game-tile-disabled:active { transform: none; }
      .game-tile-soon {
        font-size: 11px;
        font-weight: 700;
        color: rgba(255,255,255,0.7);
        background: rgba(0,0,0,0.3);
        padding: 2px 10px;
        border-radius: 8px;
        margin-top: 2px;
      }
      .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: 28px;
        border-top-right-radius: 28px;
        padding: 28px 20px;
        padding-bottom: calc(28px + 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);
        max-height: 75vh;
      }
      .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 buttons */
      .gm-btn {
        display: flex;
        align-items: center;
        gap: 14px;
        width: 100%;
        padding: 18px 16px;
        background: #1a1a2e;
        border: 1.5px solid rgba(255,255,255,0.06);
        border-radius: 16px;
        cursor: pointer;
        margin-bottom: 10px;
        text-align: right;
        transition: transform 0.1s, border-color 0.2s;
        font-family: inherit;
      }
      .gm-btn:active { transform: scale(0.96); border-color: rgba(255,255,255,0.2); }
      .gm-btn-icon {
        width: 52px;
        height: 52px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 26px;
        flex-shrink: 0;
        box-shadow: 0 3px 10px rgba(0,0,0,0.3);
      }
      .gm-btn-body { flex: 1; }
      .gm-btn-title { font-size: 17px; font-weight: 800; color: #f8fafc; }
      .gm-btn-sub { font-size: 11px; color: #64748b; margin-top: 2px; }
      .gm-btn-arrow { font-size: 22px; color: #475569; font-weight: 300; }
      .gm-chip {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
        padding: 14px 8px;
        background: #1a1a2e;
        border: 1px solid rgba(255,255,255,0.06);
        border-radius: 12px;
        cursor: pointer;
        font-family: inherit;
        color: #e2e8f0;
        font-size: 11px;
        font-weight: 600;
        transition: transform 0.1s, background 0.15s;
      }
      .gm-chip:active { transform: scale(0.93); background: rgba(255,255,255,0.08); }
      .menu-features {
        display: flex;
        gap: 10px;
        margin-top: 12px;
        flex-wrap: wrap;
      }
      .feature-chip {
        padding: 10px 16px;
        border-radius: 10px;
        background: rgba(255,255,255,0.05);
        border: 1px solid rgba(255,255,255,0.08);
        color: #e2e8f0;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: background 0.15s, transform 0.1s;
        min-height: 40px;
        display: flex;
        align-items: center;
      }
      .feature-chip:active { background: rgba(255,255,255,0.1); }
    </style>
  `;

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

  const isGuest = store.get('auth.isGuest');

  // Hide multiplayer quick actions for guests
  if (isGuest) {
    const challengeBtn = el.querySelector('#btn-challenge-friend');
    if (challengeBtn) challengeBtn.style.display = 'none';
  }

  // Daily widget buttons
  el.querySelector('#btn-challenge-friend')?.addEventListener('click', () => {
    audio.play('click');
    scene.push('challenge-friend');
  });
  el.querySelector('#btn-achievements')?.addEventListener('click', () => {
    audio.play('click');
    scene.push('achievements');
  });
  el.querySelector('#btn-daily-reward')?.addEventListener('click', () => {
    audio.play('click');
    scene.push('daily-reward');
  });

  // 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 style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;">
      <div style="display:flex;align-items:center;gap:10px;">
        <div style="width:42px;height:42px;border-radius:12px;background:${game.gradient};display:flex;align-items:center;justify-content:center;font-size:22px;">${game.icon}</div>
        <div style="font-size:22px;font-weight:800;color:#f8fafc;">${game.name}</div>
      </div>
      <button id="menu-close" style="width:36px;height:36px;border-radius:50%;background:rgba(255,255,255,0.06);border:none;color:#94a3b8;font-size:20px;cursor:pointer;display:flex;align-items:center;justify-content:center;">✕</button>
    </div>

    <!-- Main play buttons -->
    <button class="gm-btn" id="btn-single">
      <div class="gm-btn-icon" style="background:${game.gradient};">${emoji('gamepad', '🎮', 26)}</div>
      <div class="gm-btn-body">
        <div class="gm-btn-title">لاعب واحد</div>
        <div class="gm-btn-sub">العب ضد الكمبيوتر</div>
      </div>
      <div class="gm-btn-arrow">›</div>
    </button>

    <button class="gm-btn" id="btn-multi">
      <div class="gm-btn-icon" style="background:linear-gradient(135deg,#dc2626,#f97316);">${emoji('swords', '⚔️', 26)}</div>
      <div class="gm-btn-body">
        <div class="gm-btn-title">أونلاين</div>
        <div class="gm-btn-sub">نافس لاعبين حقيقيين</div>
      </div>
      <div class="gm-btn-arrow">›</div>
    </button>

    <!-- Secondary actions -->
    <div style="display:grid;grid-template-columns:${game.key === 'chess' ? '1fr 1fr 1fr' : '1fr 1fr'};gap:8px;margin-top:14px;">
      <button class="gm-chip" id="btn-leaderboard">
        <span style="font-size:18px;">${emoji('tournament_cup', '🏆', 18)}</span>
        <span>الترتيب</span>
      </button>
      <button class="gm-chip" id="btn-history">
        <span style="font-size:18px;">${emoji('clipboard', '📋', 18)}</span>
        <span>مبارياتي</span>
      </button>
      ${game.key === 'chess' ? `<button class="gm-chip" id="btn-puzzles">
        <span style="font-size:18px;">${emoji('puzzle', '🧩', 18)}</span>
        <span>أحجيات</span>
      </button>` : ''}
    </div>
  `;

  // Staggered entrance for menu buttons
  const menuBtns = menu.querySelectorAll('.gm-btn, .gm-chip');
  menuBtns.forEach((btn, i) => {
    btn.style.opacity = '0';
    btn.style.transform = 'translateY(12px)';
    setTimeout(() => {
      btn.style.transition = 'opacity 0.25s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)';
      btn.style.opacity = '1';
      btn.style.transform = 'translateY(0)';
    }, 80 + i * 60);
  });

  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 if (game.key === 'domino') {
      scene.push('domino-room', { mode: 'bot-pick' });
    } else if (game.key === 'ludo') {
      scene.push('ludo-room', { mode: 'setup', type: 'local' });
    } else if (game.key === 'backgammon') {
      scene.push('backgammon-room', { mode: 'menu' });
    } else {
      const gameScene = game.key + '-game';
      scene.push(gameScene, { mode: 'bot', game: game.key });
    }
  });

  menu.querySelector('#btn-multi').addEventListener('click', () => {
    audio.play('click');
    if (store.get('auth.isGuest')) {
      const toast = document.getElementById('toast-container');
      if (toast) {
        const msg = document.createElement('div');
        msg.style.cssText = 'background:var(--bg-elevated);color:var(--text-primary);padding:12px 20px;border-radius:var(--r-md);font-size:14px;text-align:center;animation:fadeIn 0.2s;';
        msg.textContent = t('guest.upgrade_prompt');
        toast.appendChild(msg);
        setTimeout(() => msg.remove(), 3000);
      }
      return;
    }
    menu.classList.add('hidden');
    if (game.key === 'chess') {
      scene.push('play-time-select', { game: game.key, mode: 'human' });
    } else if (game.key === 'ludo') {
      scene.push('ludo-room', { mode: 'setup', type: 'online' });
    } else if (game.key === 'backgammon') {
      scene.push('backgammon-room', { mode: 'setup', type: 'online' });
    } else {
      scene.push('play-queue', { game: game.key, mode: 'human', timeControl: 'standard' });
    }
  });

  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');
  });
}
