// Dropdown menu for adding a new cleaner-form field — picks the field kind.
function AddFieldMenu({ onAdd }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const close = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    setTimeout(() => document.addEventListener('click', close), 0);
    return () => document.removeEventListener('click', close);
  }, [open]);

  const options = [
    { kind: 'text', label: 'Short text', desc: 'Single line' },
    { kind: 'longtext', label: 'Long text', desc: 'Paragraph' },
    { kind: 'number', label: 'Number', desc: 'Count / quantity' },
    { kind: 'money', label: 'Dollar amount', desc: 'Logged on record' },
    { kind: 'yesno', label: 'Yes / No', desc: 'Binary' },
    { kind: 'photo', label: 'Photo upload', desc: 'Camera or gallery' },
    { kind: 'select', label: 'Dropdown', desc: 'Pick one option' },
    { kind: 'checklist', label: 'Checklist', desc: 'Multi-select (restock lists)' },
  ];

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="btn accent" onClick={() => setOpen(o => !o)}>
        {Icon.plus} Add field
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 10,
          width: 280, background: 'var(--bg-elev)', border: '1px solid var(--border)',
          borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.12)', padding: 6,
        }}>
          {options.map(o => (
            <button key={o.kind} onClick={() => { onAdd(o.kind); setOpen(false); }}
                    style={{
                      width: '100%', display: 'flex', alignItems: 'flex-start', gap: 10,
                      padding: '10px 12px', background: 'transparent', border: 0,
                      borderRadius: 6, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-sunken)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{
                width: 28, height: 28, borderRadius: 6, background: 'var(--bg-sunken)',
                display: 'grid', placeItems: 'center', flexShrink: 0, color: 'var(--text-secondary)',
              }}>
                <FieldKindIcon kind={o.kind}/>
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{o.label}</div>
                <div className="xs muted">{o.desc}</div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AddFieldMenu });
