// src/components/ui/RowActions.jsx
//
// Standard "Actions" button for the last column of every DataTable row.
// Opens a portal-based dropdown anchored to the button.
//
// Props:
//   actions  — array of { label, icon?, color?, onClick, divider? }
//              `divider: true` adds a separator line above the item
//   disabled — grey out and prevent opening

import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import Button from '@/components/ui/Button'

export default function RowActions({ actions = [], disabled = false, variant = 'table-actions', size = 'sm' }) {
  const [open, setOpen] = useState(false)
  const [pos, setPos]   = useState({ top: 0, right: 0 })
  const btnRef          = useRef(null)
  const menuRef         = useRef(null)

  // Close on any outside click or scroll
  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 (disabled) return
    if (!open && btnRef.current) {
      const r = btnRef.current.getBoundingClientRect()
      setPos({ top: r.bottom + 4, right: window.innerWidth - r.right })
    }
    setOpen((v) => !v)
  }

  return (
    <>
      <Button
        ref={btnRef}
        variant={variant}
        size={size}
        disabled={disabled}
        aria-haspopup="true"
        aria-expanded={open}
        aria-label="Row actions"
        onClick={handleToggle}
        iconRight={
          <svg
            width="11" height="11" viewBox="0 0 12 12"
            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' }}
          >
            <path d="M2 4l4 4 4-4" />
          </svg>
        }
      >
        Actions
      </Button>

      {open && createPortal(
        <div
          ref={menuRef}
          role="menu"
          className="row-actions-menu"
          style={{ position: 'fixed', top: pos.top, right: pos.right, zIndex: 9999 }}
        >
          {actions.map((action) => (
            <button
              key={action.label}
              role="menuitem"
              className="row-actions-item"
              style={{
                color:      action.color ?? 'var(--color-text-secondary)',
                borderTop:  action.divider ? '1px solid var(--color-border)' : 'none',
                marginTop:  action.divider ? 'var(--space-1)' : 0,
              }}
              onClick={(e) => {
                e.stopPropagation()
                setOpen(false)
                action.onClick?.()
              }}
            >
              {action.icon && <span className="row-actions-item-icon">{action.icon}</span>}
              {action.label}
            </button>
          ))}
        </div>,
        document.body
      )}
    </>
  )
}
