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: t('game.chess'), nameEn: 'Chess', color: chessPri, secondary: chessSec, icon: '♟', gradient: `linear-gradient(135deg, ${chessPri}, ${chessSec})` },
    { key: 'domino', name: t('game.domino'), nameEn: 'Domino', color: dominoPri, secondary: dominoSec, icon: '🁣', gradient: `linear-gradient(135deg, ${dominoPri}, ${dominoSec})` },
    { key: 'ludo', name: t('game.ludo'), nameEn: 'Ludo', color: ludoPri, secondary: ludoSec, icon: '🎲', gradient: `linear-gradient(135deg, ${ludoPri}, ${ludoSec})` },
    { key: 'backgammon', name: t('game.backgammon'), 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:var(--home-max-width);margin-bottom:var(--home-greeting-margin);display:flex;align-items:center;justify-content:space-between;">
        <div style="font-size:var(--home-greeting-font);font-weight:700;color:var(--text-primary);">${username} ${emoji('wave', '👋', 18)}</div>
        <div style="font-size:var(--gm-btn-sub-font);color:var(--text-muted);">Lv. ${player?.level || 1}</div>
      </div>

      <!-- Quick actions row -->
      <div id="daily-widget" style="display:flex;gap:var(--quick-row-gap);width:100%;max-width:var(--home-max-width);margin-bottom:var(--quick-row-margin);">
        <button class="quick-btn" id="btn-challenge-friend">
          <span class="qb-icon" style="background:linear-gradient(135deg,var(--violet),var(--purple-light));">${emoji('challenge_swords', '⚔️', 20)}</span>
          <span class="qb-label">${t('challenge.title')}</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">${t('play.achievements')}</span>
        </button>
        <button class="quick-btn breathe-glow" id="btn-daily-reward">
          <span class="qb-icon" style="background:linear-gradient(135deg,#92400e,var(--gold));">${emoji('gift', '🎁', 20)}</span>
          <span class="qb-label">${t('play.gift')}</span>
        </button>
      </div>

      <!-- Games -->
      <div class="games-grid">
        ${games.map(g => {
          return `
          <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: flex-start;
        height: 100%;
        padding: var(--home-padding) var(--home-padding) 0;
        overflow-y: auto;
      }
      .quick-btn { display:flex;flex-direction:column;align-items:center;gap:var(--quick-btn-gap);flex:1;background:none;border:none;cursor:pointer;padding:var(--quick-btn-padding);transition:transform 0.1s; }
      .quick-btn:active { transform:scale(0.9); }
      .qb-icon { width:var(--quick-btn-icon-size);height:var(--quick-btn-icon-size);border-radius:var(--quick-btn-icon-radius);display:flex;align-items:center;justify-content:center;font-size:var(--quick-btn-icon-font);box-shadow:0 3px 10px rgba(0,0,0,0.3); }
      .qb-label { font-size:var(--quick-btn-label-font);font-weight:600;color:var(--text-secondary); }
      .games-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: var(--game-tile-gap);
        width: 100%;
        max-width: var(--home-max-width);
      }
      .game-tile {
        position: relative;
        aspect-ratio: var(--game-tile-aspect);
        border-radius: var(--game-tile-radius);
        overflow: hidden;
        cursor: pointer;
        transition: transform 0.15s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.15s;
        box-shadow: var(--shadow-md);
      }
      .game-tile:active {
        transform: scale(0.93);
        box-shadow: var(--shadow-sm);
      }
      .game-tile-disabled {
        opacity: 0.4;
        pointer-events: none;
        filter: grayscale(0.5);
      }
      .game-tile-disabled:active { transform: none; }
      .game-tile-soon {
        font-size: var(--gm-btn-sub-font);
        font-weight: 700;
        color: rgba(255,255,255,0.7);
        background: rgba(0,0,0,0.3);
        padding: 2px 10px;
        border-radius: var(--r-sm);
        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: var(--game-tile-content-gap);
      }
      .game-tile-icon {
        font-size: var(--game-tile-icon-font);
        filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
      }
      .game-tile-icon img { width: var(--game-tile-icon-size); height: var(--game-tile-icon-size); object-fit: contain; }
      .game-tile-name {
        font-size: var(--game-tile-name-font);
        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: var(--sheet-bg);
        border-top-left-radius: var(--sheet-radius);
        border-top-right-radius: var(--sheet-radius);
        padding: var(--sheet-padding-top) var(--sheet-padding-x);
        padding-bottom: calc(var(--sheet-padding-top) + 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: var(--sheet-max-height);
      }
      .game-menu.hidden {
        transform: translateY(100%);
        pointer-events: none;
      }
      .game-menu-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: var(--menu-header-margin);
      }
      /* Game menu buttons */
      .gm-btn {
        display: flex;
        align-items: center;
        gap: var(--gm-btn-gap);
        width: 100%;
        padding: var(--gm-btn-padding-y) var(--gm-btn-padding-x);
        background: var(--bg-card);
        border: 1.5px solid var(--border);
        border-radius: var(--gm-btn-radius);
        cursor: pointer;
        margin-bottom: var(--gm-btn-margin-bottom);
        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: var(--gm-btn-icon-size);
        height: var(--gm-btn-icon-size);
        border-radius: var(--gm-btn-icon-radius);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: var(--gm-btn-icon-font);
        flex-shrink: 0;
        box-shadow: 0 3px 10px rgba(0,0,0,0.3);
      }
      .gm-btn-body { flex: 1; }
      .gm-btn-title { font-size: var(--gm-btn-title-font); font-weight: 800; color: var(--text-primary); }
      .gm-btn-sub { font-size: var(--gm-btn-sub-font); color: var(--text-muted); margin-top: 2px; }
      .gm-btn-arrow { font-size: var(--gm-btn-arrow-font); color: var(--text-muted); font-weight: 300; }
      .gm-chip {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: var(--gm-chip-gap);
        padding: var(--gm-chip-padding-y) var(--gm-chip-padding-x);
        background: var(--bg-card);
        border: 1px solid var(--border);
        border-radius: var(--gm-chip-radius);
        cursor: pointer;
        font-family: inherit;
        color: var(--text-primary);
        font-size: var(--gm-chip-font);
        font-weight: 600;
        transition: transform 0.1s, background 0.15s;
      }
      .gm-chip:active { transform: scale(0.93); background: rgba(255,255,255,0.08); }
    </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:var(--menu-header-margin);">
      <div style="display:flex;align-items:center;gap:var(--menu-header-gap);">
        <div style="width:var(--menu-header-icon-size);height:var(--menu-header-icon-size);border-radius:var(--menu-header-icon-radius);background:${game.gradient};display:flex;align-items:center;justify-content:center;font-size:var(--menu-header-icon-font);">${game.icon}</div>
        <div style="font-size:var(--menu-header-title-font);font-weight:800;color:var(--text-primary);">${game.name}</div>
      </div>
      <button id="menu-close" style="width:var(--menu-close-size);height:var(--menu-close-size);border-radius:50%;background:var(--border);border:none;color:var(--text-secondary);font-size:var(--menu-close-font);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">${t('play.single_player')}</div>
        <div class="gm-btn-sub">${t('play.single_player_desc')}</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,var(--orange));">${emoji('swords', '⚔️', 26)}</div>
      <div class="gm-btn-body">
        <div class="gm-btn-title">${t('game.online')}</div>
        <div class="gm-btn-sub">${t('play.online_desc')}</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'};gap:var(--gm-chips-grid-gap);margin-top:var(--gm-chips-margin-top);">
      <button class="gm-chip" id="btn-leaderboard">
        <span style="font-size:var(--gm-chip-icon-font);">${emoji('tournament_cup', '🏆', 18)}</span>
        <span>Leaderboard</span>
      </button>
      ${game.key === 'chess' ? `<button class="gm-chip" id="btn-history">
        <span style="font-size:var(--gm-chip-icon-font);">${emoji('clipboard', '📋', 18)}</span>
        <span>My Games</span>
      </button>
      <button class="gm-chip" id="btn-puzzles">
        <span style="font-size:var(--gm-chip-icon-font);">${emoji('puzzle', '🧩', 18)}</span>
        <span>Puzzles</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', { game: game.key });
  });

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