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

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-19 — Tirage (FenetreRechercheTirage)                   ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# ============================================================================
echo "--- TC-19-001: Ouverture /tirage ---"
# ============================================================================
R=$(jse_get_async "
  try {
    game.system.rdd.commands.onChatMessage('/tirage', {content: '/tirage', speaker: {alias: 'TC-19'}});
    await new Promise(r => setTimeout(r, 2000));
    const el = document.querySelector('[class*=tirage], [class*=recherche-tirage], .fenetre-recherche-tirage');
    return { opened: !!el };
  } catch(e) { return {error: e.message}; }
")
OPENED=$(eval_ok "$R" opened)
ERR=$(eval_ok "$R" error)
[ "$OPENED" = "True" ] && pass "TC-19-001: fenêtre tirage ouverte" || fail "TC-19-001: KO ($ERR)"

# Close
jse_get_async "
  const apps = Object.values(ui.windows).filter(w => w.constructor?.name?.includes('Tirage') || w.constructor?.name?.includes('Recherche'));
  for (const a of apps) await a.close();
  return 'closed';
" >/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