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 { emoji } from '../../../core/theme.js';
import { t } from '../../../core/i18n.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="bg-wrap">
      <div class="bg-hero">
        <div class="bg-icon">${emoji('game_die', '🎲', 56)}</div>
        <h1 class="bg-title">${t('backgammon.title')}</h1>
        <p class="bg-subtitle">${t('backgammon.subtitle')}</p>
      </div>

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

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

  el.querySelector('#btn-local').onclick = () => {
    audio.play('click');
    scene.replace('backgammon-room', { mode: 'setup', type: 'local' });
  };
  el.querySelector('#btn-online').onclick = () => {
    audio.play('click');
    if (store.get('auth.isGuest')) {
      bus.emit('toast', { text: t('play.login_required_online') });
      return;
    }
    scene.replace('backgammon-room', { mode: 'setup', type: 'online' });
  };
  el.querySelector('#btn-friend').onclick = () => {
    audio.play('click');
    if (store.get('auth.isGuest')) {
      bus.emit('toast', { text: t('play.login_required_friend') });
      return;
    }
    scene.push('challenge-friend', { game: 'backgammon' });
  };
  el.querySelector('#btn-back').onclick = () => {
    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="bg-wrap">
      <div class="bg-hero" style="margin-bottom:16px;">
        <h2 class="bg-title" style="font-size:20px;">${isOnline ? t('backgammon.settings_online') : t('backgammon.settings_game')}</h2>
      </div>

      <!-- Variant -->
      <div class="bg-section">
        <div class="bg-section-title">${t('backgammon.game_type')}</div>
        <div class="bg-grid" id="variant-grid">
          <button class="bg-chip bg-chip-active" data-variant="sheshbesh">
            <span class="bg-chip-label">${t('backgammon.sheshbesh')}</span>
          </button>
          <button class="bg-chip" data-variant="mahbousa">
            <span class="bg-chip-label">${t('backgammon.mahbousa')}</span>
          </button>
          <button class="bg-chip" data-variant="thirtyone">
            <span class="bg-chip-label">${t('backgammon.thirtyone')}</span>
          </button>
        </div>
      </div>

      <!-- Match Length -->
      <div class="bg-section">
        <div class="bg-section-title">${t('backgammon.match_length')}</div>
        <div class="bg-grid" id="length-grid">
          <button class="bg-chip" data-len="1">
            <span class="bg-chip-num">1</span>
            <span class="bg-chip-label">${t('backgammon.short_match')}</span>
          </button>
          <button class="bg-chip bg-chip-active" data-len="3">
            <span class="bg-chip-num">3</span>
            <span class="bg-chip-label">${t('backgammon.medium_match')}</span>
          </button>
          <button class="bg-chip" data-len="5">
            <span class="bg-chip-num">5</span>
            <span class="bg-chip-label">${t('backgammon.normal_match')}</span>
          </button>
          <button class="bg-chip" data-len="7">
            <span class="bg-chip-num">7</span>
            <span class="bg-chip-label">${t('backgammon.long_match')}</span>
          </button>
        </div>
      </div>

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

      <!-- Doubling Cube Toggle -->
      <div class="bg-section">
        <div class="bg-section-title">${t('backgammon.doubling_cube')}</div>
        <div class="bg-grid" id="cube-grid">
          <button class="bg-chip bg-chip-active" data-cube="on">
            <span class="bg-chip-label">${t('backgammon.enabled')}</span>
          </button>
          <button class="bg-chip" data-cube="off">
            <span class="bg-chip-label">${t('backgammon.disabled')}</span>
          </button>
        </div>
      </div>

      <button class="bg-btn bg-btn-start" id="btn-start">
        ${isOnline ? t('ludo.search_match') : t('ludo.start_play')}
      </button>
      <button class="bg-back" id="btn-back-setup">${t('common.back')}</button>
    </div>
    ${getStyles()}
  `;

  let variant = 'sheshbesh';
  let matchLength = 3;
  let difficulty = 'medium';
  let useCube = true;

  setupChipGroup(el, '#variant-grid', val => { variant = val; }, 'variant');
  setupChipGroup(el, '#length-grid', val => { matchLength = parseInt(val); }, 'len');
  if (!isOnline) setupChipGroup(el, '#difficulty-grid', val => { difficulty = val; }, 'diff');
  setupChipGroup(el, '#cube-grid', val => { useCube = val === 'on'; }, 'cube');

  el.querySelector('#btn-start').onclick = () => {
    audio.play('click');
    if (isOnline) {
      scene.push('play-queue', { game: 'backgammon', variant, matchLength, useCube });
    } else {
      scene.enterGameMode();
      scene.replace('backgammon-game', {
        mode: 'bot',
        variant,
        matchLength,
        difficulty,
        useCube
      });
    }
  };

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

function renderSearching(el) {
  el.innerHTML = `
    <div class="bg-wrap">
      <div class="bg-hero">
        <div class="bg-pulse-ring">
          <div class="bg-pulse-inner">${emoji('game_die', '🎲', 32)}</div>
        </div>
        <h2 class="bg-title" style="font-size:18px;margin-top:20px;">${t('backgammon.searching')}</h2>
        <p class="bg-subtitle">${t('backgammon.searching_hint')}</p>
      </div>
      <button class="bg-btn bg-btn-friend" id="btn-cancel" style="max-width:200px;">${t('common.cancel')}</button>
    </div>
    ${getStyles()}
  `;
  el.querySelector('#btn-cancel').onclick = () => { audio.play('click'); scene.pop(); };
}

function setupChipGroup(el, selector, onChange, dataKey) {
  el.querySelectorAll(`${selector} .bg-chip`).forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      el.querySelectorAll(`${selector} .bg-chip`).forEach(b => b.classList.remove('bg-chip-active'));
      btn.classList.add('bg-chip-active');
      onChange(btn.dataset[dataKey]);
    });
  });
}

function getStyles() {
  return `<style>
    .bg-wrap {
      display:flex;flex-direction:column;align-items:center;justify-content:center;
      height:100%;padding:20px;
      background:linear-gradient(180deg,#0a0f14 0%,#101820 40%,#141f2c 100%);
      overflow-y:auto;
    }
    .bg-hero { text-align:center;margin-bottom:24px; }
    .bg-icon { font-size:56px;margin-bottom:12px;animation:bgFloat 3s ease-in-out infinite; }
    .bg-title { font-size:26px;font-weight:800;color:var(--text-primary);margin:0; }
    .bg-subtitle { font-size:13px;color:var(--gold-dark);margin:8px 0 0;opacity:0.9; }
    .bg-buttons { display:flex;flex-direction:column;gap:12px;width:100%;max-width:320px; }
    .bg-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);
    }
    .bg-btn:active { transform:scale(0.95); }
    .bg-btn-primary { background:linear-gradient(135deg,var(--gold-dark) 0%,#8B4513 100%);color:#fff; }
    .bg-btn-online { background:linear-gradient(135deg,var(--purple) 0%,var(--violet) 100%);color:#fff; }
    .bg-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; }
    .bg-btn-start { width:100%;max-width:320px;justify-content:center;background:linear-gradient(135deg,var(--gold-dark),#8B4513);color:#fff;font-size:17px;font-weight:800;margin-top:16px; }
    .bg-btn-icon { display:flex;flex-shrink:0; }
    .bg-btn-label { font-weight:700;font-size:16px; }
    .bg-btn-desc { width:100%;font-size:11px;opacity:0.7;font-weight:400;margin-top:2px; }
    .bg-back { margin-top:16px;font-size:13px;color:var(--text-muted);background:none;border:none;cursor:pointer;padding:8px 16px; }

    .bg-section { width:100%;max-width:320px;margin-bottom:16px; }
    .bg-section-title { font-size:12px;font-weight:700;color:var(--text-secondary);margin-bottom:8px;text-align:center; }
    .bg-grid { display:flex;gap:8px;justify-content:center;flex-wrap:wrap; }
    .bg-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);
    }
    .bg-chip:active { transform:scale(0.95); }
    .bg-chip-active { background:rgba(212,148,10,0.12);border-color:rgba(212,148,10,0.5);color:var(--gold-dark); }
    .bg-chip-num { font-size:18px;font-weight:800; }
    .bg-chip-label { font-size:12px; }

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

    @keyframes bgFloat { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }
    @keyframes bgPulse { 0%,100%{border-color:rgba(212,148,10,0.4);transform:scale(1)} 50%{border-color:rgba(212,148,10,0.7);transform:scale(1.05)} }
  </style>`;
}

export function unmountRoom() {}
