// Chess Live Multiplayer — realtime game sync via Supabase
import * as realtime from '../../../core/realtime.js';
import * as net from '../../../core/net.js';
import * as store from '../../../core/store.js';

let unsubMatch = null;
let unsubQueue = null;
let matchId = null;
let onMoveReceived = null;
let onGameStateChange = null;
let lastMoveCount = 0;

export function startMatchmaking(gameKey, timeControl, callbacks) {
  const userId = store.get('auth.userId');

  unsubQueue = realtime.subscribeQueue(userId, (change) => {
    if (change.type === 'UPDATE' && change.new?.match_id) {
      stopMatchmaking();
      callbacks.onMatchFound({
        matchId: change.new.match_id,
        color: change.new.matched_with ? 'b' : 'w',
        opponentId: change.new.matched_with
      });
    }
  });

  return net.post('matchmaking.php', {
    action: 'queue',
    game_key: gameKey,
    time_control: timeControl
  });
}

export function stopMatchmaking() {
  if (unsubQueue) { unsubQueue(); unsubQueue = null; }
}

export function joinMatch(id, callbacks) {
  matchId = id;
  lastMoveCount = 0;
  onMoveReceived = callbacks.onMove;
  onGameStateChange = callbacks.onStateChange;

  realtime.connect();
  unsubMatch = realtime.subscribeMatch(id, (change) => {
    if (change.type === 'UPDATE' && change.new) {
      const match = change.new;
      if (match.move_count > lastMoveCount) {
        lastMoveCount = match.move_count;
        if (onMoveReceived) onMoveReceived(match);
      }
      if (match.status !== 'in_progress' && onGameStateChange) {
        onGameStateChange(match);
      }
    }
  });
}

export function leaveMatch() {
  if (unsubMatch) { unsubMatch(); unsubMatch = null; }
  matchId = null;
}

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

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

export async function sendDrawOffer() {
  if (!matchId) return;
  const gs = JSON.stringify({ draw_offer: store.get('auth.userId') });
  return net.post('game.php', { action: 'move', match_id: matchId, game_state: gs });
}

export async function sendEmote(emoteKey) {
  if (!matchId) return;
  const gs = JSON.stringify({ emote: { key: emoteKey, from: store.get('auth.userId'), t: Date.now() } });
  return net.post('game.php', { action: 'move', match_id: matchId, game_state: gs });
}

export function getMatchId() { return matchId; }
