// Ludo 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 matchId = null;
let onUpdate = null;

export function joinMatch(id, callback) {
  matchId = id;
  onUpdate = callback;

  realtime.connect();
  unsubMatch = realtime.subscribeLudoMatch(id, (change) => {
    if (change.type === 'UPDATE' && change.new) {
      if (onUpdate) onUpdate(change.new);
    }
  });
}

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

export async function sendRoll(diceValue, positions, currentTurn, moves) {
  if (!matchId) return;
  return net.post('ludo.php', {
    action: 'move',
    match_id: matchId,
    positions: positions,
    current_turn: currentTurn,
    dice_value: diceValue,
    moves: moves
  });
}

export async function sendEnd(winners) {
  if (!matchId) return;
  return net.post('ludo.php', { action: 'end', match_id: matchId, winners });
}

export function getMatchId() { return matchId; }
