"use client"
import { useEffect } from "react"
import { useFormContext } from "react-hook-form"

export default function AutoFillDetector() {
  const {
    formState: { dirtyFields, isDirty, touchedFields },
    trigger,
    watch,
  } = useFormContext()

  useEffect(() => {
    const dirtyFieldKeys = Object.keys(dirtyFields)
    const touchedFieldKeys = Object.keys(touchedFields)
    const hasDirtyUnTouchedFields = dirtyFieldKeys.some(
      (field) => !touchedFieldKeys.includes(field)
    )
    const subscription = watch((_, field) => {
      if (!field.type) {
        if (isDirty && hasDirtyUnTouchedFields) {
          trigger(field.name)
          trigger("countryCode")
        }
      }
    })

    return () => subscription.unsubscribe()
  }, [dirtyFields, isDirty, touchedFields, trigger, watch])

  return null
}
