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

export interface TooltipTriggerProps extends JSX.HTMLAttributes<HTMLElement> {
  children?: JSX.Element;
}

/**
 * Element that triggers the Tooltip on hover/focus.
 * Renders as a `<span>` to allow wrapping any content.
 */
export function TooltipTrigger(props: TooltipTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "children",
    "onPointerEnter",
    "onPointerLeave",
    "onFocus",
    "onBlur",
  ]);
  const ctx = useInternalTooltipContext();

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

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

  const handleFocus: JSX.EventHandler<HTMLElement, FocusEvent> = (e) => {
    if (typeof local.onFocus === "function") local.onFocus(e);
    ctx.openDelayed();
  };

  const handleBlur: JSX.EventHandler<HTMLElement, FocusEvent> = (e) => {
    if (typeof local.onBlur === "function") local.onBlur(e);
    ctx.closeDelayed();
  };

  return (
    <span
      ref={(el) => ctx.setTriggerRef(el)}
      id={ctx.triggerId}
      aria-describedby={ctx.isOpen() ? ctx.contentId : undefined}
      data-state={ctx.isOpen() ? "open" : "closed"}
      onPointerEnter={handlePointerEnter}
      onPointerLeave={handlePointerLeave}
      onFocus={handleFocus}
      onBlur={handleBlur}
      {...rest}
    >
      {local.children}
    </span>
  );
}
