"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

// Small "!" help icon that reveals an explanation on hover / focus / tap.
// Used to explain what an indicator or field means.
export function InfoHint({
  text,
  className,
  side = "top",
}: {
  text: string;
  className?: string;
  side?: "top" | "bottom";
}) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef<HTMLSpanElement>(null);

  React.useEffect(() => {
    if (!open) return;
    function onDoc(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  return (
    <span ref={ref} className={cn("relative inline-flex align-middle", className)}>
      <button
        type="button"
        aria-label="More information"
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          setOpen((o) => !o);
        }}
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={() => setOpen(false)}
        onFocus={() => setOpen(true)}
        onBlur={() => setOpen(false)}
        className="inline-flex size-4 items-center justify-center rounded-full border border-muted-foreground/40 text-[10px] font-bold leading-none text-muted-foreground transition-colors hover:border-primary hover:bg-primary hover:text-primary-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
      >
        !
      </button>
      {open && (
        <span
          role="tooltip"
          className={cn(
            "absolute left-1/2 z-50 w-56 -translate-x-1/2 rounded-md border border-border bg-card px-3 py-2 text-left text-xs font-normal normal-case leading-relaxed text-card-foreground shadow-lg",
            side === "top" ? "bottom-full mb-1.5" : "top-full mt-1.5"
          )}
        >
          {text}
        </span>
      )}
    </span>
  );
}
