// tdd-guard:skip — presentational tooltip (hover/tap open state); no pure logic to test in isolation
'use client'

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

interface Props {
  label: string
  formula: string
  example: string
  children: React.ReactNode
}

export default function FormulaTooltip({ label, formula, example, children }: Props) {
  const [open, setOpen] = useState(false)
  const rootRef = useRef<HTMLSpanElement>(null)

  // Touch has no mouseleave — close on any tap outside so the tooltip
  // can't get stuck open on iPad (KAR-708).
  useEffect(() => {
    if (!open) return
    const closeOnOutside = (e: PointerEvent) => {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('pointerdown', closeOnOutside)
    return () => document.removeEventListener('pointerdown', closeOnOutside)
  }, [open])

  return (
    <span
      ref={rootRef}
      className="relative inline-flex items-center gap-1 cursor-help"
      // Hover only for real mice — on touch, pointerenter + click both firing
      // per tap made the toggle cancel itself (open→closed within one tap).
      onPointerEnter={e => { if (e.pointerType === 'mouse') setOpen(true) }}
      onPointerLeave={e => { if (e.pointerType === 'mouse') setOpen(false) }}
      onClick={e => { e.stopPropagation(); setOpen(v => !v) }}
    >
      {children}
      <HelpCircle size={14} className="text-muted-foreground shrink-0 opacity-60" />
      {open && (
        <span className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 z-50 block w-[280px] bg-card border border-border rounded-md shadow-lg p-3 text-left pointer-events-none">
          <span className="block font-semibold text-sm text-foreground mb-1.5 leading-snug">
            {label}
          </span>
          <span className="block font-mono text-xs text-foreground bg-muted/50 rounded px-2 py-1 mb-1.5">
            {formula}
          </span>
          <span className="block text-xs text-muted-foreground leading-relaxed">
            {example}
          </span>
        </span>
      )}
    </span>
  )
}
