"use client"; import { useEffect, useState } from "react"; import { useActionState } from "react"; import { CheckCircle2Icon, AlertCircleIcon, Loader2Icon } from "lucide-react"; import { sendTestAction, type SendTestResult } from "@/actions/groups"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Label } from "@/components/ui/label"; import { useEvents } from "@/hooks/use-events"; const initial: SendTestResult | null = null; type Outcome = | { kind: "idle" } | { kind: "in-flight"; message: string } | { kind: "sent"; message: string } | { kind: "error"; message: string }; export function SendTestForm({ groupId }: { groupId: string }) { const [state, formAction, isPending] = useActionState(sendTestAction, initial); const [outcome, setOutcome] = useState({ kind: "idle" }); // Bridge the optimistic action result into our richer Outcome state. // The action's `ok` only confirms the IPC NOTIFY was published — we // wait for the bot's `send_test.done` event below to know whether // WhatsApp actually accepted the message. useEffect(() => { if (!state) return; if (state.ok) { setOutcome({ kind: "in-flight", message: state.message }); } else { setOutcome({ kind: "error", message: state.error }); } }, [state]); // Subscribe to the bot's reply. Only act on events for OUR groupId so // a parallel send-test on another group doesn't move our state. useEvents({ "send_test.done": (data) => { if (data.groupId !== groupId) return; if (data.ok) { setOutcome({ kind: "sent", message: "Sent ✓" }); } else { setOutcome({ kind: "error", message: data.error ?? "Send failed — see bot logs for details.", }); } }, }); const sending = isPending || outcome.kind === "in-flight"; return (