import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import { Avatar } from "../../components/ui/avatar";
import { Button } from "../../components/ui/button";
import { MentionTextarea } from "../../components/ui/mention-textarea";
import { cn } from "../../lib/utils";
import { useEditContext } from "../client/editContext";
import { ArrowUp, X } from "lucide-react";
const COMMENT_TEXTAREA_MIN_HEIGHT = 32;
export const COMMENT_INPUT_PLACEHOLDER = "Add a comment and notify others with @";
export function CommentEditor({ editContext: externalEditContext, initialText = "", onSave, onCancel, isSaving = false, availableTags = [], selectedTags: initialSelectedTags = [], placeholder = COMMENT_INPUT_PLACEHOLDER, autoFocus = true, submitLabel = "Save", cancelLabel = "Cancel", showTagSelector = true, compact = false, showCancelButton = true, clearOnSave = false, onKeyDown, }) {
    const contextFromHook = useEditContext();
    const editContext = externalEditContext || contextFromHook;
    const [text, setText] = React.useState(initialText);
    const [selectedTags, setSelectedTags] = React.useState(initialSelectedTags);
    const textareaRef = React.useRef(null);
    const currentSession = editContext?.activeSessions.find((session) => session.sessionId === editContext?.sessionId);
    const currentUser = currentSession?.user ?? editContext?.user;
    const userName = currentUser?.fullName?.trim() || currentUser?.name?.trim() || "User";
    const avatarUrl = currentSession?.user.avatarUrl ?? editContext?.user?.avatarUrl;
    const avatarFallbackColor = currentSession?.color;
    const hasCommentText = text.trim().length > 0;
    const resizeTextarea = React.useCallback(() => {
        const textarea = textareaRef.current;
        if (!textarea)
            return;
        textarea.style.height = `${COMMENT_TEXTAREA_MIN_HEIGHT}px`;
        if (textarea.value.length === 0)
            return;
        textarea.style.height = `${Math.max(COMMENT_TEXTAREA_MIN_HEIGHT, textarea.scrollHeight)}px`;
    }, []);
    React.useEffect(() => {
        if (autoFocus && textareaRef.current) {
            // Focus after a longer delay to ensure the component is fully mounted, especially for dynamically created popovers
            const timer = setTimeout(() => {
                textareaRef.current?.focus();
                // Move cursor to end
                const len = textareaRef.current?.value.length || 0;
                textareaRef.current?.setSelectionRange(len, len);
            }, 200);
            return () => clearTimeout(timer);
        }
    }, [autoFocus]);
    React.useEffect(() => {
        resizeTextarea();
    }, [resizeTextarea, text]);
    const handleKeyDown = (e) => {
        // Call custom handler first if provided
        if (onKeyDown) {
            onKeyDown(e);
        }
        // Default behavior: Enter to submit (unless Shift is held)
        if (e.key === "Enter" && !e.shiftKey && !e.defaultPrevented) {
            e.preventDefault();
            handleSave();
        }
        // Escape to cancel
        else if (e.key === "Escape" && !e.defaultPrevented) {
            e.preventDefault();
            onCancel();
        }
    };
    const handleSave = async () => {
        const trimmedText = text.trim();
        if (trimmedText && !isSaving) {
            await onSave(trimmedText, selectedTags);
            if (clearOnSave) {
                setText("");
                setSelectedTags([]);
            }
        }
    };
    const handleTextChange = (value) => {
        setText(value);
        window.requestAnimationFrame(resizeTextarea);
    };
    return (_jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-start gap-3", children: [_jsx(Avatar, { src: avatarUrl, name: userName, size: "sm", fallbackColor: avatarFallbackColor, fallbackClassName: "bg-highlight-100 text-white", title: userName, className: "!text-[10px] font-medium" }), _jsxs("div", { className: cn("border-border-default focus-within:border-neutral-grey-15 flex flex-1 items-end overflow-hidden rounded-lg border bg-white p-2 transition-colors"), children: [_jsx(MentionTextarea, { ref: textareaRef, "data-testid": "add-comment-textarea", value: text, onValueChange: handleTextChange, onKeyDown: handleKeyDown, placeholder: placeholder, className: cn("text-neutral-grey-100 placeholder:text-neutral-grey-50 !field-sizing-fixed h-8 !min-h-8 flex-1 resize-none appearance-none overflow-hidden !rounded-none !border-0 !bg-transparent !p-0 text-sm leading-4 !shadow-none !transition-none !outline-none focus:!border-0 focus:!shadow-none focus:!ring-0 focus:!outline-none focus-visible:!border-0 focus-visible:!shadow-none focus-visible:!ring-0 focus-visible:!outline-none"), style: {
                                    backgroundColor: "transparent",
                                    border: "none",
                                    height: 32,
                                    boxShadow: "none",
                                    outline: "none",
                                }, rows: 1, disabled: isSaving, autoFocus: autoFocus }), _jsxs("div", { className: "flex shrink-0 items-end gap-1", children: [showCancelButton && (_jsx("button", { type: "button", onClick: onCancel, disabled: isSaving, className: "text-neutral-grey-100 hover:bg-neutral-grey-5 disabled:text-neutral-grey-50 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-white transition-colors", "data-testid": "add-comment-cancel", "aria-label": cancelLabel, title: cancelLabel, children: _jsx(X, { className: "h-4 w-4", strokeWidth: 1 }) })), hasCommentText && (_jsx("button", { type: "button", onClick: handleSave, disabled: isSaving, className: "bg-neutral-grey-100 hover:bg-neutral-grey-100/90 focus-visible:ring-neutral-grey-100/30 disabled:bg-neutral-grey-5 disabled:text-neutral-grey-50 disabled:hover:bg-neutral-grey-5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded text-white shadow-sm transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-default disabled:shadow-none", "data-testid": "add-comment-submit", "aria-label": isSaving ? "Saving comment" : submitLabel, title: isSaving ? "Saving..." : submitLabel, children: _jsx(ArrowUp, { className: "h-4 w-4", strokeWidth: 1 }) }))] })] })] }), showTagSelector && availableTags.length > 0 && (_jsxs("div", { className: "space-y-2", children: [_jsx("div", { className: "text-muted-foreground text-xs", children: "Tags" }), _jsx("div", { className: "flex flex-wrap gap-2", children: availableTags.map((tag) => {
                            const isSelected = selectedTags.includes(tag.label);
                            return (_jsx(Button, { type: "button", size: "sm", variant: isSelected ? "secondary" : "outline", className: "h-6 px-2 text-xs", onClick: () => {
                                    setSelectedTags((prev) => prev.includes(tag.label)
                                        ? prev.filter((l) => l !== tag.label)
                                        : [...prev, tag.label]);
                                }, style: {
                                    borderColor: isSelected ? tag.color : undefined,
                                    backgroundColor: isSelected ? tag.color + "22" : undefined,
                                }, disabled: isSaving, children: tag.label }, tag.label));
                        }) })] }))] }));
}
//# sourceMappingURL=CommentEditor.js.map