// frontend/src/components/ui/PillButton.jsx
// An interactive pill that looks like a StatusBadge but opens a dropdown.
// Sits inline with text/badges — same size and capsule shape.
//
// Props:
//   children  — current label
//   options   — Array<{ label: string, value: string }>
//   value     — currently selected value
//   onChange  — (value: string) => void
//   variant   — 'neutral'|'primary'|'success'|'warning'|'danger'|'info'  (default: 'neutral')
//   icon      — ReactNode — optional leading icon

import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'

export default function PillButton({
  children,
  options = [],
  value,
  onChange,
  variant = 'neutral',
  icon,
}) {
  const [open, setOpen] = useState(false)
  const [pos, setPos]   = useState({ top: 0, left: 0 })
  const btnRef          = useRef(null)
  const menuRef         = useRef(null)

  useEffect(() => {
    if (!open) return
    function onMouseDown(e) {
      if (btnRef.current?.contains(e.target))  return
      if (menuRef.current?.contains(e.target)) return
      setOpen(false)
    }
    function onScroll() { setOpen(false) }
    document.addEventListener('mousedown', onMouseDown)
    document.addEventListener('scroll', onScroll, true)
    return () => {
      document.removeEventListener('mousedown', onMouseDown)
      document.removeEventListener('scroll', onScroll, true)
    }
  }, [open])

  function handleToggle(e) {
    e.stopPropagation()
    if (!open && btnRef.current) {
      const r = btnRef.current.getBoundingClientRect()
      setPos({ top: r.bottom + 4, left: r.left })
    }
    setOpen((v) => !v)
  }

  function handleSelect(optValue) {
    setOpen(false)
    onChange?.(optValue)
  }

  return (
    <>
      <button
        ref={btnRef}
        type="button"
        className={`pill-btn pill-btn-${variant}`}
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={handleToggle}
      >
        {icon && <span className="pill-btn-icon" aria-hidden="true">{icon}</span>}
        <span>{children}</span>
        <svg
          width="8" height="8" viewBox="0 0 10 10"
          fill="none" stroke="currentColor" strokeWidth="1.75"
          strokeLinecap="round" strokeLinejoin="round"
          aria-hidden="true"
          style={{ transition: 'transform var(--transition-fast)', transform: open ? 'rotate(180deg)' : 'none', flexShrink: 0 }}
        >
          <path d="M2 3.5l3 3 3-3" />
        </svg>
      </button>

      {open && createPortal(
        <div
          ref={menuRef}
          role="listbox"
          className="pill-btn-menu"
          style={{ position: 'fixed', top: pos.top, left: pos.left, zIndex: 9999 }}
        >
          {options.map((opt) => (
            <button
              key={opt.value}
              role="option"
              aria-selected={opt.value === value}
              className={`pill-btn-option${opt.value === value ? ' pill-btn-option--active' : ''}`}
              onClick={(e) => { e.stopPropagation(); handleSelect(opt.value) }}
            >
              {opt.value === value && (
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              )}
              {opt.label}
            </button>
          ))}
        </div>,
        document.body
      )}
    </>
  )
}
