import { useEffect } from "react"; import { useFormContext, useWatch } from "react-hook-form"; import { RotateCw } from "lucide-react"; import { useLocationTimeZone } from "../../hooks/useLocationTimeZone"; import { addressKey, lookupAddressOf } from "../../utils/locationTimeZoneCheck"; import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; type FormAddress = { line?: string[]; city?: string; state?: string; postalCode?: string } | undefined; const keyOf = (address: FormAddress) => { const parts = lookupAddressOf({ street: address?.line?.[0], city: address?.city, state: address?.state, postalCode: address?.postalCode, }); return parts ? addressKey(parts) : undefined; }; // The full editor's side of the 2026-09-23 ruling: a new or changed address sets the time zone from // the lookup, and the picker above stays the correction. An unchanged saved address is left alone. const AddressTimeZoneSync = () => { const { control, setValue, formState } = useFormContext(); const address = useWatch({ control, name: "address.0" }) as FormAddress; const savedKey = keyOf((formState.defaultValues?.address as FormAddress[] | undefined)?.[0]); const changed = keyOf(address) !== undefined && keyOf(address) !== savedKey; const timeZone = useLocationTimeZone( { street: address?.line?.[0], city: address?.city, state: address?.state, postalCode: address?.postalCode }, changed, ); const { check } = timeZone; useEffect(() => { if (check.state === "derived") setValue("timezone", check.timeZone, { shouldDirty: true }); }, [check, setValue]); if (!changed) return null; if (check.state === "checking") { return (
Looking up the time zone for this address
); } if (check.state === "derived") { return (
Set from the address. Change it above if it is wrong.
); } if (check.state === "ambiguous") { return
This address could be in more than one time zone. Check the time zone above.
; } if (check.state === "unverified") { return
We could not match this address, so its time zone was not looked up. Check it above.
; } if (check.state === "failed") { return (
The time zone could not be looked up just now. Check it above, or try again.
); } return null; }; export default AddressTimeZoneSync;