// Match UI — overlays and popups for all multiplayer edge cases
// Shows: disconnect warning, reconnecting spinner, opponent left, auto-win countdown, connection lost

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

let overlayEl = null;

function getOverlay() {
  if (!overlayEl) {
    overlayEl = document.createElement('div');
    overlayEl.id = 'match-overlay';
    overlayEl.style.cssText = 'position:fixed;inset:0;z-index:500;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,0.85);backdrop-filter:blur(4px);transition:opacity 0.3s;';
    document.body.appendChild(overlayEl);
  }
  return overlayEl;
}

function show(content) {
  const ov = getOverlay();
  ov.innerHTML = content;
  ov.style.display = 'flex';
  ov.style.opacity = '0';
  requestAnimationFrame(() => { ov.style.opacity = '1'; });
}

function hide() {
  const ov = getOverlay();
  ov.style.opacity = '0';
  setTimeout(() => { ov.style.display = 'none'; ov.innerHTML = ''; }, 300);
}

// ========== OPPONENT DISCONNECTED ==========
let abandonTimer = null;
let abandonSeconds = 60;

export function showOpponentDisconnect() {
  audio.play('notification');
  abandonSeconds = 60;

  show(`
    <div style="text-align:center;padding:32px;max-width:300px;">
      <div style="width:64px;height:64px;margin:0 auto 16px;border-radius:50%;background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;">
        <div style="width:16px;height:16px;border:3px solid var(--amber);border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;"></div>
      </div>
      <div style="font-size:18px;font-weight:700;color:var(--text-primary);margin-bottom:8px;">${t('match.disconnected_title')}</div>
      <div style="font-size:13px;color:var(--text-secondary);margin-bottom:16px;">${t('match.disconnected_waiting')}</div>
      <div id="abandon-countdown" style="font-size:32px;font-weight:800;color:var(--amber);font-family:Inter,monospace;margin-bottom:16px;">60</div>
      <div style="font-size:11px;color:var(--text-muted);">${t('match.disconnected_auto_win')}</div>
      <button id="claim-win-btn" style="margin-top:16px;padding:10px 24px;background:var(--gold);border:none;border-radius:8px;color:var(--bg-dark);font-weight:700;font-size:13px;cursor:pointer;opacity:0.5;pointer-events:none;">${t('match.claim_early_win')}</button>
    </div>
    <style>@keyframes spin { to { transform: rotate(360deg); } }</style>
  `);

  // Countdown timer
  abandonTimer = setInterval(() => {
    abandonSeconds--;
    const countEl = document.getElementById('abandon-countdown');
    if (countEl) countEl.textContent = String(abandonSeconds);

    // Enable claim button after 30s
    if (abandonSeconds <= 30) {
      const btn = document.getElementById('claim-win-btn');
      if (btn) { btn.style.opacity = '1'; btn.style.pointerEvents = 'auto'; }
    }

    if (abandonSeconds <= 0) {
      clearInterval(abandonTimer);
      showAutoWin();
    }
  }, 1000);

  // Claim win button
  setTimeout(() => {
    document.getElementById('claim-win-btn')?.addEventListener('click', () => {
      clearInterval(abandonTimer);
      showAutoWin();
    });
  }, 100);
}

// ========== OPPONENT RECONNECTED ==========
export function showOpponentReconnect() {
  clearInterval(abandonTimer);
  hide();

  // Brief toast
  showToast(t('match.opponent_returned'), 'var(--success)');
  audio.play('notification');
}

// ========== AUTO WIN (opponent abandoned) ==========
function showAutoWin() {
  clearInterval(abandonTimer);
  audio.play('win', 'reward');
  juice.hapticSuccess();
  juice.confetti(window.innerWidth / 2, window.innerHeight / 3, 30);

  show(`
    <div style="text-align:center;padding:32px;max-width:300px;">
      <div style="font-size:56px;margin-bottom:12px;animation:float 2s ease-in-out infinite;">${emoji('trophy', '🏆', 56)}</div>
      <div style="font-size:22px;font-weight:800;color:var(--success);margin-bottom:8px;">${t('match.you_won')}</div>
      <div style="font-size:14px;color:var(--text-secondary);margin-bottom:20px;">${t('match.opponent_left')}</div>
      <button id="abandon-back-btn" style="padding:12px 32px;background:linear-gradient(135deg,var(--gold),var(--gold-soft));border:none;border-radius:10px;color:var(--bg-dark);font-weight:700;font-size:15px;cursor:pointer;">${t('match.return')}</button>
    </div>
  `);

  setTimeout(() => {
    document.getElementById('abandon-back-btn')?.addEventListener('click', () => {
      hide();
      bus.emit('navigate', { world: 'play', scene: 'play-table' });
    });
  }, 100);

  // Emit win event for rating/coins
  bus.emit('game:ended', { result: 'win', reason: 'abandon' });
}

// ========== CONNECTION LOST (your own network) ==========
export function showConnectionLost() {
  show(`
    <div style="text-align:center;padding:32px;max-width:280px;">
      <div style="width:48px;height:48px;margin:0 auto 16px;border-radius:50%;background:var(--error);display:flex;align-items:center;justify-content:center;">
        <span style="font-size:24px;">${emoji('warning', '⚠️', 24)}</span>
      </div>
      <div style="font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:6px;">${t('match.connection_lost')}</div>
      <div style="font-size:13px;color:var(--text-secondary);">${t('match.reconnecting')}</div>
      <div style="margin-top:16px;">
        <div style="width:120px;height:4px;background:var(--bg-elevated);border-radius:2px;margin:0 auto;overflow:hidden;">
          <div style="width:30%;height:100%;background:var(--amber);border-radius:2px;animation:loading 1.5s ease-in-out infinite;"></div>
        </div>
      </div>
    </div>
    <style>@keyframes loading { 0% { transform:translateX(-100%); } 100% { transform:translateX(400%); } }</style>
  `);
}

// ========== CONNECTION RESTORED ==========
export function showConnectionRestored() {
  hide();
  showToast(t('match.reconnected'), 'var(--success)');
}

// ========== RECONNECTING (tab refresh recovery) ==========
export function showReconnecting() {
  show(`
    <div style="text-align:center;padding:32px;">
      <div style="width:48px;height:48px;margin:0 auto 16px;border:3px solid var(--gold);border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;"></div>
      <div style="font-size:16px;font-weight:700;color:var(--text-primary);">${t('match.restoring')}</div>
    </div>
    <style>@keyframes spin { to { transform: rotate(360deg); } }</style>
  `);
}

// ========== YOUR TURN REMINDER (if idle too long) ==========
export function showTurnReminder() {
  showToast(t('match.your_turn_warning'), 'var(--amber)');
  juice.hapticMedium();
}

// ========== OPPONENT THINKING ==========
export function showOpponentThinking() {
  const existing = document.getElementById('thinking-indicator');
  if (existing) return;

  const el = document.createElement('div');
  el.id = 'thinking-indicator';
  el.style.cssText = 'position:fixed;top:60px;left:50%;transform:translateX(-50%);background:rgba(30,30,58,0.95);padding:6px 14px;border-radius:20px;font-size:12px;color:var(--text-secondary);z-index:400;display:flex;align-items:center;gap:6px;border:1px solid var(--border);';
  el.innerHTML = `<div style="width:8px;height:8px;border:2px solid var(--text-secondary);border-top-color:transparent;border-radius:50%;animation:spin 0.8s linear infinite;"></div> ${t('match.opponent_thinking')}`;
  document.body.appendChild(el);
}

export function hideOpponentThinking() {
  document.getElementById('thinking-indicator')?.remove();
}

// ========== TOAST (brief notification) ==========
function showToast(message, color = 'var(--text-primary)') {
  const toast = document.createElement('div');
  toast.style.cssText = `position:fixed;top:70px;left:50%;transform:translateX(-50%);background:var(--bg-card);border:1px solid var(--border);padding:10px 20px;border-radius:12px;font-size:13px;font-weight:600;color:${color};z-index:600;box-shadow:0 4px 20px rgba(0,0,0,0.5);animation:toastIn 0.4s cubic-bezier(0.34,1.56,0.64,1);`;
  toast.textContent = message;
  document.body.appendChild(toast);
  setTimeout(() => {
    toast.style.animation = 'toastOut 0.2s ease-in forwards';
    setTimeout(() => toast.remove(), 200);
  }, 3000);
}

// ========== BOT REPLACEMENT ==========
export function showBotReplacement() {
  showToast(t('match.bot_replacement'), 'var(--amber)');
  juice.hapticLight();
}

// ========== TURN TIMED OUT ==========
export function showTurnTimedOut(isMyTimeout) {
  if (isMyTimeout) {
    showToast(t('match.your_time_expired'), 'var(--error)');
    juice.hapticMedium();
  } else {
    showToast(t('match.opponent_time_expired'), 'var(--success)');
    juice.hapticLight();
  }
}

// ========== CLEANUP ==========
export function cleanup() {
  hide();
  clearInterval(abandonTimer);
  hideOpponentThinking();
}

// ========== EXPORT TOAST FOR EXTERNAL USE ==========
export { showToast as toast };
