import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { useEditContext } from "../client/editContext";
import { getLatestComments } from "../services/reviewsService";
import { getLatestSuggestedEdits } from "../services/suggestedEditsService";
import { Lightbulb, MessageSquare } from "lucide-react";
import { LanguageSelector } from "../../components/ui/LanguageSelector";
export function LatestFeedback() {
    const editContext = useEditContext();
    const [items, setItems] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [selectedLanguage, setSelectedLanguage] = useState(undefined);
    // Cutoff is now computed server-side. Keep memo in case we later want client hints.
    const sinceIso = null;
    const load = useCallback(async () => {
        let cancelled = false;
        setIsLoading(true);
        setError(null);
        try {
            const take = 50;
            const [cRes, sRes] = await Promise.all([
                getLatestComments(take, selectedLanguage),
                getLatestSuggestedEdits(take, selectedLanguage),
            ]);
            const comments = (cRes.data || []).map((c) => ({
                ...c,
                kind: "comment",
            }));
            const suggestions = (sRes.data || []).map((s) => ({
                ...s,
                kind: "suggestion",
            }));
            const merged = [...comments, ...suggestions].sort((a, b) => {
                const ad = new Date(a.created || 0).getTime();
                const bd = new Date(b.created || 0).getTime();
                return bd - ad;
            });
            const latest = merged.slice(0, 50);
            if (!cancelled)
                setItems(latest);
        }
        catch (e) {
            if (!cancelled)
                setError(e?.message || "Failed to load latest items");
        }
        finally {
            if (!cancelled)
                setIsLoading(false);
        }
        return () => {
            cancelled = true;
        };
    }, [sinceIso, selectedLanguage]);
    useEffect(() => {
        let disposed;
        (async () => {
            disposed = await load();
        })();
        return () => {
            try {
                disposed?.();
            }
            catch { }
        };
    }, [load]);
    useEffect(() => {
        const typesToRefresh = new Set([
            "comment-updated",
            "comment-deleted",
            "suggested-edit-updated",
            "suggested-edit-deleted",
        ]);
        const dispose = editContext?.addSocketMessageListener?.((message) => {
            try {
                if (typesToRefresh.has(message?.type)) {
                    void load();
                }
            }
            catch { }
        });
        return () => {
            try {
                dispose?.();
            }
            catch { }
        };
    }, [editContext?.addSocketMessageListener, load]);
    // Items are server-side filtered by language when selected
    const onOpenItem = async (item) => {
        try {
            const mainId = item.kind === "comment" ? item.mainItemId : item.mainItemId;
            const lang = item.kind === "comment" ? item.language : item.mainItemLanguage;
            const ver = item.kind === "comment" ? item.version : item.mainItemVersion;
            await editContext?.loadItem({ id: mainId, language: lang, version: ver });
            editContext?.setSelectedComment(item.kind === "comment" ? item : undefined);
            if (item.kind === "comment") {
                editContext?.setScrollIntoView(item.itemId);
            }
            editContext?.openSidebar("feedback");
        }
        catch { }
    };
    const Row = ({ item }) => {
        const isComment = item.kind === "comment";
        const created = item.created
            ? new Date(item.created)
            : undefined;
        const dateText = created
            ? `${created.toLocaleDateString()} ${created.toLocaleTimeString()}`
            : "";
        const comment = isComment ? item : undefined;
        const pageName = isComment
            ? comment?.mainItemName ||
                (comment?.relatedItems || []).find((ri) => ri.itemId === comment?.mainItemId)?.itemName
            : item.mainItemName;
        const componentName = isComment
            ? comment?.itemName
            : item.itemName;
        const fieldName = isComment ? comment?.fieldName : undefined;
        const user = item.authorDisplayName || item.author || "";
        const label = isComment ? "Comment" : "Suggestion";
        return (_jsx("button", { className: "w-full cursor-pointer rounded p-1 text-left hover:bg-gray-100", onClick: () => onOpenItem(item), children: _jsxs("div", { className: "flex items-center justify-between gap-2 text-xs", children: [_jsxs("div", { className: "flex items-center gap-2 truncate", children: [_jsx("span", { className: "inline-flex items-center justify-center rounded py-0.5 text-gray-700", "aria-label": label, title: label, children: isComment ? (_jsx(MessageSquare, { className: "h-3.5 w-3.5", strokeWidth: 1 })) : (_jsx(Lightbulb, { className: "h-3.5 w-3.5", strokeWidth: 1 })) }), _jsx("div", { className: "flex items-center", children: [
                                    pageName,
                                    componentName,
                                    fieldName ||
                                        (item.kind === "suggestion" ? item.fieldId : undefined),
                                ]
                                    .filter((x) => !!x && x.length > 0)
                                    .map((seg, idx, arr) => (_jsxs("span", { className: "truncate", children: [idx > 0 && (_jsx("span", { className: "mx-1 text-gray-400", children: ">" })), _jsx("span", { className: idx === 0
                                                ? "font-medium text-gray-900"
                                                : "text-gray-500", children: seg })] }, idx))) }), user && _jsxs("span", { className: "text-gray-500", children: [" \u00B7 ", user] })] }), _jsx("div", { className: "shrink-0 text-[10px] text-gray-500", children: dateText })] }) }));
    };
    return (_jsxs("div", { className: "h-full overflow-auto p-2", children: [_jsxs("div", { className: "mb-2 flex items-center gap-2", children: [_jsx(LanguageSelector, { selectedLanguage: selectedLanguage, onLanguageSelected: (language) => setSelectedLanguage(language.languageCode), showAllLanguages: true }), selectedLanguage && (_jsx("button", { className: "text-xs text-gray-600 hover:underline", onClick: () => setSelectedLanguage(undefined), children: "Clear" }))] }), isLoading && _jsx("div", { className: "p-2 text-xs text-gray-500", children: "Loading\u2026" }), error && _jsx("div", { className: "p-2 text-xs text-red-600", children: error }), !isLoading && !error && items.length === 0 && (_jsx("div", { className: "p-2 text-xs text-gray-500", children: "No recent activity" })), _jsx("div", { className: "divide-y", children: items.map((it) => (_jsx(Row, { item: it }, `${it.kind}-${it.id}`))) })] }));
}
//# sourceMappingURL=LatestFeedback.js.map