/**
 * BoostMedia AI Content Generator Admin - HelpTooltip Component
 *
 * A small (?) icon that shows a popover with explanation text on click.
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useState, useRef, useEffect } from 'react'
import { HelpCircle } from 'lucide-react'

interface HelpTooltipProps {
  text: string
  className?: string
}

export function HelpTooltip({ text, className = '' }: HelpTooltipProps) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!open) return
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  return (
    <div ref={ref} className={`relative inline-flex ${className}`}>
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="inline-flex items-center justify-center w-4 h-4 text-bc-gray-400 hover:text-bc-primary transition-colors cursor-pointer bg-transparent border-none p-0"
        aria-label="Help"
      >
        <HelpCircle className="w-4 h-4" />
      </button>
      {open && (
        <div className="absolute z-50 bottom-full mb-2 start-1/2 -translate-x-1/2 w-64 bg-bc-gray-800 text-white text-xs rounded-lg px-3 py-2 shadow-lg leading-relaxed">
          {text}
          <div className="absolute top-full start-1/2 -translate-x-1/2 w-0 h-0 border-x-[6px] border-x-transparent border-t-[6px] border-t-bc-gray-800" />
        </div>
      )}
    </div>
  )
}
