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

export function mountRoom(el, params) {
  const { mode = 'menu' } = params || {};

  if (mode === 'menu') {
    renderMenu(el);
  } else if (mode === 'setup') {
    renderSetup(el, params);
  } else if (mode === 'searching') {
    renderSearching(el, params);
  }
}

function renderMenu(el) {
  el.innerHTML = `
    <div class="lr-wrap">
      <div class="lr-hero">
        <div class="lr-icon">${emoji('dice', '🎲', 56)}</div>
        <h1 class="lr-title">${t('ludo.title')}</h1>
        <p class="lr-subtitle">${t('ludo.subtitle')}</p>
      </div>

      <div class="lr-buttons">
        <button class="lr-btn lr-btn-primary" id="btn-local">
          <span class="lr-btn-icon">${emoji('gamepad', '🎮', 22)}</span>
          <span class="lr-btn-label">${t('ludo.local_play')}</span>
          <span class="lr-btn-desc">${t('ludo.local_desc')}</span>
        </button>
        <button class="lr-btn lr-btn-online" id="btn-online">
          <span class="lr-btn-icon">${emoji('globe', '🌍', 22)}</span>
          <span class="lr-btn-label">${t('game.online')}</span>
          <span class="lr-btn-desc">${t('ludo.online_desc')}</span>
        </button>
        <button class="lr-btn lr-btn-friend" id="btn-friend">
          <span class="lr-btn-icon">${emoji('handshake', '🤝', 20)}</span>
          <span class="lr-btn-label">${t('game.vs_friend')}</span>
          <span class="lr-btn-desc">${t('ludo.friend_desc')}</span>
        </button>
      </div>

      <button class="lr-back" id="btn-back">${t('common.back')}</button>
    </div>
    ${getStyles()}
  `;

  el.querySelector('#btn-local').addEventListener('click', () => {
    audio.play('click');
    scene.replace('ludo-room', { mode: 'setup', type: 'local' });
  });

  el.querySelector('#btn-online').addEventListener('click', () => {
    audio.play('click');
    if (store.get('auth.isGuest')) {
      bus.emit('toast', { text: t('play.login_required_online') });
      return;
    }
    scene.replace('ludo-room', { mode: 'setup', type: 'online' });
  });

  el.querySelector('#btn-friend').addEventListener('click', () => {
    audio.play('click');
    if (store.get('auth.isGuest')) {
      bus.emit('toast', { text: t('play.login_required_friend') });
      return;
    }
    scene.push('challenge-friend', { game: 'ludo' });
  });

  el.querySelector('#btn-back').addEventListener('click', () => {
    audio.play('click');
    bus.emit('navigate', { world: 'play', scene: 'play-table' });
  });
}

function renderSetup(el, params) {
  const { type = 'local' } = params;
  const isOnline = type === 'online';

  el.innerHTML = `
    <div class="lr-wrap">
      <div class="lr-hero" style="margin-bottom:16px;">
        <h2 class="lr-title" style="font-size:20px;">${isOnline ? t('ludo.settings_online') : t('ludo.settings_play')}</h2>
        <p class="lr-subtitle">${isOnline ? t('ludo.settings_online_hint') : t('ludo.settings_play_hint')}</p>
      </div>

      <!-- Player Count -->
      <div class="lr-section">
        <div class="lr-section-title">${t('ludo.player_count')}</div>
        <div class="lr-grid" id="player-count-grid">
          <button class="lr-chip lr-chip-active" data-count="4">
            <span class="lr-chip-num">4</span>
            <span class="lr-chip-label">${t('ludo.classic')}</span>
          </button>
          <button class="lr-chip" data-count="3">
            <span class="lr-chip-num">3</span>
            <span class="lr-chip-label">${t('ludo.triple')}</span>
          </button>
          <button class="lr-chip" data-count="2">
            <span class="lr-chip-num">2</span>
            <span class="lr-chip-label">${t('ludo.duel')}</span>
          </button>
        </div>
      </div>

      <!-- Bot/Human Distribution (local only) -->
      ${!isOnline ? `
      <div class="lr-section" id="distribution-section">
        <div class="lr-section-title">${t('ludo.player_layout')}</div>
        <div id="dist-options"></div>
      </div>
      ` : ''}

      ${!isOnline ? `
      <!-- Bot Difficulty -->
      <div class="lr-section" id="difficulty-section">
        <div class="lr-section-title">${t('ludo.bot_level')}</div>
        <div class="lr-grid" id="difficulty-grid">
          <button class="lr-chip" data-diff="easy">
            <span>${emoji('bot_easy', '😊', 18)}</span>
            <span class="lr-chip-label">${t('ludo.easy')}</span>
          </button>
          <button class="lr-chip lr-chip-active" data-diff="medium">
            <span>${emoji('bot_medium', '🧐', 18)}</span>
            <span class="lr-chip-label">${t('ludo.medium')}</span>
          </button>
          <button class="lr-chip" data-diff="hard">
            <span>${emoji('bot_hard', '🧠', 18)}</span>
            <span class="lr-chip-label">${t('ludo.hard')}</span>
          </button>
        </div>
      </div>
      ` : ''}

      <!-- Seating Preview -->
      <div class="lr-section">
        <div class="lr-section-title">${t('ludo.seat_order')}</div>
        <div id="seat-preview" class="lr-seat-preview"></div>
      </div>

      <!-- Start Button -->
      <button class="lr-btn lr-btn-start" id="btn-start">
        ${isOnline ? t('ludo.search_match') : t('ludo.start_play')}
      </button>

      <button class="lr-back" id="btn-back-setup">${t('common.back')}</button>
    </div>
    ${getStyles()}
  `;

  let playerCount = 4;
  let humanCount = 1;
  let difficulty = 'medium';

  // Player count selection
  el.querySelectorAll('#player-count-grid .lr-chip').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      el.querySelectorAll('#player-count-grid .lr-chip').forEach(b => b.classList.remove('lr-chip-active'));
      btn.classList.add('lr-chip-active');
      playerCount = parseInt(btn.dataset.count);
      if (!isOnline) updateDistribution();
      updateSeatPreview();
    });
  });

  // Difficulty selection (local only)
  if (!isOnline) {
    el.querySelectorAll('#difficulty-grid .lr-chip').forEach(btn => {
      btn.addEventListener('click', () => {
        audio.play('click');
        el.querySelectorAll('#difficulty-grid .lr-chip').forEach(b => b.classList.remove('lr-chip-active'));
        btn.classList.add('lr-chip-active');
        difficulty = btn.dataset.diff;
      });
    });
  }

  function updateDistribution() {
    const container = el.querySelector('#dist-options');
    if (!container) return;

    const options = [];
    for (let h = 1; h <= playerCount; h++) {
      const bots = playerCount - h;
      const label = h === playerCount
        ? t('ludo.players_no_bot', { n: h })
        : h === 1
          ? t('ludo.one_player_bots', { n: bots })
          : t('ludo.players_bots', { h, n: bots });
      options.push({ humans: h, bots, label });
    }

    container.innerHTML = `<div class="lr-grid">${options.map((opt, i) => `
      <button class="lr-chip ${i === 0 ? 'lr-chip-active' : ''}" data-humans="${opt.humans}">
        <span class="lr-chip-label">${opt.label}</span>
      </button>
    `).join('')}</div>`;

    humanCount = 1;
    container.querySelectorAll('.lr-chip').forEach(btn => {
      btn.addEventListener('click', () => {
        audio.play('click');
        container.querySelectorAll('.lr-chip').forEach(b => b.classList.remove('lr-chip-active'));
        btn.classList.add('lr-chip-active');
        humanCount = parseInt(btn.dataset.humans);
        updateSeatPreview();
        // Show/hide difficulty based on whether bots exist
        const diffSec = el.querySelector('#difficulty-section');
        if (diffSec) diffSec.style.display = (playerCount - humanCount > 0) ? '' : 'none';
      });
    });

    updateSeatPreview();
  }

  function updateSeatPreview() {
    const preview = el.querySelector('#seat-preview');
    if (!preview) return;

    const seats = getSeatPositions(playerCount);
    const colors = ['#E53935', '#43A047', '#FDD835', '#1E88E5'];
    const labels = [t('ludo.red'), t('ludo.green'), t('ludo.yellow'), t('ludo.blue')];
    const positions = ['bottom-left', 'top-left', 'top-right', 'bottom-right'];

    preview.innerHTML = `
      <div class="lr-board-mini">
        ${[0,1,2,3].map(i => {
          const active = seats.includes(i);
          const isHuman = active && seats.indexOf(i) < humanCount;
          const isBot = active && !isHuman;
          return `
            <div class="lr-seat lr-seat-${positions[i]} ${active ? 'lr-seat-active' : 'lr-seat-empty'}" style="--seat-color:${colors[i]};">
              <div class="lr-seat-dot">${isHuman ? emoji('person', '👤', 14) : isBot ? emoji('robot', '🤖', 14) : ''}</div>
              <div class="lr-seat-label">${active ? labels[i] : '—'}</div>
            </div>
          `;
        }).join('')}
        <div class="lr-board-center">${emoji('dice', '🎲', 24)}</div>
      </div>
    `;
  }

  // Start button
  el.querySelector('#btn-start').addEventListener('click', () => {
    audio.play('click');
    const seats = getSeatPositions(playerCount);

    if (isOnline) {
      scene.push('play-queue', { game: 'ludo', mode: 'human', playerCount, seats });
    } else {
      scene.enterGameMode();
      scene.replace('ludo-game', {
        mode: humanCount > 1 ? 'local-multi' : 'bot',
        numPlayers: playerCount,
        seats,
        humanCount,
        difficulty,
        playerIndex: 0
      });
    }
  });

  el.querySelector('#btn-back-setup').addEventListener('click', () => {
    audio.play('click');
    scene.replace('ludo-room', { mode: 'menu' });
  });

  // Initial render
  if (!isOnline) updateDistribution();
  updateSeatPreview();
}

function getSeatPositions(playerCount) {
  if (playerCount === 4) return [0, 1, 2, 3];
  if (playerCount === 3) return [0, 1, 3]; // skip Yellow (top-right)
  if (playerCount === 2) return [0, 2]; // diagonal: Red(BL) vs Yellow(TR)
  return [0, 1, 2, 3];
}

function renderSearching(el, params) {
  el.innerHTML = `
    <div class="lr-wrap">
      <div class="lr-hero">
        <div class="lr-pulse-ring">
          <div class="lr-pulse-inner">${emoji('dice', '🎲', 32)}</div>
        </div>
        <h2 class="lr-title" style="font-size:18px;margin-top:20px;">${t('ludo.searching')}</h2>
        <p class="lr-subtitle">${t('ludo.searching_hint')}</p>
      </div>
      <button class="lr-btn lr-btn-friend" id="btn-cancel" style="max-width:200px;">${t('common.cancel')}</button>
    </div>
    ${getStyles()}
  `;

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

function getStyles() {
  return `<style>
    .lr-wrap {
      display:flex;flex-direction:column;align-items:center;justify-content:center;
      height:100%;padding:20px;
      background:linear-gradient(180deg, #070d14 0%, var(--bg-inset) 40%, var(--bg-inset) 100%);
      overflow-y:auto;
    }
    .lr-hero { text-align:center;margin-bottom:24px; }
    .lr-icon { font-size:56px;margin-bottom:12px;animation:lrFloat 3s ease-in-out infinite; }
    .lr-title { font-size:26px;font-weight:800;color:var(--text-primary);margin:0; }
    .lr-subtitle { font-size:13px;color:var(--gold);margin:8px 0 0;opacity:0.9; }
    .lr-buttons { display:flex;flex-direction:column;gap:12px;width:100%;max-width:320px; }
    .lr-btn {
      display:flex;align-items:center;gap:10px;flex-wrap:wrap;
      min-height:56px;border-radius:16px;font-size:16px;font-weight:700;
      border:none;cursor:pointer;padding:14px 18px;
      transition:transform 0.15s cubic-bezier(0.34,1.56,0.64,1), box-shadow 0.2s;
      box-shadow:0 4px 16px rgba(0,0,0,0.3);
    }
    .lr-btn:active { transform:scale(0.95); }
    .lr-btn-primary { background:linear-gradient(135deg,var(--gold) 0%,var(--gold-dark) 100%);color:#1a1a1a; }
    .lr-btn-online { background:linear-gradient(135deg,var(--purple) 0%,var(--violet) 100%);color:#fff; }
    .lr-btn-friend { background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.1);color:var(--text-light);min-height:50px;font-size:14px;box-shadow:none; }
    .lr-btn-start { width:100%;max-width:320px;justify-content:center;background:linear-gradient(135deg,var(--emerald),var(--cyan));color:#fff;font-size:17px;font-weight:800;margin-top:16px; }
    .lr-btn-icon { display:flex;flex-shrink:0; }
    .lr-btn-label { font-weight:700;font-size:16px; }
    .lr-btn-desc { width:100%;font-size:11px;opacity:0.7;font-weight:400;margin-top:2px; }
    .lr-back { margin-top:16px;font-size:13px;color:var(--text-muted);background:none;border:none;cursor:pointer;padding:8px 16px; }

    .lr-section { width:100%;max-width:320px;margin-bottom:16px; }
    .lr-section-title { font-size:12px;font-weight:700;color:var(--text-secondary);margin-bottom:8px;text-align:center; }
    .lr-grid { display:flex;gap:8px;justify-content:center;flex-wrap:wrap; }
    .lr-chip {
      display:flex;align-items:center;gap:6px;
      padding:10px 16px;border-radius:12px;
      background:rgba(255,255,255,0.04);border:1.5px solid rgba(255,255,255,0.08);
      color:var(--text-secondary);font-size:13px;font-weight:600;cursor:pointer;
      transition:all 0.2s cubic-bezier(0.34,1.56,0.64,1);
    }
    .lr-chip:active { transform:scale(0.95); }
    .lr-chip-active { background:rgba(228,172,56,0.1);border-color:rgba(228,172,56,0.4);color:var(--gold); }
    .lr-chip-num { font-size:18px;font-weight:800; }
    .lr-chip-label { font-size:12px; }

    .lr-seat-preview { display:flex;justify-content:center;margin-top:8px; }
    .lr-board-mini {
      position:relative;width:140px;height:140px;
      background:linear-gradient(135deg,#1a2844,#0f1a30);
      border-radius:12px;border:1px solid var(--border);
    }
    .lr-board-center { position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);font-size:24px; }
    .lr-seat {
      position:absolute;display:flex;flex-direction:column;align-items:center;gap:2px;
      transition:all 0.3s cubic-bezier(0.34,1.56,0.64,1);
    }
    .lr-seat-bottom-left { bottom:8px;left:8px; }
    .lr-seat-top-left { top:8px;left:8px; }
    .lr-seat-top-right { top:8px;right:8px; }
    .lr-seat-bottom-right { bottom:8px;right:8px; }
    .lr-seat-dot {
      width:28px;height:28px;border-radius:50%;
      display:flex;align-items:center;justify-content:center;font-size:14px;
      border:2px solid var(--seat-color);
      background:rgba(0,0,0,0.3);
      transition:all 0.3s;
    }
    .lr-seat-active .lr-seat-dot { background:color-mix(in srgb, var(--seat-color) 20%, transparent); }
    .lr-seat-empty .lr-seat-dot { opacity:0.2;border-style:dashed; }
    .lr-seat-label { font-size:9px;color:var(--text-muted); }
    .lr-seat-active .lr-seat-label { color:var(--seat-color); }

    .lr-pulse-ring {
      width:80px;height:80px;border-radius:50%;
      border:3px solid rgba(228,172,56,0.4);
      display:flex;align-items:center;justify-content:center;
      animation:lrPulse 2s ease-in-out infinite;
      margin:0 auto;
    }
    .lr-pulse-inner { font-size:32px; }

    @keyframes lrFloat { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }
    @keyframes lrPulse { 0%,100%{border-color:rgba(228,172,56,0.4);transform:scale(1)} 50%{border-color:rgba(228,172,56,0.7);transform:scale(1.05)} }
  </style>`;
}

export function unmountRoom() {}
