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

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-14 — Voyage                                            ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# Setup
SETUP=$(jse_get_async "
  const ex = game.actors.getName('TC-14 Test');
  if (ex) await ex.delete();
  const [actor] = await Actor.createDocuments([{type:'personnage', name:'TC-14 Test'}]);
  return { actorId: actor.id };
")
AID=$(eval_ok "$SETUP" actorId)

# ============================================================================
echo "--- TC-14-001: Dialogue Voyage ---"
# ============================================================================
R=$(jse_get_async "
  try {
    game.system.rdd.commands.onChatMessage('/voyage', {content: '/voyage', speaker: {alias: 'TC-14'}});
    await new Promise(r => setTimeout(r, 2000));
    const el = document.querySelector('[class*=fatigue-voyage], [class*=voyage], .dialog-fatigue-voyage');
    return { opened: !!el };
  } catch(e) { return {error: e.message}; }
")
OPENED=$(eval_ok "$R" opened)
ERR=$(eval_ok "$R" error)
[ "$OPENED" = "True" ] && pass "TC-14-001: dialog voyage ouvert" || fail "TC-14-001: KO ($ERR)"
# Close
jse_get_async "
  const apps = Object.values(ui.windows).filter(w => w.constructor?.name?.includes('Voyage') || w.constructor?.name?.includes('Fatigue'));
  for (const a of apps) await a.close();
  return 'closed';
" >/dev/null 2>&1

# Cleanup
jse_get_async "const a = game.actors.getName('TC-14 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