import { FloatingButton } from '../floating-button/floating-button.js'
import { FormstackForm } from '../formstack-form/formstack-form.js'
const { h, register, matter, preactHooks } = globalThis.ami
const { useState } = preactHooks
const { Popup, Button } = matter

const ICON_CLOSE = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<polygon fill="#595959" points="19.293 3.293 20.707 4.707 13.414 12 20.707 19.293 19.293 20.707 12 13.414 4.707 20.707 3.293 19.293 10.586 12 3.293 4.707 4.707 3.293 12 10.586"/>
</svg>`

const DEFAULTS = {
  BUTTON_TEXT: 'Feedback',
  CLOSE_TEXT: 'Close'
}

function SiteFeedback (props) {
  const {
    'button-text': buttonText = DEFAULTS.BUTTON_TEXT,
    'close-text': closeText = DEFAULTS.CLOSE_TEXT,
    'form-id': formId,
  } = props

  const [show, setShow] = useState(false)

  if (!formId) {
    return null
  }

  return [
    h(FloatingButton, { label: buttonText, onClick: () => setShow(true) }),
    h(Popup, { _show: show, _layout: 'center', 'aria-label': buttonText },
      h('div', { className: 'flex justify-end' },
        h(Button, {
          _variant: 'plain',
          _textless: true,
          _size: 'xs',
          _model: {
            icon: ICON_CLOSE,
            name: closeText
          },
          onClick: event => {
            event.preventDefault()
            setShow(false)
          }
        })
      ),
      h('div', {
        // Reset padding in the inner Box.
        _style: id => `${id} form > div { padding: 0 }`,
        children: h(FormstackForm, props)
      })
    )
  ]
}

register(SiteFeedback, 'site-feedback')
