#!/usr/bin/env bash
# ============================================================================
# TC-11 — Combat
# Usage: ./tc-11-combat.sh [--navigate]
# ============================================================================
set -uo pipefail
source "$(dirname "$0")/tc-header.sh"

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-11 — Combat                                           ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# Setup
SETUP=$(jse_get_async "
  const ex = game.actors.getName('TC-11 Test');
  if (ex) await ex.delete();
  const [actor] = await Actor.createDocuments([{
    type: 'personnage', name: 'TC-11 Test',
    system: { carac: { force: {value: 12} }, sante: { vie: {value: 12, max: 12}, endurance: {value: 20, max: 20} } }
  }]);
  const [arme] = await actor.createEmbeddedDocuments('Item', [{
    type: 'arme', name: 'TC-11 Epee',
    system: { categorie: 'cac', degats: '3', competence: 'Mêlée', competence2: '', encombrement: 2, mains: 1 }
  }]);
  return { actorId: actor.id, armeId: arme?.id };
")
AID=$(eval_ok "$SETUP" actorId)

# ============================================================================
echo "--- TC-11-001: Création combat ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const { RdDCombat } = await import('/systems/foundryvtt-reve-de-dragon/module/combat/rdd-combat.js');
    return { hasCombat: !!RdDCombat, hasCreate: typeof RdDCombat.create === 'function' };
  } catch(e) { return {error: e.message}; }
")
HASC=$(eval_ok "$R" hasCombat)
ERR=$(eval_ok "$R" error)
[ "$HASC" = "True" ] && pass "TC-11-001: RdDCombat chargé" || fail "TC-11-001: KO ($ERR)"

# ============================================================================
echo "--- TC-11-002: Initiative — phases ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const { RdDInitiative } = await import('/systems/foundryvtt-reve-de-dragon/module/combat/initiative.mjs');
    return { hasInit: !!RdDInitiative, hasRoll: typeof RdDInitiative?.roll === 'function' };
  } catch(e) { return {error: e.message}; }
")
HASINIT=$(eval_ok "$R" hasInit)
ERR=$(eval_ok "$R" error)
[ "$HASINIT" = "True" ] && pass "TC-11-002: RdDInitiative chargé" || fail "TC-11-002: KO ($ERR)"

# Cleanup
jse_get_async "const a = game.actors.getName('TC-11 Test'); if (a) await a.delete(); return 'ok';" >/dev/null 2>&1

echo ""
echo "--- Console errors ---"
ERRS=$(tc_console_errors)
[ "$ERRS" -le 5 ] 2>/dev/null && pass "Console errors ≤5 ($ERRS)" || fail "Console errors: $ERRS"

tc_summary