// Rôle : fournit une infobulle accessible et réutilisable pour les contrôles et données denses.
import { useEffect, useId, useRef, useState } from "react";
import { createPortal } from "react-dom";

export function Tooltip({ as: Component = "span", children, content, className = "", tooltipClassName = "", position = "top", ...props }) {
  const tooltipId = useId();
  const anchorRef = useRef(null);
  const [open, setOpen] = useState(false);
  const [style, setStyle] = useState({});

  function placeTooltip() {
    const anchor = anchorRef.current;
    if (!anchor) return;
    const rect = anchor.getBoundingClientRect();
    if (position === "top-start") {
      setStyle({ top: `${Math.max(8, rect.top - 8)}px`, left: `${Math.max(8, rect.left)}px` });
      return;
    }
    setStyle({ top: `${Math.max(8, rect.top - 8)}px`, left: `${Math.min(window.innerWidth - 8, Math.max(8, rect.left + rect.width / 2))}px` });
  }

  useEffect(() => {
    if (!open) return undefined;
    placeTooltip();
    window.addEventListener("resize", placeTooltip);
    window.addEventListener("scroll", placeTooltip, true);
    return () => {
      window.removeEventListener("resize", placeTooltip);
      window.removeEventListener("scroll", placeTooltip, true);
    };
  }, [open, position]);

  if (!content) return <Component className={className} {...props}>{children}</Component>;

  return (
    <Component
      {...props}
      className={`ui-tooltip-anchor ${className}`.trim()}
      ref={anchorRef}
      tabIndex={props.tabIndex ?? 0}
      aria-describedby={tooltipId}
      onMouseEnter={(event) => {
        placeTooltip();
        setOpen(true);
        props.onMouseEnter?.(event);
      }}
      onMouseLeave={(event) => {
        setOpen(false);
        props.onMouseLeave?.(event);
      }}
      onFocus={(event) => {
        placeTooltip();
        setOpen(true);
        props.onFocus?.(event);
      }}
      onBlur={(event) => {
        setOpen(false);
        props.onBlur?.(event);
      }}
    >
      {children}
      {open && createPortal(
        <span id={tooltipId} className={`ui-tooltip ui-tooltip-${position} ${tooltipClassName}`.trim()} role="tooltip" style={style}>
          {content}
        </span>,
        document.body
      )}
    </Component>
  );
}
