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

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

      <!-- Player Count -->
      <div class="lr-section">
        <div class="lr-section-title">عدد اللاعبين</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">كلاسيك</span>
          </button>
          <button class="lr-chip" data-count="3">
            <span class="lr-chip-num">3</span>
            <span class="lr-chip-label">ثلاثي</span>
          </button>
          <button class="lr-chip" data-count="2">
            <span class="lr-chip-num">2</span>
            <span class="lr-chip-label">مبارزة</span>
          </button>
        </div>
      </div>

      <!-- Bot/Human Distribution (local only) -->
      ${!isOnline ? `
      <div class="lr-section" id="distribution-section">
        <div class="lr-section-title">توزيعة اللاعبين</div>
        <div id="dist-options"></div>
      </div>
      ` : ''}

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

      <!-- Seating Preview -->
      <div class="lr-section">
        <div class="lr-section-title">ترتيب المقاعد</div>
        <div id="seat-preview" class="lr-seat-preview"></div>
      </div>

      <!-- Start Button -->
      <button class="lr-btn lr-btn-start" id="btn-start">
        ${isOnline ? 'ابحث عن مباراة' : 'ابدأ اللعب'}
      </button>

      <button class="lr-back" id="btn-back-setup">رجوع</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
        ? `${h} لاعبين (بدون بوت)`
        : h === 1
          ? `لاعب واحد + ${bots} بوت`
          : `${h} لاعبين + ${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 = ['أحمر', 'أخضر', 'أصفر', 'أزرق'];
    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 ? '👤' : isBot ? '🤖' : ''}</div>
              <div class="lr-seat-label">${active ? labels[i] : '—'}</div>
            </div>
          `;
        }).join('')}
        <div class="lr-board-center">🎲</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;">جاري البحث...</h2>
        <p class="lr-subtitle">بنوصّلك بلاعبين قريب</p>
      </div>
      <button class="lr-btn lr-btn-friend" id="btn-cancel" style="max-width:200px;">إلغاء</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%, #0a1420 40%, #0d1a2a 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:#f8fafc;margin:0; }
    .lr-subtitle { font-size:13px;color:#E4AC38;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,#E4AC38 0%,#d4940a 100%);color:#1a1a1a; }
    .lr-btn-online { background:linear-gradient(135deg,#8B5CF6 0%,#7C3AED 100%);color:#fff; }
    .lr-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; }
    .lr-btn-start { width:100%;max-width:320px;justify-content:center;background:linear-gradient(135deg,#10b981,#06b6d4);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:#64748b;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:#94a3b8;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:#94a3b8;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:#E4AC38; }
    .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 rgba(255,255,255,0.06);
    }
    .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:#64748b; }
    .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() {}
