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,#0a0a14 0%,#0f0f1e 100%);">
      <div style="font-size:48px;">${emoji('domino_tile', '🁣', 48)}</div>
      <div style="font-size:22px;font-weight:800;color:#f8fafc;">دومينو</div>
      <div style="font-size:13px;color:#E4AC38;text-align:center;max-width:260px;">أول من يوصل الهدف يفوز!</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,#E4AC38,#d4940a);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,#0a0a14 0%,#0f0f1e 100%);">
      <div style="font-size:20px;font-weight:700;color:#f8fafc;">اختر مستوى البوت</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;
      renderTargetPicker(el, level);
    });
  });

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

function renderTargetPicker(el, botLevel) {
  const targets = [
    { value: 50, label: '50 نقطة', desc: 'مباراة سريعة', icon: '⚡', color: '#4ade80' },
    { value: 100, label: '100 نقطة', desc: 'كلاسيك', icon: '🎯', color: '#fbbf24' },
    { value: 150, label: '150 نقطة', 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,#0a0a14 0%,#0f0f1e 100%);">
      <div style="font-size:20px;font-weight:700;color:#f8fafc;">اختر الهدف</div>
      <div style="font-size:13px;color:#94a3b8;">أول من يوصل النقاط يفوز</div>
      <div style="display:flex;flex-direction:column;gap:10px;width:100%;max-width:300px;">
        ${targets.map(t => `
          <button class="btn-target" data-target="${t.value}" 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;">${t.icon}</span>
            <div style="flex:1;">
              <div style="font-size:15px;font-weight:700;color:${t.color};">${t.label}</div>
              <div style="font-size:12px;color:#94a3b8;margin-top:2px;">${t.desc}</div>
            </div>
            <div style="font-size:18px;color:#475569;">←</div>
          </button>
        `).join('')}
      </div>
      <button class="btn btn-secondary" id="btn-back-target" style="margin-top:8px;font-size:13px;color:#64748b;background:none;border:none;">رجوع</button>
    </div>
  `;

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

  el.querySelector('#btn-back-target').addEventListener('click', () => {
    audio.play('click');
    renderBotPicker(el);
  });
}

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,#0a0a14 0%,#0f0f1e 100%);">
      <div style="font-size:40px;">${emoji('domino_tile', '🁣', 40)}</div>
      <div style="font-size:18px;font-weight:700;color:#f8fafc;">
        ${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 #E4AC38;display:flex;align-items:center;justify-content:center;">
          ${emoji('clock', '⏳', 24)}
        </div>
        <div style="font-size:13px;color:#E4AC38;" 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,#3b82f6,#2563eb);">قبول</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();
}
