import { useMemo, useRef, useLayoutEffect } from 'preact/hooks'
import h from '../shared/h.js'

const PADDINGS = { full: 3, center: 6, toast: 9 }
const LAYOUTS = {
  // Follow the page scroll behaviour for full width popups.
  full: 'm-0 w-full h-full overflow-y-scroll',
  toast: 'ml-0 mr-0 mb-0 mt-auto max-h-4/5 w-full overflow-y-scroll',
  center: 'm-auto rounded-xl w-128 h-fit'
}

export function Popup ({ _show, _layout = 'toast', _modal = true, children, ...props }) {
  const classes = LAYOUTS[_layout]
  const popupRef = useRef(null)
  const scrollbarWidth = useMemo(() => window.innerWidth - document.body.clientWidth, [])

  useLayoutEffect(() => {
    if (!popupRef?.current) {
      return
    }

    if (!_show) {
      popupRef?.current?.close?.()
      return
    }

    _modal ? popupRef?.current?.showModal?.() : popupRef?.current?.show?.()
  }, [_show, _modal, children])

  return [
    h('dialog', {
      ...props,
      ref: popupRef,
      className: `z-30 overscroll-none scrollbar-stable animate-toast shadow-lg bg-bga text-txa focus-visible:outline-none ${classes}`,
      // Limit max size on center popups to leave some space around when the viewport is too small.
      style: _layout === 'center' ? 'max-width: calc(100dvw - 12px); max-height: calc(100dvh - 12px)' : null,
      // Overlay style.
      _style: id => `${id}::backdrop { background: hsla(0, 0%, 0%, 0.5); backdrop-filter: blur(4px) }`,
      children: h('div', {
        className: `max-w-page m-auto space-y-5 w-full h-full p-${PADDINGS[_layout]}`,
        // Compensate for scrollbar in center layout.
        style: _layout === 'center' ? `padding-inline-end: ${24 - scrollbarWidth}px` : null,
        children
      })
    })
  ]
}
