const { h, preactHooks } = globalThis.ami
const { useState } = preactHooks

export function Rating ({ field }) {
  const [clicked, setClicked] = useState(false)

  const label = field.required === '1' ? `${field.label} *` : field.label
  return h('fieldset', { role: 'radiogroup', className: 'block' },
    h('legend', { id: `legend-${field.id}`, className: 'font-bold' }, label),
    h('div', {
      className: 'flex justify-start',
      children: Array.from({ length: field.count }, (_, ii) => {
        const index = ii + 1
        const id = `field_${field.id}_${index}`
        return [
          h('label', { className: 'sr-only', for: id }, index),
          h('input', {
            ...field.attrs,
            value: index,
            id,
            onClick: () => setClicked(true),
            type: 'radio',
            className: 'relative inline-block appearance-none w-8 h-8',
            'data-label': field.label,
            _style: styleId => `
              ${styleId}::before {
                cursor:pointer;
                position: absolute;
                display: flex;
                align-items: center;
                justify-content: center;
                color: hsl(var(--color-txa));
                opacity: ${clicked ? '1' : '0.2'};
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                content: "★";
                font-size: 28px;
                transition: opacity var(--anim-time);
                text-shadow: 0 0 2px hsl(var(--color-txa));
              }
              input:checked ~ input${styleId}::before {
                opacity: 0.2;
              }
            `
          })
        ]
      })
    }
    )
  )
}
