'use client'; import { useEffect, useRef, useState } from 'react'; import { METRIC_EXPLANATIONS } from '@/lib/metrics'; import styles from './MetricTooltip.module.css'; interface MetricTooltipProps { metricKey?: string; label?: string; plain?: string; detail?: string; } export function MetricTooltip({ metricKey, label, plain, detail }: MetricTooltipProps) { const explanation = metricKey ? METRIC_EXPLANATIONS[metricKey] : undefined; const tooltipLabel = label ?? explanation?.label; const tooltipPlain = plain ?? explanation?.plain; const tooltipDetail = detail ?? explanation?.detail; // Tap/click/keyboard toggle so the definition is reachable on touch devices // and by keyboard, not just mouse hover (hover still works on desktop). const [open, setOpen] = useState(false); const wrapperRef = useRef(null); useEffect(() => { if (!open) return; const dismiss = (e: Event) => { if (wrapperRef.current && e.target instanceof Node && !wrapperRef.current.contains(e.target)) { setOpen(false); } }; const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); }; document.addEventListener('click', dismiss); document.addEventListener('keydown', onKey); return () => { document.removeEventListener('click', dismiss); document.removeEventListener('keydown', onKey); }; }, [open]); if (!tooltipPlain) return null; return ( {tooltipLabel && {tooltipLabel}} {tooltipPlain} {tooltipDetail && {tooltipDetail}} ); }