import h from '../shared/h.js'
import useLink from '../shared/use-link.js'
import bubbleEvent from '../shared/bubble-event.js'

export function Form ({ action, onSubmit, ...props }) {
  const { href, onClick } = useLink({ href: action })

  return h('form', {
    ...props,
    className: undefined, // Suppress.
    action: href,
    onSubmit: event => {
      if (!event.composed && !onSubmit) {
        // Include data in the action URL.
        const { currentTarget: el } = event
        const data = new FormData(el)
        el.setAttribute('action', href + new URLSearchParams(data).toString())

        // Navigation handler.
        onClick?.(event)
      }

      bubbleEvent(event)

      if (!event.composed && onSubmit) {
        onSubmit(event)
      }
    }
  })
}
