"use client";

import { useEffect } from "react";
import { useFormikContext } from "formik";

import { type IndividualRegistrationValues } from "./individualRegistrationValues";

/**
 * Watches the date-of-birth field and tells the form whether the applicant is
 * a minor, which is what reveals the emergency-contact section.
 *
 * It renders nothing: it exists only so that reading `values.dob` through
 * Formik's context does not re-render the whole form on every keystroke in
 * every other field.
 */
export default function IndividualDobWatcher({
  setIsUnder18,
  calculateAge,
}: {
  setIsUnder18: (value: boolean) => void;
  calculateAge: (dob: string) => number | null;
}) {
  const { values } = useFormikContext<IndividualRegistrationValues>();

  useEffect(() => {
    if (values.dob) {
      const age = calculateAge(values.dob);
      setIsUnder18(age !== null && age < 18);
    } else {
      setIsUnder18(false);
    }
  }, [values.dob, calculateAge, setIsUnder18]);

  return null;
}
