// Match Live — glue between match-session (logic) and match-ui (visuals)
// Games import this ONE module to get full multiplayer edge case handling

import * as session from './match-session.js';
import * as ui from './match-ui.js';
import * as mp from './multiplayer.js';

export function start(matchId, gameType, options = {}) {
  const { onMove, onGameEnd } = options;

  let lastMoveCount = 0;
  let connectionLost = false;

  const sess = session.create(matchId, gameType, {
    onOpponentMove: (data) => {
      session.markOpponentActive();
      ui.hideOpponentThinking();

      if (connectionLost) {
        connectionLost = false;
        ui.showConnectionRestored();
      }

      // Always forward data so game can process resign/draw/state changes
      const moveCount = data.move_count || data.current_turn || 0;
      if (moveCount > lastMoveCount) {
        lastMoveCount = moveCount;
      }
      onMove?.(data);

      // Detect game ended externally
      if (data.status === 'completed') {
        onGameEnd?.(data);
      }

      // Check for opponent ping (they're still connected)
      if (data.game_state) {
        try {
          const gs = typeof data.game_state === 'string' ? JSON.parse(data.game_state) : data.game_state;
          if (gs.ping) session.markOpponentActive();
        } catch (e) {}
      }
    },

    onOpponentDisconnect: () => {
      ui.showOpponentDisconnect();
    },

    onOpponentReconnect: () => {
      ui.showOpponentReconnect();
    },

    onOpponentAbandon: () => {
      // Auto-win handled by UI (shows trophy + navigates back)
    },

    onConnectionLost: () => {
      connectionLost = true;
      ui.showConnectionLost();
    },

    onConnectionRestored: () => {
      if (connectionLost) {
        connectionLost = false;
        ui.showConnectionRestored();
      }
    }
  });

  return {
    session: sess,
    markOpponentActive: () => session.markOpponentActive(),
    showThinking: () => ui.showOpponentThinking(),
    hideThinking: () => ui.hideOpponentThinking(),
    showReconnecting: () => ui.showReconnecting(),
    toast: (msg, color) => ui.toast(msg, color),
    cleanup: () => { session.destroy(); ui.cleanup(); }
  };
}

export function recover() {
  const match = session.getRecoverableMatch();
  if (match) {
    ui.showReconnecting();
    return match;
  }
  return null;
}

export { session, ui };
