// Numbered or info tip badge — click/hover for glass tooltip
function InfoTip({ step, label, children, placement = "bottom" }) {
  const [open, setOpen] = React.useState(false);
  const [coords, setCoords] = React.useState({ left: 0, top: 0 });
  const btnRef = React.useRef(null);
  const tipRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (!btnRef.current?.contains(e.target) && !tipRef.current?.contains(e.target)) {
        setOpen(false);
      }
    };
    const esc = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", handler);
    document.addEventListener("keydown", esc);
    return () => {
      document.removeEventListener("mousedown", handler);
      document.removeEventListener("keydown", esc);
    };
  }, [open]);

  React.useLayoutEffect(() => {
    if (!open || !btnRef.current) return;
    const r = btnRef.current.getBoundingClientRect();
    const tipW = 260;
    const x = Math.max(12, Math.min(window.innerWidth - tipW - 12, r.left + r.width / 2 - tipW / 2));
    const y = placement === "top" ? r.top - 12 : r.bottom + 12;
    setCoords({ left: x, top: y });
  }, [open, placement]);

  const isStep = step != null;
  const ariaLabel = label || (isStep ? `Step ${step} info` : "Info");

  return (
    <>
      <button
        ref={btnRef}
        type="button"
        className={`infotip__btn ${isStep ? "infotip__btn--step" : ""} ${open ? "open" : ""}`}
        aria-label={ariaLabel}
        aria-expanded={open}
        onClick={(e) => {
          e.stopPropagation();
          setOpen(o => !o);
          if (navigator.vibrate) navigator.vibrate(5);
        }}
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={(e) => {
          // Don't close if pointer moved into the tooltip
          setTimeout(() => {
            if (!tipRef.current?.matches(":hover") && !btnRef.current?.matches(":hover")) {
              setOpen(false);
            }
          }, 80);
        }}
      >
        {isStep ? step : (
          <svg width="11" height="11" viewBox="0 0 11 11" aria-hidden>
            <circle cx="5.5" cy="5.5" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.1"/>
            <path d="M5.5 4.6 L5.5 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
            <circle cx="5.5" cy="3.3" r="0.7" fill="currentColor"/>
          </svg>
        )}
      </button>

      {open && ReactDOM.createPortal(
        <div
          ref={tipRef}
          className={`infotip__pop ${placement === "top" ? "above" : ""}`}
          style={{
            left: coords.left,
            top: coords.top,
            transform: placement === "top" ? "translateY(-100%)" : "none",
          }}
          onMouseLeave={() => setOpen(false)}
        >
          <div className="infotip__glass"></div>
          <div className="infotip__edge"></div>
          <div className="infotip__inner">
            {isStep && (
              <div className="infotip__step">
                <span className="infotip__step-num">{step}</span>
                <span className="infotip__step-of">of 4</span>
              </div>
            )}
            {label && <div className="infotip__title">{label}</div>}
            <div className="infotip__body">{children}</div>
          </div>
          <div className="infotip__arrow" aria-hidden></div>
        </div>,
        document.body
      )}
    </>
  );
}

window.InfoTip = InfoTip;
