import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useRef, useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { ClipboardPaste } from "lucide-react";
export function PasteButton({ onPaste, duration = 2000, className, children, iconOnly = false, hideIfClipboardEmpty = false, isClipboardValid, "data-testid": dataTestId, }) {
    const [showPastedHint, setShowPastedHint] = useState(false);
    const buttonRef = useRef(null);
    const [clipboardText, setClipboardText] = useState();
    const [permissionState, setPermissionState] = useState("unknown");
    // Add keyframes to document head once (reuse same style id as copy button)
    useEffect(() => {
        const styleId = "copy-button-animations";
        if (document.getElementById(styleId))
            return;
        const style = document.createElement("style");
        style.id = styleId;
        style.textContent = `
      @keyframes shake {
        0%, 100% { transform: translateX(-50%) rotate(0deg); }
        10% { transform: translateX(-50%) rotate(-2deg) scale(1.05); }
        20% { transform: translateX(-50%) rotate(2deg) scale(1.1); }
        30% { transform: translateX(-50%) rotate(-2deg) scale(1.05); }
        40% { transform: translateX(-50%) rotate(2deg) scale(1.1); }
        50% { transform: translateX(-50%) rotate(-1deg) scale(1.02); }
        60% { transform: translateX(-50%) rotate(1deg) scale(1.02); }
        70% { transform: translateX(-50%) rotate(-1deg); }
        80% { transform: translateX(-50%) rotate(1deg); }
        90% { transform: translateX(-50%) rotate(0deg); }
      }
      @keyframes fadeOut {
        0% { opacity: 1; }
        70% { opacity: 1; }
        100% { opacity: 0; }
      }
    `;
        document.head.appendChild(style);
    }, []);
    // Check clipboard-read permission using the Permissions API
    useEffect(() => {
        let isActive = true;
        const checkPermission = async () => {
            try {
                // Check if Permissions API is available
                if (!navigator.permissions) {
                    // Permissions API not available, assume we can try
                    setPermissionState("unknown");
                    return;
                }
                const result = await navigator.permissions.query({
                    name: "clipboard-read",
                });
                if (!isActive)
                    return;
                setPermissionState(result.state);
                // Listen for permission changes
                const handleChange = () => {
                    if (isActive) {
                        setPermissionState(result.state);
                    }
                };
                result.addEventListener("change", handleChange);
                return () => result.removeEventListener("change", handleChange);
            }
            catch {
                // Permission query failed (e.g., clipboard-read not supported in Firefox)
                // Fall back to unknown - we'll try to read on click
                if (isActive) {
                    setPermissionState("unknown");
                }
            }
        };
        checkPermission();
        return () => {
            isActive = false;
        };
    }, []);
    // Only try to read clipboard on mount/focus if permission is granted
    // This avoids the "Read permission denied" error when permission is not granted
    useEffect(() => {
        if (!hideIfClipboardEmpty)
            return;
        // Don't try to read clipboard if permission is denied or we don't know
        if (permissionState !== "granted")
            return;
        let isActive = true;
        const tryReadClipboard = async () => {
            try {
                const text = await navigator.clipboard.readText();
                if (!isActive)
                    return;
                setClipboardText(text);
            }
            catch {
                // If we cannot read (permissions/gesture), leave as undefined (unknown)
                if (!isActive)
                    return;
                setClipboardText(undefined);
            }
        };
        tryReadClipboard();
        const onFocus = () => tryReadClipboard();
        const onVisibility = () => {
            if (document.visibilityState === "visible")
                tryReadClipboard();
        };
        window.addEventListener("focus", onFocus);
        document.addEventListener("visibilitychange", onVisibility);
        return () => {
            isActive = false;
            window.removeEventListener("focus", onFocus);
            document.removeEventListener("visibilitychange", onVisibility);
        };
    }, [hideIfClipboardEmpty, permissionState]);
    const handlePaste = async () => {
        try {
            const text = await navigator.clipboard.readText();
            // If we got here, permission was granted (user gesture allowed it)
            if (permissionState !== "granted") {
                setPermissionState("granted");
            }
            if (typeof isClipboardValid === "function" && !isClipboardValid(text)) {
                return;
            }
            await onPaste(text);
            setShowPastedHint(true);
            setTimeout(() => setShowPastedHint(false), duration);
        }
        catch (error) {
            // If reading fails, update permission state to hide the button
            // This handles the case where permission is denied at runtime
            if (error instanceof DOMException &&
                (error.name === "NotAllowedError" || error.name === "SecurityError")) {
                setPermissionState("denied");
            }
            console.error("Failed to paste from clipboard:", error);
        }
    };
    const Element = iconOnly ? "span" : "button";
    const defaultClassName = iconOnly
        ? "cursor-pointer"
        : "text-neutral-grey-100 flex cursor-pointer items-center gap-1 p-0 text-xs";
    const defaultChildren = iconOnly ? (_jsx(ClipboardPaste, { strokeWidth: 1, className: "h-3 w-3" })) : (_jsxs(_Fragment, { children: [_jsx(ClipboardPaste, { strokeWidth: 1, className: "h-3 w-3" }), " Paste"] }));
    // Hide the button if clipboard-read permission is denied
    // (This means the user has explicitly blocked clipboard access)
    if (permissionState === "denied") {
        return null;
    }
    const shouldRender = !hideIfClipboardEmpty
        ? true
        : clipboardText === undefined // unknown -> show
            ? true
            : (() => {
                const hasText = (clipboardText || "").trim().length > 0;
                if (!hasText)
                    return false;
                if (typeof isClipboardValid === "function") {
                    return isClipboardValid(clipboardText);
                }
                return true;
            })();
    return (_jsxs(_Fragment, { children: [shouldRender && (_jsx(Element, { ref: buttonRef, onClick: handlePaste, className: className || defaultClassName, "data-testid": dataTestId, children: children || defaultChildren })), showPastedHint &&
                buttonRef.current &&
                createPortal(_jsx("div", { className: "bg-neutral-grey-100 badge-pad pointer-events-none fixed z-[9999] rounded text-xs whitespace-nowrap text-white shadow-lg", style: {
                        animation: "shake 0.5s ease-in-out, fadeOut 2s ease-out forwards",
                        left: buttonRef.current.getBoundingClientRect().left +
                            buttonRef.current.offsetWidth / 2,
                        top: buttonRef.current.getBoundingClientRect().top - 32,
                        transform: "translateX(-50%)",
                    }, children: "Pasted!" }), document.body)] }));
}
//# sourceMappingURL=paste-button.js.map