// Exercise 2: merging object state correctly
//
// Implement <ProfileForm />, which manages a single state object:
//   const [profile, setProfile] = useState({ name: "", email: "", age: 0 });
//
// Implement three handlers using the FUNCTIONAL updater form with a spread,
// so each only changes its own field without clobbering the others:
//   updateName(value: string)
//   updateEmail(value: string)
//   updateAge(value: number)
//
// Render three inputs bound to profile.name / profile.email / profile.age,
// each calling the matching updater onChange.

import { useState, type ReactElement } from "react";

type Profile = { name: string; email: string; age: number };

function ProfileForm(): ReactElement {
  const [profile, setProfile] = useState<Profile>({ name: "", email: "", age: 0 });

  function updateName(value: string) {
    // TODO: setProfile(prev => ({ ...prev, name: value }))
  }

  function updateEmail(value: string) {
    // TODO
  }

  function updateAge(value: number) {
    // TODO
  }

  return (
    <form>
      <input value={profile.name} onChange={(e) => updateName(e.target.value)} placeholder="name" />
      <input value={profile.email} onChange={(e) => updateEmail(e.target.value)} placeholder="email" />
      <input
        type="number"
        value={profile.age}
        onChange={(e) => updateAge(Number(e.target.value))}
        placeholder="age"
      />
    </form>
  );
}

export default ProfileForm;

// --- self-check: do not modify below this line ---
// (pure-logic re-implementation of the update rule, to verify the MERGE
// semantics independent of React's render cycle)
function mergeUpdate<T extends object>(prev: T, patch: Partial<T>): T {
  return { ...prev, ...patch };
}

let profile: Profile = { name: "Ana", email: "ana@x.com", age: 30 };
profile = mergeUpdate(profile, { age: 31 });
const ok = profile.name === "Ana" && profile.email === "ana@x.com" && profile.age === 31;
console.log("merge keeps other fields intact:", ok ? "PASS" : "FAIL");

// Visual verification: typing in any one input must NOT clear the other two
// — if it does, you replaced the whole object instead of merging.
