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

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   TC-12 — Calendrier / Temps                                ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

tc_ensure_ready

# ============================================================================
echo "--- TC-12-001: Calendrier visible ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const cal = game.system.rdd?.calendrier;
    if (!cal) return {error: 'no calendrier'};
    const el = document.querySelector('.calendar, #rdd-calendar, [class*=calendar]');
    const visible = el !== null && el.offsetParent !== null;
    return { exists: !!cal, visible, tag: el?.tagName };
  } catch(e) { return {error: e?.message || String(e)}; }
")
EXISTS=$(eval_ok "$R" exists)
ERR=$(eval_ok "$R" error)
[ "$EXISTS" = "True" ] && pass "TC-12-001: calendrier existe" || fail "TC-12-001: KO ($ERR)"

# ============================================================================
echo "--- TC-12-002: Heure Draconique ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const cal = game.system.rdd?.calendrier;
    if (!cal) return {error: 'no calendrier'};
    const timestamp = cal.timestamp || cal.getTimestamp?.();
    const heure = cal.dateCourante?.()?.getHeure?.() ?? cal.getCurrentHeure?.();
    const date = cal.dateCourante?.();
    return { heure, hasDate: !!date, timestamp };
  } catch(e) { return {error: e?.message || String(e)}; }
")
HEURE=$(eval_ok "$R" heure)
HASDATE=$(eval_ok "$R" hasDate)
ERR=$(eval_ok "$R" error)
[ "$HASDATE" = "True" ] && pass "TC-12-002: heure draconique = $HEURE" || fail "TC-12-002: KO ($ERR)"

# ============================================================================
echo "--- TC-12-003: Avancement du temps ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const cal = game.system.rdd?.calendrier;
    if (!cal) return {error: 'no calendrier'};
    const ts = cal.timestamp;
    const before = ts.indexDate + ':' + ts.indexMinute;
    const newTs = ts.addJours(1);
    if (cal.setNewTimestamp) await cal.setNewTimestamp(newTs);
    else if (cal.incrementerJour) await cal.incrementerJour();
    await new Promise(r => setTimeout(r, 500));
    const after = cal.timestamp.indexDate + ':' + cal.timestamp.indexMinute;
    const changed = before !== after;
    return { before, after, changed };
  } catch(e) { return {error: e?.message || String(e)}; }
")
CHANGED=$(eval_ok "$R" changed)
ERR=$(eval_ok "$R" error)
[ "$CHANGED" = "True" ] && pass "TC-12-003: temps avance" || fail "TC-12-003: KO ($ERR)"

# ============================================================================
echo "--- TC-12-004: Nombres Astraux ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const cal = game.system.rdd?.calendrier;
    if (!cal) return {error: 'no calendrier'};
    const na = cal.getNombresAstraux?.() ?? cal.nombresAstraux;
    return { hasNA: !!na, na: typeof na === 'object' ? JSON.stringify(na).substring(0, 200) : na };
  } catch(e) { return {error: e?.message || String(e)}; }
")
HASNA=$(eval_ok "$R" hasNA)
ERR=$(eval_ok "$R" error)
[ "$HASNA" = "True" ] && pass "TC-12-004: nombres astraux disponibles" || fail "TC-12-004: KO ($ERR)"

# ============================================================================
echo "--- TC-12-007: Chronologie ---"
# ============================================================================
R=$(jse_get_async "
  try {
    const { DialogChronologie } = await import('/systems/foundryvtt-reve-de-dragon/module/dialog-chronologie.js');
    if (!DialogChronologie) return {error: 'no DialogChronologie'};
    await DialogChronologie.create();
    await new Promise(r => setTimeout(r, 2000));
    const el = document.querySelector('.dialog-chronologie, [class*=chronolog]');
    const ok = !!el;
    // Close it
    const apps = Object.values(ui.windows).filter(w => w.constructor?.name?.includes('Chronolog'));
    for (const a of apps) await a.close();
    if (!apps.length && el) el.remove();
    return { opened: ok };
  } catch(e) { return {error: e?.message || String(e)}; }
")
OPENED=$(eval_ok "$R" opened)
ERR=$(eval_ok "$R" error)
[ "$OPENED" = "True" ] && pass "TC-12-007: chronologie ouverte" || fail "TC-12-007: KO ($ERR)"

# ============================================================================
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