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

let pollInterval = null;
let onMoveCallback = null;
let onDrawOfferCallback = null;
let lastMoveCount = 0;

export function startSync(matchId, callbacks) {
  onMoveCallback = callbacks.onMove;
  onDrawOfferCallback = callbacks.onDrawOffer;
  lastMoveCount = 0;

  pollInterval = setInterval(() => pollMatch(matchId), 2000);
}

export function stopSync() {
  if (pollInterval) {
    clearInterval(pollInterval);
    pollInterval = null;
  }
}

async function pollMatch(matchId) {
  try {
    const data = await net.get('game.php', { action: 'get', match_id: matchId });
    if (!data || data.error) return;

    if (data.move_count > lastMoveCount && data.current_fen) {
      lastMoveCount = data.move_count;
      if (onMoveCallback) onMoveCallback(data);
    }

    if (data.game_state?.draw_offer && onDrawOfferCallback) {
      const offer = data.game_state.draw_offer;
      if (offer.from !== store.get('auth.userId')) {
        onDrawOfferCallback(offer);
      }
    }
  } catch (e) {}
}

export async function sendMove(matchId, fen, move, moveCount) {
  return net.post('game.php', {
    action: 'move',
    match_id: matchId,
    fen,
    move: JSON.stringify(move),
    move_count: moveCount
  });
}

export async function sendDrawOffer(matchId) {
  return net.post('game.php', {
    action: 'draw_offer',
    match_id: matchId
  });
}

export async function acceptDraw(matchId) {
  return net.post('game.php', {
    action: 'complete',
    match_id: matchId,
    result: 'draw'
  });
}

export async function sendResign(matchId) {
  return net.post('game.php', {
    action: 'resign',
    match_id: matchId
  });
}

export async function requestRematch(matchId) {
  return net.post('game.php', {
    action: 'start',
    game_key: 'chess',
    mode: 'rematch',
    rematch_of: matchId
  });
}
