// Exercise 2: accumulating state across submissions (harder)
//
// A poll widget should keep a running vote tally across multiple button
// presses — each press is a separate "submission" whose action builds on
// the PREVIOUS tally, exactly like a reducer. This exercise tests whether
// you understand that useActionState threads state from one call to the
// next via the action's first parameter.
//
// TODO 1: implement applyVote (pure, no hooks) — the "reducer" logic
// TODO 2: implement voteAction using applyVote, respecting the
//         (previousState, formData) => newState signature
// TODO 3: wire useActionState into PollWidget, rendering both vote counts

import { useActionState } from "react";

interface Tally {
  yes: number;
  no: number;
}

// TODO 1: given the previous tally and a vote ("yes" | "no"), return a NEW
// tally object with the matching count incremented by 1. Do not mutate
// `previous`.
function applyVote(previous: Tally, vote: "yes" | "no"): Tally {
  return previous; // TODO: return a new object with the vote count +1
}

// TODO 2: read formData.get("vote") as "yes" | "no", call applyVote.
async function voteAction(previousState: Tally, formData: FormData): Promise<Tally> {
  return previousState; // TODO: implement using applyVote
}

function PollWidget() {
  // TODO 3: const [tally, formAction, isPending] = useActionState(voteAction, { yes: 0, no: 0 });
  const tally: Tally = { yes: 0, no: 0 };
  const formAction = undefined as unknown as (formData: FormData) => void;
  const isPending = false;

  return (
    <form action={formAction}>
      <p>
        Yes: {tally.yes} — No: {tally.no}
      </p>
      <button name="vote" value="yes" disabled={isPending}>
        Vote Yes
      </button>
      <button name="vote" value="no" disabled={isPending}>
        Vote No
      </button>
    </form>
  );
}

export { PollWidget, voteAction, applyVote };

// --- self-check: do not modify below this line ---
const t0: Tally = { yes: 0, no: 0 };
const t1 = applyVote(t0, "yes");
const check1 = t1.yes === 1 && t1.no === 0 && t0.yes === 0; // t0 must stay unmutated

const t2 = applyVote(t1, "no");
const check2 = t2.yes === 1 && t2.no === 1;

const t3 = applyVote(t2, "yes");
const check3 = t3.yes === 2 && t3.no === 1;

console.log(check1 ? "PASS (applyVote does not mutate, increments yes)" : "FAIL (applyVote yes/immutability)");
console.log(check2 ? "PASS (applyVote increments no, builds on previous)" : "FAIL (applyVote no)");
console.log(check3 ? "PASS (applyVote accumulates across calls)" : "FAIL (applyVote accumulation)");

// Verify visually: mount <PollWidget />, click "Vote Yes" three times and
// "Vote No" once. The displayed tally should read "Yes: 3 — No: 1",
// confirming each submission's previousState correctly carries forward.
