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 class="domino-menu">
      <div class="dm-hero">
        <div class="dm-icon">${emoji('domino_tile', '🁣', 56)}</div>
        <h1 class="dm-title">دومينو</h1>
        <p class="dm-subtitle">أول من يوصل الهدف يفوز!</p>
      </div>

      <div class="dm-buttons">
        <button class="dm-btn dm-btn-primary" id="btn-bot">
          <span class="dm-btn-icon">${emoji('robot', '🤖', 22)}</span>
          <span class="dm-btn-label">ضد البوت</span>
        </button>
        <button class="dm-btn dm-btn-online" id="btn-online">
          <span class="dm-btn-icon">${emoji('globe', '🌍', 22)}</span>
          <span class="dm-btn-label">أونلاين</span>
        </button>
        <button class="dm-btn dm-btn-friend" id="btn-friend">
          <span class="dm-btn-icon">${emoji('handshake', '🤝', 20)}</span>
          <span class="dm-btn-label">تحدي صديق</span>
        </button>
      </div>

      <button class="dm-back" id="btn-back">رجوع</button>
    </div>
    <style>
      .domino-menu {
        display:flex;flex-direction:column;align-items:center;justify-content:center;
        height:100%;padding:24px;
        background:linear-gradient(180deg, #070d14 0%, #0a1420 40%, #0d1a2a 100%);
      }
      .dm-hero { text-align:center;margin-bottom:28px; }
      .dm-icon { font-size:56px;margin-bottom:12px;animation:dmFloat 3s ease-in-out infinite; }
      .dm-title { font-size:26px;font-weight:800;color:#f8fafc;margin:0; }
      .dm-subtitle { font-size:13px;color:#E4AC38;margin:8px 0 0;opacity:0.9; }
      .dm-buttons { display:flex;flex-direction:column;gap:12px;width:100%;max-width:300px; }
      .dm-btn {
        display:flex;align-items:center;justify-content:center;gap:10px;
        min-height:56px;border-radius:16px;font-size:16px;font-weight:700;
        border:none;cursor:pointer;
        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);
      }
      .dm-btn:active { transform:scale(0.95); }
      .dm-btn-primary { background:linear-gradient(135deg,#E4AC38 0%,#d4940a 100%);color:#1a1a1a; }
      .dm-btn-online { background:linear-gradient(135deg,#06b6d4 0%,#0891b2 100%);color:#fff; }
      .dm-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; }
      .dm-btn-icon { display:flex; }
      .dm-btn-label { flex:none; }
      .dm-back { margin-top:20px;font-size:13px;color:#64748b;background:none;border:none;cursor:pointer;padding:8px 16px; }
      @keyframes dmFloat { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-6px)} }
    </style>
  `;

  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', bg: 'rgba(74,222,128,0.08)', border: 'rgba(74,222,128,0.2)' },
    { key: 'intermediate', label: 'متوسط', desc: 'يفضل النقاط العالية', icon: '🧐', color: '#fbbf24', bg: 'rgba(251,191,36,0.08)', border: 'rgba(251,191,36,0.2)' },
    { key: 'expert', label: 'خبير', desc: 'استراتيجي ومخادع', icon: '🧠', color: '#f87171', bg: 'rgba(248,113,113,0.08)', border: 'rgba(248,113,113,0.2)' }
  ];

  el.innerHTML = `
    <div class="domino-menu">
      <div class="dm-hero">
        <h2 style="font-size:20px;font-weight:700;color:#f8fafc;margin:0;">اختر مستوى البوت</h2>
        <p style="font-size:12px;color:#94a3b8;margin:8px 0 0;">كل مستوى له استراتيجية مختلفة</p>
      </div>
      <div class="dm-buttons">
        ${levels.map(l => `
          <button class="dm-level-btn" data-level="${l.key}" style="background:${l.bg};border:1px solid ${l.border};">
            <span class="dm-level-icon">${l.icon}</span>
            <div class="dm-level-info">
              <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>
            <span style="font-size:16px;color:#475569;">←</span>
          </button>
        `).join('')}
      </div>
      <button class="dm-back" id="btn-back-bot">رجوع</button>
    </div>
    <style>
      .dm-level-btn {
        display:flex;align-items:center;gap:14px;padding:16px 18px;
        border-radius:14px;cursor:pointer;width:100%;text-align:right;
        transition:transform 0.15s cubic-bezier(0.34,1.56,0.64,1), box-shadow 0.2s;
      }
      .dm-level-btn:active { transform:scale(0.97); }
      .dm-level-icon { font-size:30px;flex-shrink:0; }
      .dm-level-info { flex:1; }
    </style>
  `;

  el.querySelectorAll('.dm-level-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      audio.play('click');
      renderTargetPicker(el, btn.dataset.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: 'مباراة سريعة (~5 دقائق)', icon: '⚡', color: '#4ade80', bg: 'rgba(74,222,128,0.08)', border: 'rgba(74,222,128,0.2)' },
    { value: 100, label: '100 نقطة', desc: 'كلاسيك (~10 دقائق)', icon: '🎯', color: '#fbbf24', bg: 'rgba(251,191,36,0.08)', border: 'rgba(251,191,36,0.2)' },
    { value: 150, label: '150 نقطة', desc: 'مباراة طويلة (~15 دقيقة)', icon: '🔥', color: '#f87171', bg: 'rgba(248,113,113,0.08)', border: 'rgba(248,113,113,0.2)' }
  ];

  el.innerHTML = `
    <div class="domino-menu">
      <div class="dm-hero">
        <h2 style="font-size:20px;font-weight:700;color:#f8fafc;margin:0;">اختر الهدف</h2>
        <p style="font-size:12px;color:#94a3b8;margin:8px 0 0;">أول من يوصل النقاط يفوز بالمباراة</p>
      </div>
      <div class="dm-buttons">
        ${targets.map(t => `
          <button class="dm-level-btn" data-target="${t.value}" style="background:${t.bg};border:1px solid ${t.border};">
            <span class="dm-level-icon">${t.icon}</span>
            <div class="dm-level-info">
              <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>
            <span style="font-size:16px;color:#475569;">←</span>
          </button>
        `).join('')}
      </div>
      <button class="dm-back" id="btn-back-target">رجوع</button>
    </div>
  `;

  el.querySelectorAll('.dm-level-btn').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 class="domino-menu">
      <div class="dm-hero">
        <div style="font-size:44px;margin-bottom:12px;">${emoji('domino_tile', '🁣', 44)}</div>
        <h2 style="font-size:18px;font-weight:700;color:#f8fafc;margin:0;">
          ${isHost ? 'بانتظار الصديق...' : `تحدي من ${friendName || 'صديق'}`}
        </h2>
      </div>

      <div id="lobby-status" style="display:flex;flex-direction:column;align-items:center;gap:12px;">
        <div style="width:64px;height:64px;border-radius:50%;border:3px solid rgba(228,172,56,0.4);display:flex;align-items:center;justify-content:center;animation:dmPulseRing 2s ease-in-out infinite;">
          ${emoji('clock', '⏳', 26)}
        </div>
        <div style="font-size:13px;color:#E4AC38;" id="lobby-msg">${isHost ? 'أرسل الدعوة لصديقك' : 'اضغط قبول للبدء'}</div>
      </div>

      <div style="display:flex;gap:10px;margin-top:20px;">
        ${!isHost ? `<button class="dm-btn dm-btn-online" id="btn-accept" style="min-height:48px;padding:0 28px;font-size:15px;">قبول</button>` : ''}
        <button class="dm-btn dm-btn-friend" id="btn-cancel-lobby" style="min-height:48px;padding:0 20px;font-size:14px;border-color:rgba(239,68,68,0.3);color:#fca5a5;">إلغاء</button>
      </div>
    </div>
    <style>
      @keyframes dmPulseRing { 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>
  `;

  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();
}
