// ============ Custom tooltip ============
// Native title= has a ~700ms delay and unstyled chrome. We need:
//  - 120ms show delay (feels instant, not nervous)
//  - immediate hide on mouseleave / scroll / click
//  - dark, rounded, max-width, with arrow
//  - position-aware (flip if would overflow)
//  - non-blocking (pointer-events: none)
//
// Usage:
//   <Tip text="Plain-English explanation">
//     <button>...</button>
//   </Tip>
//
// Or as a child wrapper that doesn't add a DOM node:
//   <Tip text="..." asChild>
//     <button>...</button>
//   </Tip>
const { useState: useTipState, useEffect: useTipEffect, useRef: useTipRef } = React;

const TIP_DELAY = 120;
const TIP_OFFSET = 10;

function Tip({ text, children, side = 'top', maxWidth = 260, inline = false }) {
  const ref = useTipRef(null);
  const timerRef = useTipRef(null);
  const [visible, setVisible] = useTipState(false);
  const [pos, setPos] = useTipState({ x: 0, y: 0, side: side });

  const compute = () => {
    const node = ref.current;
    if (!node) return;
    // If wrapper is display:contents (used inside grid layouts), its own
    // bounding rect is empty. Fall back to the first child element.
    let r = node.getBoundingClientRect();
    if (r.width === 0 && r.height === 0 && node.firstElementChild) {
      r = node.firstElementChild.getBoundingClientRect();
    }
    let s = side;
    let x = r.left + r.width / 2;
    let y = r.top - TIP_OFFSET;
    // Flip down if too close to top
    if (s === 'top' && r.top < 60) { s = 'bottom'; y = r.bottom + TIP_OFFSET; }
    if (s === 'bottom' && r.bottom > window.innerHeight - 60) { s = 'top'; y = r.top - TIP_OFFSET; }
    setPos({ x, y, side: s });
  };

  const onEnter = () => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      compute();
      setVisible(true);
    }, TIP_DELAY);
  };
  const onLeave = () => {
    if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
    setVisible(false);
  };
  useTipEffect(() => {
    if (!visible) return;
    const off = () => setVisible(false);
    window.addEventListener('scroll', off, true);
    window.addEventListener('wheel', off, true);
    window.addEventListener('pointerdown', off, true);
    return () => {
      window.removeEventListener('scroll', off, true);
      window.removeEventListener('wheel', off, true);
      window.removeEventListener('pointerdown', off, true);
    };
  }, [visible]);
  useTipEffect(() => () => { if (timerRef.current) clearTimeout(timerRef.current); }, []);

  return (
    <>
      <span
        ref={ref}
        className={inline ? 'tip-target tip-inline' : 'tip-target'}
        onMouseEnter={onEnter}
        onMouseLeave={onLeave}
        onFocus={onEnter}
        onBlur={onLeave}
      >{children}</span>
      {visible && text && ReactDOM.createPortal(
        <div
          className={`tip tip-${pos.side}`}
          style={{
            left: pos.x,
            top: pos.y,
            maxWidth,
          }}
          role="tooltip"
        >
          <div className="tip-body">{text}</div>
          <div className="tip-arrow" />
        </div>,
        document.body
      )}
    </>
  );
}

window.Tip = Tip;
