import type { JSX } from "solid-js";
import { Show, splitProps } from "solid-js";
import { useInternalTooltipContext } from "./tooltip-context";

export interface TooltipContentProps extends JSX.HTMLAttributes<HTMLDivElement> {
  /** Keep mounted when closed. @default false */
  forceMount?: boolean | undefined;
  children?: JSX.Element;
}

/**
 * Floating content for Tooltip. Renders with `role="tooltip"` and
 * is positioned relative to the trigger via floating-ui.
 */
export function TooltipContent(props: TooltipContentProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "children",
    "forceMount",
    "onPointerEnter",
    "onPointerLeave",
  ]);
  const ctx = useInternalTooltipContext();

  const handlePointerEnter: JSX.EventHandler<HTMLDivElement, PointerEvent> = (e) => {
    if (typeof local.onPointerEnter === "function") local.onPointerEnter(e);
    ctx.cancelTimers();
  };

  const handlePointerLeave: JSX.EventHandler<HTMLDivElement, PointerEvent> = (e) => {
    if (typeof local.onPointerLeave === "function") local.onPointerLeave(e);
    ctx.closeDelayed();
  };

  return (
    <Show when={local.forceMount || ctx.isOpen()}>
      <div
        ref={(el) => ctx.setContentRef(el)}
        id={ctx.contentId}
        role="tooltip"
        data-state={ctx.isOpen() ? "open" : "closed"}
        style={ctx.floatingStyle()}
        onPointerEnter={handlePointerEnter}
        onPointerLeave={handlePointerLeave}
        {...rest}
      >
        {local.children}
      </div>
    </Show>
  );
}
