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

let pollTimer = null;

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

  if (mode === 'bot-pick') {
    renderBotPicker(el);
  } else if (mode === 'lobby') {
    renderLobby(el, { challengeId, friendId, friendName });
  } else {
    renderMenu(el);
  }
}

function renderMenu(el) {
  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:20px;padding:24px;background:linear-gradient(180deg,#081a0c 0%,#0a2a0e 100%);">
      <div style="font-size:48px;">${emoji('domino_tile', '🁣', 48)}</div>
      <div style="font-size:22px;font-weight:800;color:#f0fdf4;">دومينو</div>
      <div style="font-size:13px;color:#86efac;text-align:center;max-width:260px;">أول من يوصل 100 نقطة يفوز!</div>

      <div style="display:flex;flex-direction:column;gap:10px;width:100%;max-width:300px;margin-top:12px;">
        <button class="btn btn-primary" id="btn-bot" style="min-height:56px;border-radius:16px;font-size:16px;font-weight:700;background:linear-gradient(135deg,#10b981,#059669);display:flex;align-items:center;justify-content:center;gap:8px;">
          ${emoji('robot', '🤖', 20)} ضد البوت
        </button>
        <button class="btn btn-primary" id="btn-online" style="min-height:56px;border-radius:16px;font-size:16px;font-weight:700;background:linear-gradient(135deg,#06b6d4,#0891b2);display:flex;align-items:center;justify-content:center;gap:8px;">
          ${emoji('globe', '🌍', 20)} أونلاين
        </button>
        <button class="btn btn-secondary" id="btn-friend" style="min-height:48px;border-radius:14px;font-size:14px;font-weight:600;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);color:#e2e8f0;display:flex;align-items:center;justify-content:center;gap:8px;">
          ${emoji('handshake', '🤝', 18)} تحدي صديق
        </button>
      </div>

      <button class="btn btn-secondary" id="btn-back" style="margin-top:12px;font-size:13px;color:#64748b;background:none;border:none;">رجوع</button>
    </div>
  `;

  el.querySelector('#btn-bot').addEventListener('click', () => {
    audio.play('click');
    scene.replace('domino-room', { mode: 'bot-pick' });
  });

  el.querySelector('#btn-online').addEventListener('click', () => {
    audio.play('click');
    scene.push('play-queue', { game: 'domino' });
  });

  el.querySelector('#btn-friend').addEventListener('click', () => {
    audio.play('click');
    scene.push('challenge-friend', { game: 'domino' });
  });

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

function renderBotPicker(el) {
  const levels = [
    { key: 'beginner', label: 'مبتدئ', desc: 'يلعب عشوائي', icon: '😊', color: '#4ade80' },
    { key: 'intermediate', label: 'متوسط', desc: 'يفضل النقاط العالية', icon: '🧐', color: '#fbbf24' },
    { key: 'expert', label: 'خبير', desc: 'استراتيجي ومخادع', icon: '🧠', color: '#f87171' }
  ];

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:20px;padding:24px;background:linear-gradient(180deg,#081a0c 0%,#0a2a0e 100%);">
      <div style="font-size:20px;font-weight:700;color:#f0fdf4;">اختر مستوى البوت</div>
      <div style="display:flex;flex-direction:column;gap:10px;width:100%;max-width:300px;">
        ${levels.map(l => `
          <button class="btn-level" data-level="${l.key}" style="
            display:flex;align-items:center;gap:12px;padding:16px;
            background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);
            border-radius:14px;cursor:pointer;width:100%;text-align:right;
            transition:transform 0.1s,border-color 0.2s;
          ">
            <span style="font-size:28px;">${l.icon}</span>
            <div style="flex:1;">
              <div style="font-size:15px;font-weight:700;color:${l.color};">${l.label}</div>
              <div style="font-size:12px;color:#94a3b8;margin-top:2px;">${l.desc}</div>
            </div>
            <div style="font-size:18px;color:#475569;">←</div>
          </button>
        `).join('')}
      </div>
      <button class="btn btn-secondary" id="btn-back-bot" style="margin-top:8px;font-size:13px;color:#64748b;background:none;border:none;">رجوع</button>
    </div>
  `;

  el.querySelectorAll('.btn-level').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      const level = btn.dataset.level;
      scene.enterGameMode();
      scene.replace('domino-game', { mode: 'bot', botLevel: level });
    });
  });

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

function renderLobby(el, { challengeId, friendId, friendName }) {
  const isHost = !challengeId;
  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:16px;padding:24px;background:linear-gradient(180deg,#081a0c 0%,#0a2a0e 100%);">
      <div style="font-size:40px;">${emoji('domino_tile', '🁣', 40)}</div>
      <div style="font-size:18px;font-weight:700;color:#f0fdf4;">
        ${isHost ? 'بانتظار الصديق...' : `تحدي من ${friendName || 'صديق'}`}
      </div>

      <div id="lobby-status" style="display:flex;flex-direction:column;align-items:center;gap:8px;">
        <div class="pulse" style="width:60px;height:60px;border-radius:50%;border:3px solid #10b981;display:flex;align-items:center;justify-content:center;">
          ${emoji('clock', '⏳', 24)}
        </div>
        <div style="font-size:13px;color:#86efac;" id="lobby-msg">${isHost ? 'أرسل الدعوة لصديقك' : 'اضغط قبول للبدء'}</div>
      </div>

      <div style="display:flex;gap:10px;margin-top:12px;">
        ${!isHost ? `<button class="btn btn-primary" id="btn-accept" style="min-height:48px;padding:0 24px;border-radius:14px;font-size:15px;font-weight:700;background:linear-gradient(135deg,#10b981,#06b6d4);">قبول</button>` : ''}
        <button class="btn btn-secondary" id="btn-cancel-lobby" style="min-height:48px;padding:0 24px;border-radius:14px;font-size:14px;background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);color:#fca5a5;">إلغاء</button>
      </div>
    </div>
  `;

  if (isHost) {
    pollForAcceptance(el, friendId);
  }

  el.querySelector('#btn-accept')?.addEventListener('click', () => {
    audio.play('click');
    acceptChallenge(el, challengeId);
  });

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

async function pollForAcceptance(el, friendId) {
  try {
    const data = await net.post('domino-match.php', {
      action: 'start',
      mode: 'friend',
      friend_id: friendId
    });
    if (data?.id) {
      const matchId = data.id;
      const msgEl = el.querySelector('#lobby-msg');
      if (msgEl) msgEl.textContent = 'تم إنشاء المباراة، بانتظار القبول...';

      pollTimer = setInterval(async () => {
        try {
          const status = await net.post('domino-match.php', { action: 'get', match_id: matchId });
          if (status?.status === 'in_progress' && status?.game_state) {
            const gs = typeof status.game_state === 'string' ? JSON.parse(status.game_state) : status.game_state;
            if (gs.accepted) {
              cleanupLobby();
              audio.play('notification');
              scene.replace('domino-game', { mode: 'live', matchId, playerIndex: 0 });
            }
          }
        } catch (e) {}
      }, 2500);
    }
  } catch (e) {}
}

async function acceptChallenge(el, challengeId) {
  try {
    await net.post('domino-match.php', {
      action: 'move',
      match_id: challengeId,
      game_state: JSON.stringify({ accepted: true, accepted_at: Date.now() })
    });
    cleanupLobby();
    audio.play('notification');
    scene.replace('domino-game', { mode: 'live', matchId: challengeId, playerIndex: 1 });
  } catch (e) {}
}

function cleanupLobby() {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
}

export function unmountRoom() {
  cleanupLobby();
}
