import { useState, useSyncExternalStore } from "react";
import { PopoverSurface, useAnchoredPopover } from "./AnchoredPopover";
import { hintsEnabled, subscribeHints } from "../lib/hints";

type Side = "top" | "bottom";

/** Wrap any element to show a short glass hint caption on hover — but only while the
 *  app-wide hints toggle (Settings → Appearance) is on. Anchored by the R8 popover platform, so it
 *  is never clipped by an overflow/stacking ancestor, flips when the preferred side runs out of room
 *  and slides back inside the viewport near an edge. */
export default function Tooltip({
  hint,
  side = "top",
  children,
}: {
  hint: string;
  side?: Side;
  children: React.ReactNode;
}) {
  const enabled = useSyncExternalStore(subscribeHints, hintsEnabled, hintsEnabled);
  const [open, setOpen] = useState(false);
  const pop = useAnchoredPopover({
    open: open && enabled && !!hint,
    onOpenChange: setOpen,
    mode: "hover",
    placement: side,
    offset: 8,
    // Show/hide on contact, as the pre-platform tooltip did — the platform's 120/140 ms hover-intent
    // default suits interactive cards but makes a fast sweep across an icon row surface no hints.
    hoverDelay: { open: 0, close: 0 },
  });

  if (!enabled || !hint) return <>{children}</>;

  return (
    <>
      <span ref={pop.refs.setReference} {...pop.getReferenceProps()} className="inline-flex">
        {children}
      </span>
      {/* Passive caption: it must not swallow a click aimed at a neighbouring control that it
          overlaps while the hover-close delay runs out. */}
      <PopoverSurface
        popover={pop}
        passthrough
        className="glass w-max max-w-[240px] px-2.5 py-1.5 rounded-lg text-xs leading-snug text-fg font-normal normal-case tracking-normal animate-[fadeIn_0.12s_ease]"
      >
        {hint}
      </PopoverSurface>
    </>
  );
}
