import { Tooltip as T } from "radix-ui";
import type { ReactElement, ReactNode } from "react";
import { cn } from "./cn";

export const TipProvider = ({ children }: { children: ReactNode }) => (
  <T.Provider delayDuration={250} skipDelayDuration={150}>
    {children}
  </T.Provider>
);

/** A keycap chip: white on the dark tooltip, outlined on the page. */
export function Kbd({ children, onDark = false, className }: { children: ReactNode; onDark?: boolean; className?: string }) {
  return (
    <kbd
      className={cn(
        "inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full px-1.5 font-mono text-[11px] leading-none",
        onDark ? "bg-white text-tooltip" : "bg-page text-muted shadow-[inset_0_0_0_1px_var(--color-line)]",
        className,
      )}
    >
      {children}
    </kbd>
  );
}

/**
 * Dark tooltip with optional keycaps, for icon-only controls and the collapsed rail. Multiline wraps a
 * sentence or two; open holds it open (to say "Copied", say) until it is undefined again.
 */
export function Tip({
  label,
  keys,
  side = "top",
  children,
  disabled = false,
  multiline = false,
  open,
}: {
  label: ReactNode;
  keys?: string[];
  side?: "top" | "right" | "bottom" | "left";
  children: ReactElement;
  disabled?: boolean;
  multiline?: boolean;
  open?: boolean;
}) {
  if (disabled) return children;
  return (
    <T.Root open={open}>
      <T.Trigger asChild>{children}</T.Trigger>
      <T.Portal>
        <T.Content
          side={side}
          sideOffset={8}
          className={cn(
            "z-50 flex items-center gap-2.5 rounded-[5px] bg-tooltip px-3 text-[13px] text-white shadow-pop data-[state=closed]:opacity-0 data-[state=delayed-open]:animate-[context-tip_120ms_var(--ease-out-expo)]",
            multiline ? "max-w-[280px] py-2 leading-[18px]" : "h-8",
          )}
        >
          {label}
          {keys && keys.length > 0 && (
            <span className="flex gap-1">
              {keys.map((k) => (
                <Kbd key={k} onDark>
                  {k}
                </Kbd>
              ))}
            </span>
          )}
          <T.Arrow width={10} height={5} className="fill-tooltip" />
        </T.Content>
      </T.Portal>
    </T.Root>
  );
}
