"use client";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useState } from "react";
import uuid from "react-uuid";
import { useEditContext } from "../client/editContext";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { Button } from "../../components/ui/button";
import { deleteComment, resolveComment, unresolveComment, createOrUpdateComment, } from "../services/reviewsService";
import { toast } from "sonner";
import { CommentView } from "./CommentView";
import { CommentEditor } from "./CommentEditor";
import { openAiAgentForComment } from "./commentAi";
import { LicenseFeatures, useFeature } from "../../licensing";
export function CommentDisplayPopover({ comment, children, onCommentUpdated, }) {
    const editContext = useEditContext();
    const [isOpen, setIsOpen] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [isReplying, setIsReplying] = useState(false);
    const canUseAi = useFeature(LicenseFeatures.AI);
    const [isSaving, setIsSaving] = useState(false);
    const [editText, setEditText] = useState(comment.text);
    const [deleteConfirm, setDeleteConfirm] = useState(false);
    const availableTags = editContext?.availableCommentTags || [];
    const contentRef = React.useRef(null);
    // Tags are now provided by editContext.availableCommentTags
    const canDelete = !comment.isNew &&
        (comment.author === editContext?.user?.name ||
            editContext?.user?.isAdministrator === true);
    const canEdit = !comment.isNew &&
        !comment.isResolved &&
        comment.author === editContext?.user?.name;
    const canResolve = !comment.isNew && !editContext?.readonly;
    const handleSave = async (text, tags) => {
        setIsSaving(true);
        try {
            const updatedComment = { ...comment, text, tags: tags.join(",") };
            const result = await createOrUpdateComment(updatedComment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to save comment:", result);
                toast.error(result.details || result.summary || "Failed to save comment");
                return;
            }
            setIsEditing(false);
            onCommentUpdated?.();
        }
        finally {
            setIsSaving(false);
        }
    };
    const handleCancel = () => {
        setIsEditing(false);
    };
    const handleDelete = async () => {
        await deleteComment(comment);
        setIsOpen(false);
        onCommentUpdated?.();
    };
    const handleResolve = async () => {
        await resolveComment(comment);
        onCommentUpdated?.();
    };
    const handleUnresolve = async () => {
        await unresolveComment(comment);
        onCommentUpdated?.();
    };
    const handleAiAction = () => openAiAgentForComment(comment, editContext);
    const handleReplySave = async (text, tags) => {
        if (!editContext?.currentItemDescriptor)
            return;
        setIsSaving(true);
        try {
            // Always set the immediate comment as the parent being replied to.
            const buildReplyFrom = (base, text, tags) => {
                const descriptor = editContext.currentItemDescriptor;
                return {
                    id: uuid(),
                    isNew: false,
                    parentCommentId: base.id,
                    itemId: base.itemId,
                    itemName: base.itemName,
                    fieldId: base.fieldId,
                    fieldName: base.fieldName,
                    mainItemId: base.mainItemId,
                    language: base.language || descriptor.language,
                    version: base.version || descriptor.version,
                    position: 0,
                    rangeStart: base.rangeStart,
                    rangeEnd: base.rangeEnd,
                    author: editContext?.user?.name,
                    authorDisplayName: editContext?.user?.fullName,
                    created: new Date().toISOString(),
                    text,
                    tags: tags.join(","),
                    fieldValue: base.fieldValue,
                };
            };
            const replyComment = buildReplyFrom(comment, text, tags);
            const result = await createOrUpdateComment(replyComment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to save reply comment:", result);
                toast.error(result.details || result.summary || "Failed to save reply comment");
                return;
            }
            setIsReplying(false);
            setIsOpen(false);
            onCommentUpdated?.();
            await editContext.loadComments?.();
        }
        finally {
            setIsSaving(false);
        }
    };
    const parentSnippet = comment.parentCommentId && editContext?.comments
        ? (() => {
            const parent = editContext.comments.find((c) => c.id === comment.parentCommentId);
            const source = parent?.text || "";
            const words = source
                .trim()
                .split(/\s+/)
                .filter((w) => w.length > 0)
                .slice(0, 3);
            return words.join(" ");
        })()
        : undefined;
    const handleEditorKeyDown = (e) => {
        if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
            e.preventDefault();
            // The editor will handle the save
        }
    };
    return (_jsxs(Popover, { open: isOpen, onOpenChange: (open) => {
            if (!open && isEditing && editText !== comment.text) {
                return;
            }
            setIsOpen(open);
            if (!open) {
                setDeleteConfirm(false);
                setIsEditing(false);
                setIsReplying(false);
                setEditText(comment.text);
            }
        }, enableIframeClickDetection: true, children: [_jsx(PopoverTrigger, { asChild: true, children: children }), _jsx(PopoverContent, { ref: contentRef, tabIndex: -1, className: "w-96 p-4", side: "bottom", align: "start", onOpenAutoFocus: (e) => {
                    e.preventDefault();
                    contentRef.current?.focus();
                }, onInteractOutside: (e) => {
                    const target = e.target;
                    if (target && target.closest('[data-slot="tooltip-content"]')) {
                        e.preventDefault();
                    }
                }, onPointerDownOutside: (e) => {
                    const target = e.target;
                    if (target && target.closest('[data-slot="tooltip-content"]')) {
                        e.preventDefault();
                    }
                }, onFocusOutside: (e) => {
                    const target = e.target;
                    if (target && target.closest('[data-slot="tooltip-content"]')) {
                        e.preventDefault();
                    }
                }, children: _jsx("div", { className: "space-y-3", children: !isEditing ? (_jsxs(_Fragment, { children: [_jsx(CommentView, { comment: comment, canEdit: canEdit, canDelete: canDelete, canResolve: canResolve, availableTags: availableTags, parentSnippet: parentSnippet, onEdit: () => setIsEditing(true), onDelete: handleDelete, onResolve: handleResolve, onUnresolve: handleUnresolve, onAiAction: canUseAi ? handleAiAction : undefined, onReply: !comment.isNew && !comment.isResolved && !editContext?.readonly
                                    ? () => setIsReplying((x) => !x)
                                    : undefined, compact: true }), isReplying && (_jsx("div", { className: "border-t pt-3", children: _jsx(CommentEditor, { onSave: handleReplySave, onCancel: () => setIsReplying(false), isSaving: isSaving, availableTags: availableTags, placeholder: "Write your reply...", submitLabel: "Reply", compact: true }) })), !editContext?.configuration?.forceFullscreen && (_jsx("div", { className: "border-t pt-3", children: _jsx(Button, { variant: "outline", size: "sm", onClick: () => {
                                        setIsOpen(false);
                                        // Exit fullscreen mode if active
                                        if (editContext?.fullscreen) {
                                            editContext.setFullscreen(false);
                                        }
                                        editContext?.toggleSidebar("feedback");
                                    }, className: "w-full", children: "View in Comments Panel" }) }))] })) : (_jsx(CommentEditor, { initialText: comment.text, onSave: handleSave, onCancel: handleCancel, isSaving: isSaving, availableTags: availableTags, selectedTags: [], placeholder: "Edit your comment...", submitLabel: "Save", compact: true, onKeyDown: handleEditorKeyDown })) }) })] }));
}
//# sourceMappingURL=CommentDisplayPopover.js.map