// Reusable tooltip — works on hover (desktop) and tap (mobile)
function Tooltip({ children, text, side = 'top' }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [open]);

  return (
    <span ref={ref} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}>
      <span
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={() => setOpen(false)}
        onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
        style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 16, height: 16, borderRadius: '50%',
          background: open ? 'var(--primary)' : 'color-mix(in oklab, var(--ink) 12%, transparent)',
          color: open ? 'var(--primary-ink)' : 'var(--ink-2)',
          fontSize: 10, fontWeight: 700, fontFamily: 'var(--mono)',
          cursor: 'help', transition: 'all .15s ease', userSelect: 'none',
          marginLeft: 6, verticalAlign: 'middle',
        }}
        aria-label={`Explicação: ${text}`}
      >?</span>
      {children}
      {open && (
        <span style={{
          position: 'absolute',
          [side]: 'calc(100% + 10px)',
          left: '50%', transform: 'translateX(-50%)',
          background: 'var(--ink)', color: 'var(--bg)',
          padding: '10px 14px', borderRadius: 10,
          fontSize: 12.5, lineHeight: 1.5, fontWeight: 400,
          width: 'max-content', maxWidth: 260,
          boxShadow: 'var(--shadow-lg)',
          zIndex: 50, fontFamily: 'var(--sans)',
          letterSpacing: 0,
          pointerEvents: 'none',
          textTransform: 'none',
        }}>
          {text}
          <span style={{
            position: 'absolute',
            [side === 'top' ? 'bottom' : 'top']: -4,
            left: '50%', transform: 'translateX(-50%) rotate(45deg)',
            width: 8, height: 8, background: 'var(--ink)',
          }} />
        </span>
      )}
    </span>
  );
}

window.Tooltip = Tooltip;
