// tooltip.jsx — Win95-style yellow tooltip. Shows on hover (desktop) and
// 600ms long-press (touch). Wrap any element by passing `text` and the
// children. The tooltip is portal-free — positioned absolute relative to
// the wrapper — which keeps it inside the Win95 windowing flow without a
// portal, but it can be clipped if the parent has `overflow: hidden`. For
// elements inside such parents, prefer placing the wrapper outside the
// clipping container, or accept the truncation.
function Tooltip({ text, children, placement = 'bottom', delay = 350 }) {
  const [show, setShow] = React.useState(false);
  const timerRef = React.useRef(null);

  if (!text) return children;

  // Skip the wrapper entirely on coarse-pointer devices (phones / tablets).
  // Tooltips are a hover affordance — on touch they tend to flash on tap or
  // require a confusing long-press. Mobile gets the underlying control with
  // its own aria-label / title for screen readers.
  const isCoarse = typeof window !== 'undefined'
    && window.matchMedia
    && window.matchMedia('(pointer: coarse)').matches;
  if (isCoarse) return children;

  const open = () => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setShow(true), delay);
  };
  const close = () => {
    if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
    setShow(false);
  };

  const pos = {
    bottom: { top: '100%', left: '50%', transform: 'translate(-50%, 4px)' },
    top:    { bottom: '100%', left: '50%', transform: 'translate(-50%, -4px)' },
    right:  { top: '50%', left: '100%', transform: 'translate(4px, -50%)' },
    left:   { top: '50%', right: '100%', transform: 'translate(-4px, -50%)' },
  }[placement] || {};

  return (
    <span
      onMouseEnter={open}
      onMouseLeave={close}
      onFocus={open}
      onBlur={close}
      style={{ position: 'relative', display: 'inline-flex' }}>
      {children}
      {show && (
        <span style={{
          position: 'absolute', ...pos, zIndex: 99999,
          background: '#ffffe1', color: '#000',
          border: '1px solid #000',
          padding: '2px 6px', fontSize: 10, fontFamily: 'inherit',
          whiteSpace: 'nowrap', pointerEvents: 'none',
          boxShadow: '1px 1px 0 #888',
        }}>
          {text}
        </span>
      )}
    </span>
  );
}

window.Tooltip = Tooltip;
