"use client";

import { createPortal } from "react-dom";
import { useState } from "react";

export function CursorTooltip({
  text,
  children,
  className = "",
}: {
  text: string;
  children: React.ReactNode;
  className?: string;
}) {
  const [point, setPoint] = useState({ x: 0, y: 0, visible: false });
  function move(event: React.PointerEvent<HTMLSpanElement>) {
    const maxX = Math.max(8, window.innerWidth - 244);
    const above = event.clientY > window.innerHeight - 70;
    setPoint({
      x: Math.min(event.clientX + 14, maxX),
      y: above ? event.clientY - 42 : event.clientY + 14,
      visible: true,
    });
  }
  return (
    <span
      className={className}
      onPointerEnter={move}
      onPointerMove={move}
      onPointerLeave={() => setPoint((value) => ({ ...value, visible: false }))}
    >
      {children}
      {point.visible && typeof document !== "undefined"
        ? createPortal(
            <span
              className="cursor-tooltip"
              style={{ left: point.x, top: point.y }}
            >
              {text}
            </span>,
            document.body,
          )
        : null}
    </span>
  );
}
