// Match Session Manager — handles ALL multiplayer edge cases
// Used by Chess, Ludo, Domino for consistent connection handling

import * as store from './store.js';
import * as net from './net.js';
import * as bus from './bus.js';

const PING_INTERVAL = 10000;      // Ping server every 10s to show "online"
const DISCONNECT_THRESHOLD = 30000; // Consider opponent disconnected after 30s
const ABANDON_THRESHOLD = 60000;    // Auto-win after 60s disconnect
const POLL_INTERVAL = 2000;         // Poll for opponent moves every 2s
const RECONNECT_GRACE = 5000;       // Wait 5s on page load before assuming fresh start

let currentSession = null;

export function create(matchId, gameType, options = {}) {
  destroy(); // Clean up any existing session

  currentSession = {
    matchId,
    gameType,               // 'chess' | 'ludo' | 'domino'
    myUserId: store.get('auth.userId'),
    lastServerPing: Date.now(),
    lastOpponentActivity: Date.now(),
    pollTimer: null,
    pingTimer: null,
    disconnectTimer: null,
    isActive: true,
    isBackground: false,
    onOpponentMove: options.onOpponentMove || null,
    onOpponentDisconnect: options.onOpponentDisconnect || null,
    onOpponentReconnect: options.onOpponentReconnect || null,
    onOpponentAbandon: options.onOpponentAbandon || null,
    onConnectionLost: options.onConnectionLost || null,
    onConnectionRestored: options.onConnectionRestored || null,
    opponentDisconnected: false
  };

  // Save match ID to localStorage for tab refresh recovery
  localStorage.setItem('el3ab_active_match', JSON.stringify({
    matchId, gameType, timestamp: Date.now()
  }));

  startPolling();
  startPinging();
  startDisconnectWatch();
  setupVisibilityHandler();

  return currentSession;
}

export function destroy() {
  if (!currentSession) return;
  currentSession.isActive = false;
  clearInterval(currentSession.pollTimer);
  clearInterval(currentSession.pingTimer);
  clearInterval(currentSession.disconnectTimer);
  localStorage.removeItem('el3ab_active_match');
  currentSession = null;
}

// Check if player has an active match to resume (after tab refresh)
export function getRecoverableMatch() {
  try {
    const saved = localStorage.getItem('el3ab_active_match');
    if (!saved) return null;
    const data = JSON.parse(saved);
    // Only recover if less than 5 minutes old
    if (Date.now() - data.timestamp > 300000) {
      localStorage.removeItem('el3ab_active_match');
      return null;
    }
    return data;
  } catch (e) { return null; }
}

// Record that opponent made an action (keeps disconnect timer alive)
export function markOpponentActive() {
  if (!currentSession) return;
  currentSession.lastOpponentActivity = Date.now();
  if (currentSession.opponentDisconnected) {
    currentSession.opponentDisconnected = false;
    currentSession.onOpponentReconnect?.();
  }
}

// ===== POLLING =====
function startPolling() {
  if (!currentSession) return;
  currentSession.pollTimer = setInterval(async () => {
    if (!currentSession || !currentSession.isActive) return;
    if (currentSession.isBackground) return; // Don't poll when tab is hidden

    try {
      const endpoint = currentSession.gameType === 'ludo' ? 'ludo-match.php' : 'game.php';
      const data = await net.post(endpoint, {
        action: 'get',
        match_id: currentSession.matchId
      });

      if (!data || data.error) return;

      // Connection is alive
      currentSession.lastServerPing = Date.now();
      currentSession.onConnectionRestored?.();

      // Notify about opponent's move
      currentSession.onOpponentMove?.(data);

    } catch (e) {
      // Network error
      if (Date.now() - currentSession.lastServerPing > 10000) {
        currentSession.onConnectionLost?.();
      }
    }
  }, POLL_INTERVAL);
}

// ===== PING (let server know we're still here) =====
function startPinging() {
  if (!currentSession) return;
  currentSession.pingTimer = setInterval(async () => {
    if (!currentSession || !currentSession.isActive) return;
    try {
      const endpoint = currentSession.gameType === 'ludo' ? 'ludo-match.php' : 'game.php';
      await net.post(endpoint, {
        action: 'move',
        match_id: currentSession.matchId,
        game_state: JSON.stringify({ ping: currentSession.myUserId, t: Date.now() })
      });
    } catch (e) {}
  }, PING_INTERVAL);
}

// ===== DISCONNECT DETECTION =====
function startDisconnectWatch() {
  if (!currentSession) return;
  currentSession.disconnectTimer = setInterval(() => {
    if (!currentSession || !currentSession.isActive) return;

    const elapsed = Date.now() - currentSession.lastOpponentActivity;

    if (elapsed > ABANDON_THRESHOLD && !currentSession.opponentDisconnected) {
      // Opponent abandoned — auto-claim win
      currentSession.onOpponentAbandon?.();
    } else if (elapsed > DISCONNECT_THRESHOLD && !currentSession.opponentDisconnected) {
      // Opponent disconnected but within grace period
      currentSession.opponentDisconnected = true;
      currentSession.onOpponentDisconnect?.();
    }
  }, 5000);
}

// ===== TAB VISIBILITY (handles tab switch/minimize) =====
function setupVisibilityHandler() {
  document.addEventListener('visibilitychange', () => {
    if (!currentSession) return;

    if (document.hidden) {
      // Tab went to background — pause expensive operations
      currentSession.isBackground = true;
    } else {
      // Tab came back — resume and immediately poll for updates
      currentSession.isBackground = false;
      currentSession.lastServerPing = Date.now(); // Reset so we don't false-disconnect

      // Immediately fetch latest state
      if (currentSession.onOpponentMove) {
        const endpoint = currentSession.gameType === 'ludo' ? 'ludo-match.php' : 'game.php';
        net.post(endpoint, { action: 'get', match_id: currentSession.matchId })
          .then(data => {
            if (data && !data.error) {
              currentSession.onOpponentMove(data);
              markOpponentActive();
            }
          })
          .catch(() => {});
      }
    }
  });
}

// ===== UTILITY =====
export function isConnected() {
  if (!currentSession) return false;
  return (Date.now() - currentSession.lastServerPing) < 15000;
}

export function isOpponentConnected() {
  if (!currentSession) return false;
  return !currentSession.opponentDisconnected;
}

export function getMatchId() {
  return currentSession?.matchId || null;
}

export function getSession() {
  return currentSession;
}
