// Exercise 2: compose useActionState + useFormStatus
//
// Build a contact form using useActionState for the submit action (which
// simulates a network delay and returns a result message), with a nested
// SubmitButton that independently reads pending/data via useFormStatus to
// disable itself and show which email is currently being submitted.
//
// TODO 1: implement submitContact — the action function for useActionState
// TODO 2: wire up ContactForm using useActionState(submitContact, null)
// TODO 3: implement SubmitButton reading pending + data from useFormStatus

import { useActionState } from "react";
import { useFormStatus } from "react-dom";

type ActionState = { message: string } | null;

// TODO 1: pure-ish action function (still async, but no hidden component
// state) — read formData.get("email"), await a simulated 800ms delay, and
// return { message: `Thanks, ${email}!` }. Must NOT reference any hook.
async function submitContact(_prevState: ActionState, formData: FormData): Promise<ActionState> {
  const email = formData.get("email");
  return { message: "" }; // TODO: await the delay, then return the real message
}

// TODO 3: read { pending, data } from useFormStatus and render accordingly:
// disabled button, "Submitting: <email>..." while pending, "Send" otherwise.
function SubmitButton() {
  // TODO: const { pending, data } = useFormStatus();
  return <button>Send</button>;
}

// TODO 2: wire useActionState(submitContact, null) and render the result
// message once available.
function ContactForm() {
  // TODO: const [state, formAction] = useActionState(submitContact, null);
  return (
    <form>
      <input name="email" type="email" required />
      <SubmitButton />
      {/* TODO: render state?.message once implemented */}
    </form>
  );
}

export { ContactForm, SubmitButton, submitContact };

// --- self-check: do not modify below this line ---
// The action function is called directly here with a constructed FormData —
// no rendering involved, this tests the pure request/response contract.
async function runCheck() {
  const fd = new FormData();
  fd.set("email", "ana@example.com");
  const result = await submitContact(null, fd);
  const ok = result?.message === "Thanks, ana@example.com!";
  console.log(ok ? "PASS (submitContact returns the expected message)" : "FAIL (submitContact returns the expected message)");
}
runCheck();

// Verify visually: mount <ContactForm />, type an email, click Send. The
// button should disable and read "Submitting: <that email>..." for ~800ms
// (reading `data` from useFormStatus), then re-enable and the form should
// display "Thanks, <email>!" (from useActionState's returned state).
