/*! ratio-ui · design system for knowledge sharing · https://github.com/losol/ratio-ui · (c) 2026 Losol AS · MPL-2.0 */
import { useCallback, useEffect, useRef, useState } from "react";
//#region src/hooks/useCopyToClipboard.ts
/** Default lifetime of the post-copy "Copied" feedback. */
var DEFAULT_RESET_DELAY = 3e3;
/**
* Copy-to-clipboard with transient "copied" feedback. Prefers the async
* Clipboard API and falls back to a hidden-textarea + `execCommand` when it
* is unavailable or blocked (older browsers, insecure contexts). The `copied`
* flag auto-resets after `resetDelay`, and any pending reset is cleared on
* unmount.
*
* Shared by `CopyLabel`, `CodeBlock`, and any other copy affordance so the
* fallback path and reset timing live in one place.
*
* @beta This hook is experimental — its API may change before release.
*/
function useCopyToClipboard(options = {}) {
	const { resetDelay = DEFAULT_RESET_DELAY, onCopy } = options;
	const [copied, setCopied] = useState(false);
	const resetTimer = useRef(void 0);
	const onCopyRef = useRef(onCopy);
	useEffect(() => {
		onCopyRef.current = onCopy;
	}, [onCopy]);
	useEffect(() => () => clearTimeout(resetTimer.current), []);
	return {
		copied,
		copy: useCallback((value) => {
			const flagCopied = () => {
				setCopied(true);
				clearTimeout(resetTimer.current);
				resetTimer.current = setTimeout(() => setCopied(false), resetDelay);
				onCopyRef.current?.(value);
			};
			const copyViaTextarea = () => {
				const textarea = document.createElement("textarea");
				textarea.value = value;
				textarea.style.position = "fixed";
				textarea.style.opacity = "0";
				document.body.appendChild(textarea);
				try {
					textarea.select();
					return document.execCommand("copy");
				} catch {
					return false;
				} finally {
					textarea.remove();
				}
			};
			if (navigator.clipboard?.writeText) navigator.clipboard.writeText(value).then(flagCopied).catch(() => {
				if (copyViaTextarea()) flagCopied();
			});
			else if (copyViaTextarea()) flagCopied();
		}, [resetDelay])
	};
}
//#endregion
export { useCopyToClipboard };

//# sourceMappingURL=useCopyToClipboard.js.map