import { useCallback, useEffect, useRef, useState, type MouseEvent } from "react";

/**
 * Clipboard write with a 2s "Copied!" indicator. Returns null-safe
 * callbacks so callers can pass `text === null` through unconditionally
 * (the hook still runs; the click handler short-circuits).
 */
export function useCopyFeedback(text: string | null): {
  copied: boolean;
  copy: (event: MouseEvent) => void;
} {
  const [copied, setCopied] = useState(false);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(
    () => () => {
      if (timerRef.current !== null) clearTimeout(timerRef.current);
    },
    [],
  );

  const copy = useCallback(
    (event: MouseEvent) => {
      event.stopPropagation();
      if (text === null) return;
      void window.navigator.clipboard.writeText(text).then(() => {
        setCopied(true);
        if (timerRef.current !== null) clearTimeout(timerRef.current);
        timerRef.current = setTimeout(() => setCopied(false), 2000);
      });
    },
    [text],
  );

  return { copied, copy };
}
