import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEditContext } from "../client/editContext";
import { User } from "./User";
import { Avatar } from "../../components/ui/avatar";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { useEffect, useState } from "react";
import { getItemVisitors } from "../services/editService";
import { useResolvedUser } from "../services/userResolution";
import { AboutDialog } from "../client/AboutDialog";
import { formatDateOnly } from "../utils";
import { ChevronDown, Info, LogOut } from "lucide-react";
export function ActiveUsers() {
    const editContext = useEditContext();
    const [visitors, setVisitors] = useState([]);
    const [isLoadingVisitors, setIsLoadingVisitors] = useState(false);
    const isHomeWorkspace = editContext?.workspace?.id === "home";
    const mySession = editContext?.activeSessions.find((x) => x.sessionId === editContext?.sessionId);
    // More robust session filtering - if mySession or mySession.item is not found,
    // show all active sessions instead of an empty list
    const activeSessions = (() => {
        const allSessions = editContext?.activeSessions || [];
        // On the home workspace, only show the current user — recent visitors and
        // other active sessions aren't meaningful without an item context.
        if (isHomeWorkspace) {
            return mySession ? [mySession] : [];
        }
        // If we don't have a current session or current item, show all sessions
        if (!mySession || !mySession.item?.id) {
            return allSessions;
        }
        // Filter sessions for the same item as the current user
        const filteredSessions = allSessions.filter((x) => x.item?.id === mySession.item?.id);
        // If filtering results in no sessions (which shouldn't happen since mySession
        // should be included), fall back to showing all sessions
        return filteredSessions.length > 0 ? filteredSessions : allSessions;
    })();
    // Fetch visitors when current item changes — but not on the home workspace.
    useEffect(() => {
        if (isHomeWorkspace) {
            setVisitors([]);
            return;
        }
        if (editContext?.currentItemDescriptor) {
            setIsLoadingVisitors(true);
            getItemVisitors(editContext.currentItemDescriptor)
                .then((result) => {
                if (result.type === "success" && result.data) {
                    setVisitors(result.data);
                }
                else {
                    console.warn("Failed to fetch visitors:", result);
                    setVisitors([]);
                }
            })
                .catch((error) => {
                console.error("Error fetching visitors:", error);
                setVisitors([]);
            })
                .finally(() => {
                setIsLoadingVisitors(false);
            });
        }
    }, [
        isHomeWorkspace,
        editContext?.currentItemDescriptor?.id,
        editContext?.currentItemDescriptor?.language,
        editContext?.currentItemDescriptor?.version,
    ]);
    // Recent visitors = visited the item but not currently active (limit 10).
    const activeUserNames = new Set(activeSessions.map((s) => s.user.name.toLowerCase()));
    const recentVisitors = visitors
        .filter((visitor) => !activeUserNames.has(visitor.userName.toLowerCase()))
        .slice(0, 10);
    const visibleUsers = activeSessions.slice(0, 3); // Only show active users in the avatar stack
    const remainingActiveCount = Math.max(0, activeSessions.length - 3);
    const hasAnyUsers = activeSessions.length > 0 || recentVisitors.length > 0;
    const handleAbout = () => {
        editContext?.openDialog(AboutDialog, {});
    };
    const handleLogout = () => {
        window.location.href = "/sitecore/login?action=logout";
    };
    return (_jsxs(Popover, { children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("div", { className: "flex cursor-pointer items-center gap-1", title: `${activeSessions.length} active user${activeSessions.length !== 1 ? "s" : ""}, ${recentVisitors.length} recent visitor${recentVisitors.length !== 1 ? "s" : ""}`, "data-testid": "active-users", children: [_jsxs("div", { className: "flex items-center -space-x-2", children: [visibleUsers.map((session, index) => (_jsx("div", { className: "relative rounded-full border-2 border-white", style: { zIndex: visibleUsers.length - index }, children: _jsx(User, { session: session }) }, session.sessionId))), (remainingActiveCount > 0 || recentVisitors.length > 0) && (_jsxs("div", { className: "bg-neutral-grey-50 relative flex h-7 w-7 items-center justify-center rounded-full border-2 border-white text-xs font-medium text-white", style: { zIndex: 0 }, children: ["+", remainingActiveCount + recentVisitors.length] }))] }), !editContext?.isMobile && _jsx(ChevronDown, { className: "size-3" })] }) }), _jsxs(PopoverContent, { className: "w-80 p-1", align: "end", children: [isLoadingVisitors && (_jsx("div", { className: "text-neutral-grey-50 mb-2 text-xs", children: "Loading recent visitors..." })), _jsxs("div", { className: "max-h-96 space-y-1 overflow-y-auto", children: [activeSessions.length > 0 && (_jsx(_Fragment, { children: activeSessions.map((session) => {
                                    const userName = session.user.fullName || session.user.name;
                                    const idxBackslash = userName.indexOf("\\");
                                    const displayName = idxBackslash >= 0
                                        ? userName.substring(idxBackslash + 1)
                                        : userName;
                                    const userEmail = session.user.email?.trim();
                                    const isCurrentUser = session.sessionId === editContext?.sessionId;
                                    return (_jsxs("div", { className: "hover:bg-neutral-grey-5 flex items-center gap-3 rounded p-1", children: [_jsxs("div", { className: "relative", children: [_jsx(User, { session: session }), _jsx("div", { className: "bg-feedback-green absolute -right-0.5 -bottom-0.5 h-3 w-3 rounded-full border-2 border-white" })] }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-xs font-medium", children: displayName }), userEmail && (_jsx("div", { className: "text-neutral-grey-50 truncate text-xs", children: userEmail }))] }), isCurrentUser && (_jsx("div", { className: "text-feedback-blue text-xs font-medium", children: "You" }))] }, session.sessionId));
                                }) })), recentVisitors.length > 0 && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "text-neutral-grey-50 mt-3 mb-1 px-2 text-xs font-medium", children: ["Recent Visitors (", recentVisitors.length, ")"] }), recentVisitors.map((visitor, index) => (_jsx(VisitorRow, { visitor: visitor }, `visitor-${index}`)))] })), hasAnyUsers && (_jsx("div", { className: "border-border-default my-2 border-t" })), _jsxs("div", { className: "space-y-1", children: [_jsxs("div", { className: "hover:bg-neutral-grey-5 flex cursor-pointer items-center gap-3 rounded p-1", onClick: handleAbout, children: [_jsx("div", { className: "flex h-8 w-8 items-center justify-center", children: _jsx(Info, { className: "text-neutral-grey-50 h-4 w-4" }) }), _jsx("div", { className: "min-w-0 flex-1", children: _jsx("div", { className: "text-neutral-grey-100 text-xs font-medium", children: "About" }) })] }), _jsxs("div", { className: "hover:bg-neutral-grey-5 flex cursor-pointer items-center gap-3 rounded p-1", onClick: handleLogout, children: [_jsx("div", { className: "flex h-8 w-8 items-center justify-center", children: _jsx(LogOut, { className: "text-neutral-grey-50 h-4 w-4" }) }), _jsx("div", { className: "min-w-0 flex-1", children: _jsx("div", { className: "text-neutral-grey-100 text-xs font-medium", children: "Log Out" }) })] })] }), !hasAnyUsers && !isLoadingVisitors && (_jsx("div", { className: "text-neutral-grey-50 p-1 text-sm", children: "No users found" }))] })] })] }));
}
function VisitorRow({ visitor }) {
    const resolved = useResolvedUser(visitor.userName, {
        fullName: visitor.userFullName,
        avatarUrl: visitor.avatarUrl,
    });
    const visitedAt = visitor.visitedAt ? new Date(visitor.visitedAt) : null;
    const timeAgo = visitedAt ? formatTimeAgo(visitedAt) : "";
    return (_jsxs("div", { className: "hover:bg-neutral-grey-5 flex items-center gap-3 rounded p-1 opacity-75", children: [_jsx(Avatar, { src: resolved.avatarUrl, name: resolved.displayName, size: "md" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-xs font-medium", children: resolved.displayName }), _jsx("div", { className: "text-neutral-grey-50 truncate text-xs", children: timeAgo })] })] }));
}
function formatTimeAgo(date) {
    const now = new Date();
    const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
    if (diffInSeconds < 60)
        return "Just now";
    if (diffInSeconds < 3600)
        return `${Math.floor(diffInSeconds / 60)}m ago`;
    if (diffInSeconds < 86400)
        return `${Math.floor(diffInSeconds / 3600)}h ago`;
    if (diffInSeconds < 604800)
        return `${Math.floor(diffInSeconds / 86400)}d ago`;
    return formatDateOnly(date);
}
//# sourceMappingURL=ActiveUsers.js.map