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

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">طاولة</h1>
        <p class="bg-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">ضد البوت</span>
          <span class="bg-btn-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">أونلاين</span>
          <span class="bg-btn-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">تحدي صديق</span>
          <span class="bg-btn-desc">ادعُ صديقك للعب</span>
        </button>
      </div>

      <button class="bg-back" id="btn-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: 'سجّل دخولك للعب أونلاين' });
      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: 'سجّل دخولك لتحدي صديق' });
      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 ? 'إعدادات الأونلاين' : 'إعدادات اللعبة'}</h2>
      </div>

      <!-- Variant -->
      <div class="bg-section">
        <div class="bg-section-title">نوع اللعبة</div>
        <div class="bg-grid" id="variant-grid">
          <button class="bg-chip bg-chip-active" data-variant="sheshbesh">
            <span class="bg-chip-label">شيش بيش</span>
          </button>
          <button class="bg-chip" data-variant="mahbousa">
            <span class="bg-chip-label">محبوسة</span>
          </button>
          <button class="bg-chip" data-variant="thirtyone">
            <span class="bg-chip-label">٣١</span>
          </button>
        </div>
      </div>

      <!-- Match Length -->
      <div class="bg-section">
        <div class="bg-section-title">طول الماتش</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">سريع</span>
          </button>
          <button class="bg-chip bg-chip-active" data-len="3">
            <span class="bg-chip-num">3</span>
            <span class="bg-chip-label">قصير</span>
          </button>
          <button class="bg-chip" data-len="5">
            <span class="bg-chip-num">5</span>
            <span class="bg-chip-label">عادي</span>
          </button>
          <button class="bg-chip" data-len="7">
            <span class="bg-chip-num">7</span>
            <span class="bg-chip-label">طويل</span>
          </button>
        </div>
      </div>

      ${!isOnline ? `
      <!-- Bot Difficulty -->
      <div class="bg-section">
        <div class="bg-section-title">مستوى البوت</div>
        <div class="bg-grid" id="difficulty-grid">
          <button class="bg-chip" data-diff="easy">
            <span>😊</span>
            <span class="bg-chip-label">سهل</span>
          </button>
          <button class="bg-chip bg-chip-active" data-diff="medium">
            <span>🧐</span>
            <span class="bg-chip-label">متوسط</span>
          </button>
          <button class="bg-chip" data-diff="hard">
            <span>🧠</span>
            <span class="bg-chip-label">صعب</span>
          </button>
        </div>
      </div>
      ` : ''}

      <!-- Doubling Cube Toggle -->
      <div class="bg-section">
        <div class="bg-section-title">مكعب المضاعفة</div>
        <div class="bg-grid" id="cube-grid">
          <button class="bg-chip bg-chip-active" data-cube="on">
            <span class="bg-chip-label">مفعّل</span>
          </button>
          <button class="bg-chip" data-cube="off">
            <span class="bg-chip-label">بدون</span>
          </button>
        </div>
      </div>

      <button class="bg-btn bg-btn-start" id="btn-start">
        ${isOnline ? 'ابحث عن مباراة' : 'ابدأ اللعب'}
      </button>
      <button class="bg-back" id="btn-back-setup">رجوع</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;">جاري البحث...</h2>
        <p class="bg-subtitle">بنوصّلك بلاعب قريب</p>
      </div>
      <button class="bg-btn bg-btn-friend" id="btn-cancel" style="max-width:200px;">إلغاء</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:#f8fafc;margin:0; }
    .bg-subtitle { font-size:13px;color:#d4940a;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,#d4940a 0%,#8B4513 100%);color:#fff; }
    .bg-btn-online { background:linear-gradient(135deg,#8B5CF6 0%,#7C3AED 100%);color:#fff; }
    .bg-btn-friend { background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.1);color:#e2e8f0;min-height:50px;font-size:14px;box-shadow:none; }
    .bg-btn-start { width:100%;max-width:320px;justify-content:center;background:linear-gradient(135deg,#d4940a,#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:#64748b;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:#94a3b8;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:#94a3b8;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:#d4940a; }
    .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() {}
