#!/usr/bin/env bash
# M10 nested-components test under quibble:
#   1. clicking the first child button raises its output through the parent
#      handler (stdout shows the running total),
#   2. the second button steps by five (its own props),
#   3. the reactive parent→child prop repaints the second button's label
#      (screenshots differ around a click of the *first* button, whose only
#      visible effects are the total line and the fives label),
#   4. idle renders zero frames.
set -euo pipefail
cd "$(dirname "$0")/.."

cargo build -p guiduck --example m10_panel

workdir=$(mktemp -d)
sock="$workdir/quibble.sock"
cleanup() {
    quibblectl --socket "$sock" quit >/dev/null 2>&1 || true
    rm -rf "$workdir"
}
trap cleanup EXIT

GUIDUCK_BACKEND=software GUIDUCK_TRACE_FRAMES=1 \
    quibble --socket "$sock" --width 480 --height 360 \
    target/debug/examples/m10_panel \
    >"$workdir/out.log" 2>"$workdir/err.log" &
for _ in $(seq 1 50); do
    quibblectl --socket "$sock" ping >/dev/null 2>&1 && break
    sleep 0.2
done
quibblectl --socket "$sock" wait-window --timeout-ms 30000 >/dev/null
sleep 1

frames() { grep -c '^guiduck-frame' "$workdir/err.log" || true; }
qc() { quibblectl --socket "$sock" "$@" >/dev/null; }
last_total() { grep '^total=' "$workdir/out.log" | tail -1; }
fail=0

# Layout (title 16px, padding 16, gap 12, rows 32 high): button centers.
ONES_X=81;  ONES_Y=63
FIVES_X=81; FIVES_Y=107

# 1: the ones button tallies through the parent's handler.
qc pointer-move $ONES_X $ONES_Y
qc click
sleep 0.3
v=$(last_total)
if [ "$v" = "total=1" ]; then
    echo "child output -> parent handler: $v"
else
    echo "FAIL: ones click; got '$v'" >&2; fail=1
fi

# 2: the fives button carries its own props.
qc pointer-move $FIVES_X $FIVES_Y
qc click
sleep 0.3
v=$(last_total)
if [ "$v" = "total=6" ]; then
    echo "per-instance props: $v"
else
    echo "FAIL: fives click; got '$v'" >&2; fail=1
fi

# 3: a ones click repaints the fives *label* (reactive parent→child prop).
#    Move the pointer off the fives button first so no hover change is in
#    the diff, then compare screenshots around the click.
qc pointer-move $ONES_X $ONES_Y
sleep 0.3
quibblectl --socket "$sock" screenshot -o "$workdir/before.png" >/dev/null
qc click
sleep 0.4
quibblectl --socket "$sock" screenshot -o "$workdir/after.png" >/dev/null
v=$(last_total)
if [ "$v" != "total=7" ]; then
    echo "FAIL: third click; got '$v'" >&2; fail=1
elif cmp -s "$workdir/before.png" "$workdir/after.png"; then
    echo "FAIL: reactive child prop did not repaint" >&2; fail=1
else
    echo "reactive parent->child prop: repainted at $v"
fi

# 4: idle.
q0=$(frames); sleep 3; q1=$(frames)
echo "idle frames: $q0 -> $q1"
[ "$q0" = "$q1" ] || { echo "FAIL: rendering while idle" >&2; fail=1; }

[ "$fail" -eq 0 ] && echo "M10 nested test PASSED"
exit $fail
