import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useCallback } from "react";
import { SimpleToolbar } from "../ui/SimpleToolbar";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Button } from "../../components/ui/button";
import { Checkbox } from "../../components/ui/checkbox";
import { Check, X, Clock, Filter, Plus, MessageSquare, Lightbulb, Users, } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { formatDate } from "../utils";
import { Badge } from "../../components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { Loader2 } from "lucide-react";
import { ItemTreeSelector } from "./ItemTreeSelector";
import { useEditContext } from "../client/editContext";
import { cn } from "../../lib/utils";
import { getComments } from "../services/reviewsService";
import { getSuggestedEdits } from "../services/suggestedEditsService";
export function DecisionsMatrix({ items, assignments, onMakeDecision, loading, reviewId, language, finalDecision, onSetFinalDecision, onAddPages, onRemovePages, allReviewersResponded, selectedReviewerId, onSelectReviewer, currentUserEmail, requiredApprovals = 1, }) {
    const selectionKeySeparator = "|||";
    const toSelectionKey = (itemId, itemLanguage) => `${itemId}${selectionKeySeparator}${itemLanguage}`;
    const fromSelectionKey = (key) => {
        const separatorIndex = key.indexOf(selectionKeySeparator);
        if (separatorIndex === -1)
            return null;
        const itemId = key.slice(0, separatorIndex);
        const language = key.slice(separatorIndex + selectionKeySeparator.length);
        if (!itemId || !language)
            return null;
        return { itemId, language };
    };
    const [filter, setFilter] = useState("all");
    const [isAddPopoverOpen, setIsAddPopoverOpen] = useState(false);
    const [selectedItems, setSelectedItems] = useState([]);
    const [selectedPagesForRemoval, setSelectedPagesForRemoval] = useState(new Set());
    const editContext = useEditContext();
    const isLimitedPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
    const [commentsData, setCommentsData] = useState(new Map());
    const [suggestionsData, setSuggestionsData] = useState(new Map());
    const [loadingCounts, setLoadingCounts] = useState(false);
    const [itemDetailsCache, setItemDetailsCache] = useState(new Map());
    const [deletedItemKeys, setDeletedItemKeys] = useState(new Set());
    const currentItem = editContext?.currentItemDescriptor;
    const currentFullItem = editContext?.item; // FullItem has path and parentId
    // Filter assignments based on selection
    // For limited preview users, only show their own assignment
    const displayAssignments = (() => {
        let filtered = assignments;
        // If limited preview user, only show their own assignment
        if (isLimitedPreviewUser && currentUserEmail) {
            filtered = filtered.filter((a) => a.reviewerEmail.toLowerCase() === currentUserEmail.toLowerCase());
        }
        // Apply reviewer selection filter if specified
        if (selectedReviewerId) {
            filtered = filtered.filter((a) => a.assignmentId === selectedReviewerId);
        }
        return filtered;
    })();
    // Combine items from the original items list AND items that have decisions
    const allItemsWithDecisions = useMemo(() => {
        const itemsMap = new Map();
        // Add all original items
        items.forEach((item) => {
            const key = `${item.itemId}-${item.language}`;
            itemsMap.set(key, item);
        });
        // Add items from decisions that aren't already in the list
        assignments.forEach((assignment) => {
            assignment.decisions?.forEach((decision) => {
                const key = `${decision.itemId}-${decision.itemLanguage}`;
                if (!itemsMap.has(key)) {
                    // Check if we have cached details for this item
                    const cachedDetails = itemDetailsCache.get(key);
                    // Create a synthetic item entry for this decision
                    itemsMap.set(key, {
                        itemId: decision.itemId,
                        language: decision.itemLanguage,
                        includeSubitems: false,
                        name: cachedDetails?.name,
                        path: cachedDetails?.path,
                    });
                }
            });
        });
        return Array.from(itemsMap.values());
    }, [items, assignments, itemDetailsCache]);
    // Fetch item details for synthetic items that don't have names/paths
    useEffect(() => {
        const fetchItemDetails = async () => {
            if (!editContext?.itemsRepository)
                return;
            const itemsToFetch = [];
            // Find synthetic items that need details
            assignments.forEach((assignment) => {
                assignment.decisions?.forEach((decision) => {
                    const key = `${decision.itemId}-${decision.itemLanguage}`;
                    // Check if this item is not in the original items list
                    const isOriginalItem = items.some((item) => item.itemId === decision.itemId &&
                        item.language === decision.itemLanguage);
                    // Check if we already have cached details
                    const hasCachedDetails = itemDetailsCache.has(key);
                    // Only fetch if it's not an original item and we don't have cached details
                    if (!isOriginalItem && !hasCachedDetails) {
                        itemsToFetch.push({
                            key,
                            descriptor: {
                                id: decision.itemId,
                                language: decision.itemLanguage,
                                version: 0,
                            },
                        });
                    }
                });
            });
            if (itemsToFetch.length === 0)
                return;
            try {
                // Fetch items in batches
                const fetchedItems = await Promise.all(itemsToFetch.map(({ descriptor }) => editContext.itemsRepository.getItem(descriptor)));
                // Update cache with fetched details
                const newCache = new Map(itemDetailsCache);
                itemsToFetch.forEach(({ key }, index) => {
                    const fetchedItem = fetchedItems[index];
                    if (fetchedItem) {
                        newCache.set(key, {
                            name: fetchedItem.name,
                            path: fetchedItem.path,
                        });
                    }
                });
                if (newCache.size > itemDetailsCache.size) {
                    setItemDetailsCache(newCache);
                }
            }
            catch (err) {
                console.error("Failed to fetch item details:", err);
            }
        };
        fetchItemDetails();
    }, [assignments, items, itemDetailsCache, editContext?.itemsRepository]);
    const getDecision = (assignment, itemId, itemLanguage) => {
        return assignment.decisions?.find((d) => d.itemId === itemId && d.itemLanguage === itemLanguage);
    };
    const getLookupLanguage = useCallback((itemLanguage) => {
        if (itemLanguage === "*") {
            return currentItem?.language || "en";
        }
        return itemLanguage || "en";
    }, [currentItem?.language]);
    const isNotFoundError = (err) => {
        if (!err)
            return false;
        const message = err instanceof Error ? err.message : typeof err === "string" ? err : "";
        const normalized = message.toLowerCase();
        return (normalized.includes("not found") ||
            normalized.includes("404") ||
            normalized.includes("does not exist"));
    };
    // Calculate approval count for an item
    const getApprovalCount = (itemId, itemLanguage) => {
        return assignments.filter((assignment) => {
            const decision = getDecision(assignment, itemId, itemLanguage);
            return decision?.decision === "Approved";
        }).length;
    };
    // Get approval status for an item
    const getItemApprovalStatus = (itemId, itemLanguage) => {
        const approvalCount = getApprovalCount(itemId, itemLanguage);
        const rejectionCount = assignments.filter((assignment) => {
            const decision = getDecision(assignment, itemId, itemLanguage);
            return decision?.decision === "Rejected";
        }).length;
        const totalReviewers = assignments.length;
        const pendingCount = totalReviewers - approvalCount - rejectionCount;
        if (approvalCount >= requiredApprovals) {
            return "approved";
        }
        // If it's impossible to reach the threshold, mark as rejected
        if (approvalCount + pendingCount < requiredApprovals) {
            return "rejected";
        }
        return "pending";
    };
    const handleLoadItem = (itemId, itemLanguage) => {
        console.log("[DecisionsMatrix.handleLoadItem] Loading item from decisions matrix:", {
            itemId,
            itemLanguage,
            isLimitedPreviewUser,
            currentUserEmail,
            timestamp: new Date().toISOString(),
        });
        if (editContext?.loadItem) {
            // Handle "*" language (All Languages mode) - use default language
            const languageToLoad = itemLanguage === "*"
                ? editContext?.currentItemDescriptor?.language || "en"
                : itemLanguage;
            editContext.loadItem({
                id: itemId,
                language: languageToLoad,
                version: 0,
            });
        }
        else {
            console.error("[DecisionsMatrix.handleLoadItem] editContext.loadItem is not available");
        }
    };
    const getDecisionCell = (assignment, item) => {
        const decision = getDecision(assignment, item.itemId, item.language);
        if (decision) {
            if (decision.decision === "Approved") {
                return (_jsx("div", { className: "flex items-center justify-center p-1", children: _jsxs("div", { className: "flex flex-col items-center gap-0.5", children: [_jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Check, { className: "text-feedback-green h-3.5 w-3.5" }), _jsx("span", { className: "text-neutral-grey-50 text-xs leading-tight", children: formatDate(new Date(decision.decisionDate)) })] }), decision.itemVersion !== undefined && (_jsxs("span", { className: "text-neutral-grey-50 text-xs leading-tight", children: ["v", decision.itemVersion] }))] }) }));
            }
            else {
                return (_jsx("div", { className: "flex items-center justify-center p-1", children: _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(X, { className: "text-feedback-red h-3.5 w-3.5" }), _jsx("span", { className: "text-neutral-grey-50 text-xs leading-tight", children: formatDate(new Date(decision.decisionDate)) })] }) }));
            }
        }
        // Show pending indicator
        return (_jsx("div", { className: "flex items-center justify-center p-1", children: _jsx(Clock, { className: "text-neutral-grey-50 h-3.5 w-3.5" }) }));
    };
    const filteredItems = allItemsWithDecisions.filter((item) => {
        if (filter === "all")
            return true;
        if (filter === "pending") {
            return displayAssignments.some((a) => !getDecision(a, item.itemId, item.language));
        }
        if (filter === "rejected") {
            return displayAssignments.some((a) => getDecision(a, item.itemId, item.language)?.decision === "Rejected");
        }
        if (filter === "approved") {
            return displayAssignments.every((a) => getDecision(a, item.itemId, item.language)?.decision === "Approved");
        }
        return true;
    });
    const handleMakeDecision = async (assignmentId, itemId, itemLanguage, decision) => {
        // Try to get the version of the item being decided on
        let itemVersion = undefined;
        // First, check if the current item matches and has a real version (not 0 which means "latest")
        const currentItem = editContext?.currentItemDescriptor;
        if (currentItem &&
            currentItem.id === itemId &&
            (currentItem.language === itemLanguage ||
                itemLanguage === "*" ||
                currentItem.language === "*") &&
            currentItem.version !== 0) {
            itemVersion = currentItem.version;
        }
        else {
            // Try to fetch the item to get its actual version
            if (editContext?.itemsRepository) {
                try {
                    const item = await editContext.itemsRepository.getItem({
                        id: itemId,
                        language: itemLanguage === "*" ? "en" : itemLanguage,
                        version: 0, // Get latest version
                    });
                    if (item) {
                        itemVersion = item.version;
                    }
                }
                catch (err) {
                    console.warn(`Failed to fetch item version for ${itemId}:`, err);
                    // Continue with undefined version (version-null decision)
                }
            }
        }
        await onMakeDecision(assignmentId, itemId, itemLanguage, itemVersion, decision);
    };
    const handleApproveCurrentPage = async () => {
        const currentItem = editContext?.currentItemDescriptor;
        if (!currentItem || !currentUserEmail)
            return;
        // Find current user's assignment
        const userAssignment = assignments.find((a) => a.reviewerEmail.toLowerCase() === currentUserEmail.toLowerCase());
        if (!userAssignment)
            return;
        await handleMakeDecision(userAssignment.assignmentId, currentItem.id, currentItem.language || "en", "Approved");
    };
    const handleRejectCurrentPage = async () => {
        const currentItem = editContext?.currentItemDescriptor;
        if (!currentItem || !currentUserEmail)
            return;
        // Find current user's assignment
        const userAssignment = assignments.find((a) => a.reviewerEmail.toLowerCase() === currentUserEmail.toLowerCase());
        if (!userAssignment)
            return;
        await handleMakeDecision(userAssignment.assignmentId, currentItem.id, currentItem.language || "en", "Rejected");
    };
    const handleItemsChange = (descriptors) => {
        setSelectedItems(descriptors);
    };
    const handleAddSelectedPages = async () => {
        if (selectedItems.length > 0) {
            const itemsToAdd = selectedItems.map((desc) => ({
                descriptor: desc,
                includeSubitems: false,
            }));
            await onAddPages(itemsToAdd);
            setSelectedItems([]);
            setIsAddPopoverOpen(false);
        }
    };
    const handleRemovePage = async (itemId, itemLanguage) => {
        const item = allItemsWithDecisions.find((i) => i.itemId === itemId && i.language === itemLanguage);
        const itemName = item?.name || item?.path || itemId;
        editContext?.confirm({
            header: "Remove Page",
            message: `Are you sure you want to remove "${itemName}" from this review?`,
            acceptLabel: "Remove",
            showCancel: true,
            accept: async () => {
                await onRemovePages([
                    {
                        id: itemId,
                        language: itemLanguage,
                        version: 0,
                    },
                ]);
            },
        });
    };
    const togglePageSelection = (itemId, language) => {
        const key = toSelectionKey(itemId, language);
        const newSelection = new Set(selectedPagesForRemoval);
        if (newSelection.has(key)) {
            newSelection.delete(key);
        }
        else {
            newSelection.add(key);
        }
        setSelectedPagesForRemoval(newSelection);
    };
    const handleRemoveSelectedPages = async () => {
        if (selectedPagesForRemoval.size === 0)
            return;
        const pagesToRemove = Array.from(selectedPagesForRemoval)
            .map((key) => fromSelectionKey(key))
            .filter((parsed) => !!parsed);
        const itemDescriptors = pagesToRemove.map(({ itemId, language }) => ({
            id: itemId,
            language: language,
            version: 0,
        }));
        const pageNames = pagesToRemove.map(({ itemId, language }) => {
            const item = allItemsWithDecisions.find((i) => i.itemId === itemId && i.language === language);
            return item?.name || item?.path || itemId;
        });
        const message = selectedPagesForRemoval.size === 1
            ? `Are you sure you want to remove "${pageNames[0]}" from this review?`
            : `Are you sure you want to remove ${selectedPagesForRemoval.size} pages from this review?`;
        editContext?.confirm({
            header: "Remove Pages",
            message,
            acceptLabel: "Remove",
            showCancel: true,
            accept: async () => {
                await onRemovePages(itemDescriptors);
                setSelectedPagesForRemoval(new Set());
            },
        });
    };
    const hasSelectedPages = selectedPagesForRemoval.size > 0;
    // Helper function to refresh counts for a specific item
    const refreshItemCounts = useCallback(async (itemId, itemLanguage) => {
        const key = `${itemId}-${itemLanguage}`;
        // Check if this item is in our review
        const itemInReview = allItemsWithDecisions.some((item) => item.itemId === itemId &&
            (item.language === itemLanguage ||
                item.language === "*" ||
                itemLanguage === "*"));
        if (!itemInReview) {
            return;
        }
        try {
            // Fetch updated comments
            const commentsResult = await getComments(itemId, itemLanguage === "*" ? "en" : itemLanguage, 0, reviewId);
            if (commentsResult.data) {
                setCommentsData((prev) => {
                    const newMap = new Map(prev);
                    newMap.set(key, commentsResult.data);
                    return newMap;
                });
            }
            // Fetch updated suggestions
            const suggestionsResult = await getSuggestedEdits(itemId, itemLanguage === "*" ? "en" : itemLanguage, 0, reviewId);
            if (suggestionsResult.data) {
                setSuggestionsData((prev) => {
                    const newMap = new Map(prev);
                    newMap.set(key, suggestionsResult.data);
                    return newMap;
                });
            }
        }
        catch (err) {
            console.error(`Failed to refresh counts for ${key}:`, err);
        }
    }, [allItemsWithDecisions, reviewId]);
    // Fetch comments and suggestions for all items
    useEffect(() => {
        const fetchCounts = async () => {
            if (allItemsWithDecisions.length === 0) {
                setCommentsData(new Map());
                setSuggestionsData(new Map());
                return;
            }
            setLoadingCounts(true);
            const commentsMap = new Map();
            const suggestionsMap = new Map();
            try {
                await Promise.all(allItemsWithDecisions.map(async (item) => {
                    const key = `${item.itemId}-${item.language}`;
                    // Fetch comments (using version 0 as default, or we could track version)
                    // Pass reviewId to filter server-side by review creation date
                    try {
                        const commentsResult = await getComments(item.itemId, item.language, 0, reviewId);
                        if (commentsResult.data) {
                            commentsMap.set(key, commentsResult.data);
                        }
                    }
                    catch (err) {
                        console.error(`Failed to fetch comments for ${key}:`, err);
                    }
                    // Fetch suggestions
                    // Pass reviewId to filter server-side by review creation date
                    try {
                        const suggestionsResult = await getSuggestedEdits(item.itemId, item.language, 0, reviewId);
                        if (suggestionsResult.data) {
                            suggestionsMap.set(key, suggestionsResult.data);
                        }
                    }
                    catch (err) {
                        console.error(`Failed to fetch suggestions for ${key}:`, err);
                    }
                }));
                setCommentsData(commentsMap);
                setSuggestionsData(suggestionsMap);
            }
            catch (err) {
                console.error("Failed to fetch counts:", err);
            }
            finally {
                setLoadingCounts(false);
            }
        };
        fetchCounts();
    }, [allItemsWithDecisions, reviewId]);
    // Detect review items that have been deleted from content tree
    useEffect(() => {
        const detectDeletedItems = async () => {
            if (!editContext?.itemsRepository || allItemsWithDecisions.length === 0) {
                setDeletedItemKeys(new Set());
                return;
            }
            const deletedKeys = new Set();
            await Promise.all(allItemsWithDecisions.map(async (item) => {
                const key = `${item.itemId}-${item.language}`;
                try {
                    const fetched = await editContext.itemsRepository.getItem({
                        id: item.itemId,
                        language: getLookupLanguage(item.language),
                        version: 0,
                    });
                    if (!fetched) {
                        deletedKeys.add(key);
                    }
                }
                catch (err) {
                    if (isNotFoundError(err)) {
                        deletedKeys.add(key);
                    }
                    else {
                        console.warn(`[DecisionsMatrix] Failed to check item existence for ${key}:`, err);
                    }
                }
            }));
            setDeletedItemKeys(deletedKeys);
        };
        detectDeletedItems();
    }, [allItemsWithDecisions, editContext?.itemsRepository, getLookupLanguage]);
    // Listen for websocket messages to update counts in real-time
    useEffect(() => {
        if (!editContext?.addSocketMessageListener) {
            return;
        }
        const unsubscribe = editContext.addSocketMessageListener((message) => {
            try {
                // Handle comment updates
                if (message.type === "comment-updated" && message.payload?.comment) {
                    const comment = message.payload.comment;
                    const itemId = comment.mainItemId;
                    const itemLanguage = comment.language || "en";
                    // Refresh counts for this item
                    refreshItemCounts(itemId, itemLanguage);
                }
                // Handle comment deletions
                if (message.type === "comment-deleted" && message.payload?.commentId) {
                    // Find which item(s) this comment belonged to by checking our cache
                    const deletedCommentId = message.payload.commentId;
                    const itemsToRefresh = new Set();
                    commentsData.forEach((comments, key) => {
                        if (comments.some((c) => c.id === deletedCommentId)) {
                            itemsToRefresh.add(key);
                        }
                    });
                    // If we found the comment in our cache, refresh only those items
                    if (itemsToRefresh.size > 0) {
                        itemsToRefresh.forEach((key) => {
                            const parts = key.split("-");
                            if (parts.length >= 2) {
                                const itemId = parts[0];
                                const itemLanguage = parts.slice(1).join("-"); // Handle language codes with dashes
                                refreshItemCounts(itemId, itemLanguage);
                            }
                        });
                    }
                    else {
                        // If not found in cache, refresh all items to be safe
                        allItemsWithDecisions.forEach((item) => {
                            refreshItemCounts(item.itemId, item.language);
                        });
                    }
                }
                // Handle suggested edit updates
                if (message.type === "suggested-edit-updated" &&
                    message.payload?.suggestedEdit) {
                    const suggestion = message.payload.suggestedEdit;
                    const itemId = suggestion.mainItemId;
                    const itemLanguage = suggestion.mainItemLanguage || "en";
                    // Refresh counts for this item
                    refreshItemCounts(itemId, itemLanguage);
                }
                // Handle suggested edit deletions
                if (message.type === "suggested-edit-deleted" && message.payload?.id) {
                    // Find which item(s) this suggestion belonged to by checking our cache
                    const deletedSuggestionId = message.payload.id;
                    const itemsToRefresh = new Set();
                    suggestionsData.forEach((suggestions, key) => {
                        if (suggestions.some((s) => s.id === deletedSuggestionId)) {
                            itemsToRefresh.add(key);
                        }
                    });
                    // If we found the suggestion in our cache, refresh only those items
                    if (itemsToRefresh.size > 0) {
                        itemsToRefresh.forEach((key) => {
                            const parts = key.split("-");
                            if (parts.length >= 2) {
                                const itemId = parts[0];
                                const itemLanguage = parts.slice(1).join("-"); // Handle language codes with dashes
                                refreshItemCounts(itemId, itemLanguage);
                            }
                        });
                    }
                    else {
                        // If not found in cache, refresh all items to be safe
                        allItemsWithDecisions.forEach((item) => {
                            refreshItemCounts(item.itemId, item.language);
                        });
                    }
                }
            }
            catch (err) {
                console.error("Error handling websocket message:", err);
            }
        });
        return () => {
            unsubscribe();
        };
    }, [
        editContext?.addSocketMessageListener,
        refreshItemCounts,
        allItemsWithDecisions,
        commentsData,
        suggestionsData,
    ]);
    // Helper function to get comment count for an item by reviewer email
    const getCommentCount = (itemId, itemLanguage, reviewerEmail) => {
        const key = `${itemId}-${itemLanguage}`;
        const comments = commentsData.get(key) || [];
        return comments.filter((c) => !c.suggestedEditId &&
            c.author?.toLowerCase() === reviewerEmail.toLowerCase()).length;
    };
    // Helper function to get suggestion count for an item by reviewer email
    const getSuggestionCount = (itemId, itemLanguage, reviewerEmail) => {
        const key = `${itemId}-${itemLanguage}`;
        const suggestions = suggestionsData.get(key) || [];
        return suggestions.filter((s) => s.author?.toLowerCase() === reviewerEmail.toLowerCase()).length;
    };
    // Helper function to get total comment count for an item
    const getTotalCommentCount = (itemId, itemLanguage) => {
        const key = `${itemId}-${itemLanguage}`;
        const comments = commentsData.get(key) || [];
        return comments.filter((comment) => !comment.suggestedEditId).length;
    };
    // Helper function to get total suggestion count for an item
    const getTotalSuggestionCount = (itemId, itemLanguage) => {
        const key = `${itemId}-${itemLanguage}`;
        const suggestions = suggestionsData.get(key) || [];
        return suggestions.length;
    };
    const userAssignment = assignments.find((a) => currentUserEmail &&
        a.reviewerEmail.toLowerCase() === currentUserEmail.toLowerCase());
    const currentItemDecision = userAssignment && currentItem
        ? getDecision(userAssignment, currentItem.id, currentItem.language || "en")
        : undefined;
    const currentItemKey = currentItem
        ? `${currentItem.id}-${currentItem.language || "en"}`
        : null;
    const isCurrentItemDeleted = currentItemKey
        ? deletedItemKeys.has(currentItemKey)
        : false;
    // Check if current page is in the review (either directly or as a subitem)
    const isCurrentPageInReview = useMemo(() => {
        if (!currentItem || !currentFullItem) {
            console.log("[DecisionsMatrix] No current item or full item");
            return false;
        }
        const currentPath = currentFullItem.path;
        const currentId = currentItem.id;
        const currentLanguage = currentItem.language || "en";
        console.log("[DecisionsMatrix] Checking if current page is in review:", {
            currentItemId: currentId,
            currentItemPath: currentPath,
            currentItemLanguage: currentLanguage,
            parentId: currentFullItem.parentId,
            itemsCount: items.length,
            items: items.map((i) => ({
                id: i.itemId,
                path: i.path,
                includeSubitems: i.includeSubitems,
                language: i.language,
            })),
        });
        // Check if current item is directly in the items list
        const isDirectMatch = items.some((item) => item.itemId === currentId &&
            (item.language === currentLanguage ||
                item.language === "*" ||
                currentLanguage === "*"));
        console.log("[DecisionsMatrix] Is direct match:", isDirectMatch);
        if (isDirectMatch) {
            console.log("[DecisionsMatrix] Current item is directly in review");
            return true;
        }
        // Check if it's a subitem of any item with includeSubitems: true
        const isSubitem = items.some((item) => {
            if (!item.includeSubitems) {
                return false;
            }
            console.log(`[DecisionsMatrix] Checking if ${currentId} is subitem of ${item.itemId}`, {
                currentPath: currentPath,
                itemPath: item.path,
                currentParentId: currentFullItem.parentId,
                itemId: item.itemId,
            });
            // Method 1: Check by path if both are available
            if (currentPath && item.path) {
                // Normalize paths - remove trailing slashes and ensure consistent format
                const normalizedCurrentPath = currentPath
                    .replace(/\/$/, "")
                    .replace(/\\$/, "");
                const normalizedItemPath = item.path
                    .replace(/\/$/, "")
                    .replace(/\\$/, "");
                // Check if current path starts with item path and is deeper
                const isSubPath = normalizedCurrentPath.startsWith(normalizedItemPath + "/") ||
                    normalizedCurrentPath.startsWith(normalizedItemPath + "\\");
                if (isSubPath && normalizedCurrentPath !== normalizedItemPath) {
                    console.log(`[DecisionsMatrix] Found subitem match by path: ${normalizedCurrentPath} is under ${normalizedItemPath}`);
                    return true;
                }
            }
            // Method 2: Check if current item's parent ID matches the review item ID
            if (currentFullItem.parentId &&
                item.itemId === currentFullItem.parentId) {
                console.log(`[DecisionsMatrix] Found subitem match by parent ID: ${currentId} has parent ${currentFullItem.parentId} which matches ${item.itemId}`);
                return true;
            }
            // Method 3: Check if item ID is in the current path
            if (currentPath && item.itemId) {
                const pathContainsId = currentPath.includes(`/${item.itemId}/`) ||
                    currentPath.includes(`\\${item.itemId}\\`) ||
                    currentPath.endsWith(`/${item.itemId}`) ||
                    currentPath.endsWith(`\\${item.itemId}`);
                if (pathContainsId && currentId !== item.itemId) {
                    console.log(`[DecisionsMatrix] Found subitem match by ID in path: ${currentPath} contains ${item.itemId}`);
                    return true;
                }
            }
            return false;
        });
        console.log("[DecisionsMatrix] Is in review result:", isDirectMatch || isSubitem);
        return isDirectMatch || isSubitem;
    }, [currentItem, currentFullItem, items]);
    const showCurrentPageButtons = currentItem && userAssignment && isCurrentPageInReview;
    // Debug logging
    useEffect(() => {
        console.log("[DecisionsMatrix] Button visibility check:", {
            isLimitedPreviewUser,
            hasCurrentItem: !!currentItem,
            hasCurrentFullItem: !!currentFullItem,
            hasUserAssignment: !!userAssignment,
            isCurrentPageInReview,
            showCurrentPageButtons,
            currentItem: currentItem
                ? {
                    id: currentItem.id,
                    path: currentItem.path,
                    language: currentItem.language,
                }
                : null,
            currentFullItem: currentFullItem
                ? {
                    id: currentFullItem.id,
                    path: currentFullItem.path,
                    parentId: currentFullItem.parentId,
                }
                : null,
            userAssignment: userAssignment
                ? {
                    assignmentId: userAssignment.assignmentId,
                    reviewerEmail: userAssignment.reviewerEmail,
                }
                : null,
        });
    }, [
        isLimitedPreviewUser,
        currentItem,
        currentFullItem,
        userAssignment,
        isCurrentPageInReview,
        showCurrentPageButtons,
    ]);
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs("div", { className: "bg-neutral-grey-5/80 flex items-center gap-2 border-b px-3 py-2", children: [_jsx("span", { className: "text-neutral-grey-50 text-xs font-semibold tracking-wide", children: "Review Items" }), _jsx("span", { className: "bg-neutral-grey-10 badge-pad-sm text-neutral-grey-50 rounded-full text-[10px] font-medium", children: allItemsWithDecisions.length })] }), _jsxs(SimpleToolbar, { children: [!isLimitedPreviewUser && (_jsxs(Popover, { open: isAddPopoverOpen, onOpenChange: setIsAddPopoverOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(SimpleIconButton, { label: "Add Pages", icon: _jsx(Plus, { className: "h-4 w-4" }), onClick: () => setIsAddPopoverOpen(true), "data-testid": "add-pages-button" }) }), _jsx(PopoverContent, { className: "m-2 w-[600px] p-0", align: "start", "data-testid": "page-selector-popover", children: _jsxs("div", { className: "flex flex-col gap-2 p-2", children: [_jsx("div", { className: "text-sm font-medium", children: "Select Pages" }), _jsx(ItemTreeSelector, { selectedItems: selectedItems, onItemsChange: handleItemsChange, language: language, height: "350px" }), _jsxs("div", { className: "flex justify-end gap-2 border-t pt-2", children: [_jsx(Button, { variant: "outline", size: "sm", onClick: () => {
                                                        setSelectedItems([]);
                                                        setIsAddPopoverOpen(false);
                                                    }, children: "Cancel" }), _jsxs(Button, { size: "sm", onClick: handleAddSelectedPages, disabled: selectedItems.length === 0 || loading, children: [_jsx(Plus, { className: "mr-2 h-4 w-4" }), "Add", " ", selectedItems.length > 0 ? `${selectedItems.length} ` : "", "Page", selectedItems.length !== 1 ? "s" : ""] })] })] }) })] })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Filter, { className: "h-4 w-4" }), _jsxs("select", { value: filter, onChange: (e) => setFilter(e.target.value), className: "badge-pad rounded border text-xs", children: [_jsx("option", { value: "all", children: "All Items" }), _jsx("option", { value: "pending", children: "Pending" }), _jsx("option", { value: "rejected", children: "Rejected" }), _jsx("option", { value: "approved", children: "All Approved" })] })] }), !isLimitedPreviewUser && (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Users, { className: "h-4 w-4" }), _jsxs("select", { value: selectedReviewerId || "", onChange: (e) => onSelectReviewer(e.target.value === "" ? null : e.target.value), className: "badge-pad rounded border text-xs", children: [_jsx("option", { value: "", children: "All Reviewers" }), assignments.map((assignment) => (_jsx("option", { value: assignment.assignmentId, children: assignment.reviewerName || assignment.reviewerEmail }, assignment.assignmentId)))] })] })), hasSelectedPages && (_jsx(SimpleIconButton, { label: "Remove Selected", icon: _jsx(DeleteIcon, { size: "lg" }), onClick: handleRemoveSelectedPages, disabled: loading, "data-testid": "remove-selected-pages-button" })), showCurrentPageButtons && (_jsxs("div", { className: "ml-auto flex items-center gap-2", children: [_jsx("div", { className: "border-border-default mx-1 h-6 border-l" }), isCurrentItemDeleted && (_jsx("span", { className: "text-feedback-orange text-xs", children: "This item has been deleted" })), _jsx(SimpleIconButton, { label: `Approve Current Page`, icon: _jsx(Check, { className: "h-4 w-4" }), onClick: handleApproveCurrentPage, disabled: loading || isCurrentItemDeleted, className: currentItemDecision?.decision === "Approved"
                                    ? "text-feedback-green"
                                    : "" }), _jsx(SimpleIconButton, { label: `Reject Current Page`, icon: _jsx(X, { className: "h-4 w-4" }), onClick: handleRejectCurrentPage, disabled: loading || isCurrentItemDeleted, className: currentItemDecision?.decision === "Rejected"
                                    ? "text-feedback-red"
                                    : "" })] }))] }), _jsx("div", { className: "flex-1 overflow-auto", children: allItemsWithDecisions.length === 0 ? (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center text-sm", children: "No items in review" })) : (_jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "w-full border-separate border-spacing-0 text-xs", children: [_jsx("thead", { className: "sticky top-0 z-20 bg-white", children: _jsxs("tr", { children: [!isLimitedPreviewUser && (_jsx("th", { className: "sticky left-0 z-30 w-12 border bg-white p-2 text-center font-medium shadow-[1px_0_0_0_color-mix(in_srgb,var(--color-neutral-grey-100)_10%,transparent)]", children: _jsx(Checkbox, { checked: filteredItems.length > 0 &&
                                                    filteredItems.every((item) => selectedPagesForRemoval.has(toSelectionKey(item.itemId, item.language))), onCheckedChange: (checked) => {
                                                    const newSelection = new Set();
                                                    if (checked) {
                                                        filteredItems.forEach((item) => {
                                                            newSelection.add(toSelectionKey(item.itemId, item.language));
                                                        });
                                                    }
                                                    setSelectedPagesForRemoval(newSelection);
                                                }, className: "h-4 w-4" }) })), _jsx("th", { className: cn("sticky z-20 max-w-[300px] min-w-[150px] border bg-white p-2 text-left font-medium shadow-[1px_0_0_0_color-mix(in_srgb,var(--color-neutral-grey-100)_10%,transparent)]", !isLimitedPreviewUser ? "left-12" : "left-0"), children: "Item" }), displayAssignments.map((assignment) => (_jsx("th", { className: "max-w-[200px] min-w-[120px] border bg-white p-2 text-center font-medium", children: _jsxs("div", { className: "flex flex-col overflow-hidden", children: [_jsx("span", { className: "truncate font-medium normal-case", title: assignment.reviewerName, children: assignment.reviewerName }), _jsx("span", { className: "text-neutral-grey-50 text-xs font-normal break-all", title: assignment.reviewerEmail, children: assignment.reviewerEmail })] }) }, assignment.assignmentId))), _jsx("th", { className: "min-w-[50px] border bg-white p-2 text-center font-medium", children: _jsxs("div", { className: "flex items-center justify-center gap-1.5", children: [_jsx("div", { title: "Total comments", children: _jsx(MessageSquare, { className: "h-3.5 w-3.5" }) }), _jsx("div", { title: "Total suggestions", children: _jsx(Lightbulb, { className: "h-3.5 w-3.5" }) })] }) }), userAssignment && (_jsx("th", { className: "min-w-[80px] border bg-white p-2 text-center font-medium", children: "Actions" }))] }) }), _jsx("tbody", { children: filteredItems.map((item, itemIndex) => {
                                    const itemKey = `${item.itemId}-${item.language}`;
                                    const selectionKey = toSelectionKey(item.itemId, item.language);
                                    const isSelected = selectedPagesForRemoval.has(selectionKey);
                                    const currentItemLanguage = currentItem?.language || "en";
                                    const itemLanguage = item.language === "*" ? currentItemLanguage : item.language;
                                    const isCurrentItem = currentItem &&
                                        currentItem.id === item.itemId &&
                                        currentItemLanguage === itemLanguage;
                                    const rowClass = isCurrentItem
                                        ? "bg-feedback-blue-light"
                                        : "bg-white";
                                    const itemCellClass = isCurrentItem
                                        ? "bg-feedback-blue-light"
                                        : "bg-white";
                                    return (_jsxs("tr", { className: rowClass, children: [!isLimitedPreviewUser && (_jsx("td", { className: cn("sticky left-0 z-10 border p-1 text-center shadow-[1px_0_0_0_color-mix(in_srgb,var(--color-neutral-grey-100)_10%,transparent)]", itemCellClass), children: _jsx(Checkbox, { checked: isSelected, onCheckedChange: () => togglePageSelection(item.itemId, item.language), onClick: (e) => e.stopPropagation(), className: "h-4 w-4", "data-testid": `review-item-select-checkbox-${item.itemId}-${item.language}` }) })), _jsx("td", { className: cn("sticky z-10 max-w-[300px] border p-2 shadow-[1px_0_0_0_color-mix(in_srgb,var(--color-neutral-grey-100)_10%,transparent)]", !isLimitedPreviewUser ? "left-12" : "left-0", itemCellClass), children: _jsxs("div", { className: "hover:bg-neutral-grey-5 -m-1 flex cursor-pointer flex-col rounded p-1", onClick: () => handleLoadItem(item.itemId, item.language), title: "Click to load item", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "font-medium break-all", children: item.name || item.path || item.itemId }), item.language === "*" ? (_jsx(Badge, { variant: "outline", className: "text-2xs", children: "All Languages" })) : (_jsx("span", { className: "text-neutral-grey-50 text-xs", children: item.language }))] }), item.includeSubitems && (_jsx("span", { className: "text-neutral-grey-50 text-xs", children: "(with subitems)" })), !isLimitedPreviewUser &&
                                                            (() => {
                                                                const approvalCount = getApprovalCount(item.itemId, item.language);
                                                                const status = getItemApprovalStatus(item.itemId, item.language);
                                                                return (_jsxs("div", { className: "mt-1 flex items-center gap-1", children: [_jsxs("span", { className: `text-2xs ${status === "approved"
                                                                                ? "text-feedback-green font-semibold"
                                                                                : status === "rejected"
                                                                                    ? "text-feedback-red font-semibold"
                                                                                    : "text-neutral-grey-50"}`, children: [approvalCount, "/", requiredApprovals, " ", "approvals"] }), status === "approved" && (_jsx(Check, { className: "text-feedback-green h-3 w-3" })), status === "rejected" && (_jsx(X, { className: "text-feedback-red h-3 w-3" }))] }));
                                                            })()] }) }), displayAssignments.map((assignment) => {
                                                return (_jsx("td", { className: "border p-1 text-center", children: getDecisionCell(assignment, item) }, assignment.assignmentId));
                                            }), _jsx("td", { className: "border p-1 text-center", children: loadingCounts ? (_jsx(Loader2, { className: "mx-auto h-3 w-3 animate-spin" })) : (_jsx("div", { className: "flex items-center justify-center gap-2 text-xs", children: (() => {
                                                        // If a reviewer is selected, filter counts by that reviewer
                                                        // Otherwise, show total counts for all reviewers
                                                        let commentCount;
                                                        let suggestionCount;
                                                        if (selectedReviewerId) {
                                                            // Find the selected reviewer's assignment
                                                            const selectedAssignment = assignments.find((a) => a.assignmentId === selectedReviewerId);
                                                            if (selectedAssignment) {
                                                                commentCount = getCommentCount(item.itemId, item.language, selectedAssignment.reviewerEmail);
                                                                suggestionCount = getSuggestionCount(item.itemId, item.language, selectedAssignment.reviewerEmail);
                                                            }
                                                            else {
                                                                // Fallback to total counts if assignment not found
                                                                commentCount = getTotalCommentCount(item.itemId, item.language);
                                                                suggestionCount = getTotalSuggestionCount(item.itemId, item.language);
                                                            }
                                                        }
                                                        else {
                                                            // No reviewer selected, show total counts
                                                            commentCount = getTotalCommentCount(item.itemId, item.language);
                                                            suggestionCount = getTotalSuggestionCount(item.itemId, item.language);
                                                        }
                                                        return (_jsxs(_Fragment, { children: [commentCount > 0 && (_jsxs("div", { className: "flex items-center gap-0.5", title: `${commentCount} comment${commentCount !== 1 ? "s" : ""}`, children: [_jsx(MessageSquare, { className: "h-3 w-3" }), _jsx("span", { children: commentCount })] })), suggestionCount > 0 && (_jsxs("div", { className: "flex items-center gap-0.5", title: `${suggestionCount} suggestion${suggestionCount !== 1 ? "s" : ""}`, children: [_jsx(Lightbulb, { className: "h-3 w-3" }), _jsx("span", { children: suggestionCount })] })), commentCount === 0 &&
                                                                    suggestionCount === 0 && (_jsx("span", { className: "text-neutral-grey-50 text-xs", children: "-" }))] }));
                                                    })() })) }), userAssignment && (_jsx("td", { className: "border p-1 text-center", children: (() => {
                                                    const userDecision = getDecision(userAssignment, item.itemId, item.language);
                                                    const isApproved = userDecision?.decision === "Approved";
                                                    const isRejected = userDecision?.decision === "Rejected";
                                                    const isItemDeleted = deletedItemKeys.has(itemKey);
                                                    const disabledReason = isItemDeleted
                                                        ? "This item has been deleted"
                                                        : undefined;
                                                    return (_jsxs("div", { className: "flex flex-col items-center justify-center gap-1", children: [_jsxs("div", { className: "flex items-center justify-center gap-1", children: [_jsx(Button, { variant: "ghost", size: "sm", className: cn("h-6 w-6 p-0", isApproved
                                                                            ? "bg-feedback-green-light text-feedback-green hover:bg-feedback-green-light"
                                                                            : "text-neutral-grey-50 hover:text-feedback-green"), onClick: () => handleMakeDecision(userAssignment.assignmentId, item.itemId, item.language, "Approved"), disabled: loading || isItemDeleted, title: disabledReason || "Approve this item", children: _jsx(Check, { className: "h-3.5 w-3.5" }) }), _jsx(Button, { variant: "ghost", size: "sm", className: cn("h-6 w-6 p-0", isRejected
                                                                            ? "bg-feedback-red-light text-feedback-red hover:bg-feedback-red-light"
                                                                            : "text-neutral-grey-50 hover:text-feedback-red"), onClick: () => handleMakeDecision(userAssignment.assignmentId, item.itemId, item.language, "Rejected"), disabled: loading || isItemDeleted, title: disabledReason || "Reject this item", children: _jsx(X, { className: "h-3.5 w-3.5" }) })] }), isItemDeleted && (_jsx("span", { className: "text-2xs text-feedback-orange", children: "Item deleted" }))] }));
                                                })() }))] }, `${item.itemId}-${item.language}-${itemIndex}`));
                                }) })] }) })) })] }));
}
//# sourceMappingURL=DecisionsMatrix.js.map