// Exercise 1: build a validating action (basics)
//
// `signupAction` should validate the submitted email/password and return a
// result object describing success or failure — WITHOUT throwing, so
// useActionState can carry the result as its `state` without extra error
// state. Wire it into `SignupForm` with useActionState.
//
// TODO 1: implement validateSignup (pure, no hooks)
// TODO 2: implement signupAction using validateSignup, matching the
//         (previousState, formData) => newState signature
// TODO 3: wire useActionState into SignupForm

import { useActionState } from "react";

interface SignupResult {
  success: boolean;
  message: string;
}

// TODO 1: return { success: false, message: "..." } if email doesn't
// include "@", or if password.length < 8. Otherwise return
// { success: true, message: "Account created!" }.
function validateSignup(email: string, password: string): SignupResult {
  return { success: true, message: "" }; // TODO: implement real validation
}

// TODO 2: implement the action. Signature MUST be
// (previousState: SignupResult | null, formData: FormData) => Promise<SignupResult>
// Read "email" and "password" off formData, call validateSignup.
async function signupAction(
  previousState: SignupResult | null,
  formData: FormData
): Promise<SignupResult> {
  return { success: true, message: "TODO: not implemented" };
}

function SignupForm() {
  // TODO 3: const [result, formAction, isPending] = useActionState(signupAction, null);
  const result: SignupResult | null = null;
  const formAction = undefined as unknown as (formData: FormData) => void;
  const isPending = false;

  return (
    <form action={formAction}>
      <input name="email" type="email" placeholder="email" />
      <input name="password" type="password" placeholder="password" />
      <button disabled={isPending}>{isPending ? "Creating..." : "Sign up"}</button>
      {result && (
        <p style={{ color: result.success ? "green" : "red" }}>{result.message}</p>
      )}
    </form>
  );
}

export { SignupForm, signupAction, validateSignup };

// --- self-check: do not modify below this line ---
const bad1 = validateSignup("not-an-email", "longenough1");
const check1 = bad1.success === false;

const bad2 = validateSignup("a@b.com", "short");
const check2 = bad2.success === false;

const good = validateSignup("a@b.com", "longenough1");
const check3 = good.success === true;

console.log(check1 ? "PASS (rejects bad email)" : "FAIL (rejects bad email)");
console.log(check2 ? "PASS (rejects short password)" : "FAIL (rejects short password)");
console.log(check3 ? "PASS (accepts valid signup)" : "FAIL (accepts valid signup)");

// Verify visually: mount <SignupForm />, submit with an invalid email —
// should show a red error message with isPending briefly true. Submit
// with valid values — should show a green success message.
