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">${t('domino.title')}</h1>
        <p class="dm-subtitle">${t('domino.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">${t('game.vs_bot')}</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">${t('game.online')}</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">${t('game.vs_friend')}</span>
        </button>
      </div>

      <button class="dm-back" id="btn-back">${t('common.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%, var(--bg-inset) 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:var(--text-primary);margin:0; }
      .dm-subtitle { font-size:13px;color:var(--gold);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,var(--gold) 0%,var(--gold-dark) 100%);color:var(--bg-dark); }
      .dm-btn-online { background:linear-gradient(135deg,var(--cyan) 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:var(--text-light);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:var(--text-muted);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: t('domino.beginner'), desc: t('domino.beginner_desc'), icon: emoji('bot_easy', '😊', 30), color: 'var(--green-light)', bg: 'rgba(74,222,128,0.08)', border: 'rgba(74,222,128,0.2)' },
    { key: 'intermediate', label: t('domino.intermediate'), desc: t('domino.intermediate_desc'), icon: emoji('bot_medium', '🧐', 30), color: 'var(--amber)', bg: 'rgba(251,191,36,0.08)', border: 'rgba(251,191,36,0.2)' },
    { key: 'expert', label: t('domino.expert'), desc: t('domino.expert_desc'), icon: emoji('bot_hard', '🧠', 30), color: 'var(--red-light)', 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:var(--text-primary);margin:0;">${t('domino.select_bot')}</h2>
        <p style="font-size:12px;color:var(--text-secondary);margin:8px 0 0;">${t('domino.bot_strategy')}</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:var(--text-secondary);margin-top:2px;">${l.desc}</div>
            </div>
            <span style="font-size:16px;color:var(--text-dim);">←</span>
          </button>
        `).join('')}
      </div>
      <button class="dm-back" id="btn-back-bot">${t('common.back')}</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: t('domino.50_points'), desc: t('domino.50_desc'), icon: emoji('lightning', '⚡', 30), color: 'var(--green-light)', bg: 'rgba(74,222,128,0.08)', border: 'rgba(74,222,128,0.2)' },
    { value: 100, label: t('domino.100_points'), desc: t('domino.100_desc'), icon: emoji('target', '🎯', 30), color: 'var(--amber)', bg: 'rgba(251,191,36,0.08)', border: 'rgba(251,191,36,0.2)' },
    { value: 150, label: t('domino.150_points'), desc: t('domino.150_desc'), icon: emoji('fire', '🔥', 30), color: 'var(--red-light)', 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:var(--text-primary);margin:0;">${t('domino.select_target')}</h2>
        <p style="font-size:12px;color:var(--text-secondary);margin:8px 0 0;">${t('domino.target_hint')}</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:var(--text-secondary);margin-top:2px;">${t.desc}</div>
            </div>
            <span style="font-size:16px;color:var(--text-dim);">←</span>
          </button>
        `).join('')}
      </div>
      <button class="dm-back" id="btn-back-target">${t('common.back')}</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:var(--text-primary);margin:0;">
          ${isHost ? t('room.waiting_friend') : t('room.challenge_from', { name: friendName || t('common.friend') })}
        </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:var(--gold);" id="lobby-msg">${isHost ? t('room.send_invite') : t('room.tap_accept')}</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;">${t('social.accept')}</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:var(--red-soft);">${t('common.cancel')}</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 = t('room.match_created');

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