"use client";

import clsx from "clsx";
import type { FC } from "react";
import { Tooltip as ReactTooltip, type ITooltip } from "react-tooltip";
import styles from "./Tooltip.module.css";

/**
 * BEST PRACTICES:
 * - Tooltips are intended for interactive elements, and should not be used on non-interactive elements, such as divs, spans, p, etc.
 * - Tooltips should not be focusable, so you should not put interactive elements inside of them, such as links.
 * - https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Roles/tooltip_role
 *
 * USAGE REQUIREMENTS:
 * - The anchor element must have an `aria-describedby` attribute that is equivalent to the tooltip's ID.
 * - If you must put a tooltip on a non-interactive element, it must have a `tabIndex` attribute set to 0 so that it can be reached by
 * keyboard interaction. However, this still will not ensure that the tooltip will be read by screen readers. It is recommended to have a
 * secondary means for screen readers to access the tooltip information, such as a span with a "screen-reader-only" class and the tooltip
 * information inside of it.
 * - If you must put content that is clickable inside of the tooltip, the `clickable` prop must provided and set to true.
 **/

export interface TooltipProps extends ITooltip {
  id: string;
  "data-testid"?: string;
  disableStyleInjection?: "core" | undefined;
}

export const Tooltip: FC<TooltipProps> = ({
  id,
  "data-testid": testId,
  children,
  disableStyleInjection,
  ...props
}) => (
  <div className={styles.container} {...(testId && { "data-testid": testId })}>
    <ReactTooltip
      id={id}
      {...props}
      className={clsx([styles.tooltip, props.className])}
      disableStyleInjection={disableStyleInjection}
      globalCloseEvents={{ escape: true, clickOutsideAnchor: true }}
      closeEvents={{ mouseleave: true, blur: !props.clickable }}
    >
      {children}
    </ReactTooltip>
  </div>
);
