import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { useEditContext } from "../client/editContext";
import { findFieldElement } from "../utils";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { Avatar } from "../../components/ui/avatar";
import { useResolvedUser } from "../services/userResolution";
import { measureCollapsedTextOffsetRect, measureElementRect, rectEquals, } from "./overlay/geometry";
import { useIframeOverlay } from "./overlay/IframeOverlayProvider";
import { useOverlayMeasurement } from "./overlay/useOverlayMeasurement";
function useResolvedSessionUser(session) {
    return useResolvedUser(session.user.name, {
        fullName: session.user.fullName,
        avatarUrl: session.user.avatarUrl,
    });
}
export function LockedFieldIndicator({ iframe, }) {
    const editContext = useEditContext();
    if (!editContext)
        return;
    const sessionsWithFieldLock = editContext.activeSessions.filter((x) => x.fieldLock && x.sessionId !== editContext.sessionId);
    const effectiveIframe = iframe ??
        editContext.getActiveSlotContext()?.primaryPageViewContext.editorIframe;
    return (_jsx(_Fragment, { children: sessionsWithFieldLock.map((session) => {
            if (!session.fieldLock)
                return;
            if (!effectiveIframe)
                return;
            const element = findFieldElement(effectiveIframe, session.fieldLock);
            if (!element)
                return;
            const caret = editContext.remoteCarets[session.sessionId];
            const caretMatchesLock = caret?.offset != null &&
                caret.fieldId === session.fieldLock.fieldId &&
                caret.item?.id === session.fieldLock.item.id &&
                caret.item?.language === session.fieldLock.item.language &&
                caret.item?.version === session.fieldLock.item.version;
            return (_jsxs("div", { children: [!caretMatchesLock && (_jsx(FieldLock, { element: element, session: session })), caretMatchesLock && (_jsx(FieldCaret, { element: element, session: session, offset: caret.offset }))] }, session.sessionId));
        }) }));
}
function FieldCaret({ element, session, offset, }) {
    const { displayName, avatarUrl } = useResolvedSessionUser(session);
    const rect = useOverlayMeasurement((metrics) => measureCollapsedTextOffsetRect(element.ownerDocument, element, offset, metrics) ?? measureElementRect(element, metrics), [element, offset, session.sessionId], {
        initialValue: null,
        equals: rectEquals,
        interests: ["viewport", "layout", "text", "adornment-data"],
    });
    if (!rect)
        return null;
    return (_jsxs("div", { className: "pointer-events-none absolute z-[1]", style: {
            left: rect.x,
            top: rect.y,
            height: Math.max(rect.height, 14),
        }, children: [_jsx("style", { children: `@keyframes parheliaRemoteCaretBlink {
          0%, 49% { opacity: 1; }
          50%, 100% { opacity: 0; }
        }` }), _jsx("div", { className: "h-full w-0.5 rounded-full", style: {
                    background: session.color,
                    animation: "parheliaRemoteCaretBlink 1s steps(1, end) infinite",
                } }), _jsxs("div", { className: "badge-pad-sm absolute top-0 left-1.5 flex max-w-40 -translate-y-full items-center gap-1 rounded text-xs text-white shadow", style: { background: session.color }, children: [avatarUrl && (_jsx(Avatar, { src: avatarUrl, name: displayName, className: "size-4 border border-white/40" })), _jsx("span", { className: "truncate", children: displayName })] })] }));
}
function FieldLock({ element, session, }) {
    const { displayName, avatarUrl } = useResolvedSessionUser(session);
    const [tooltipOpen, setTooltipOpen] = useState(false);
    const overlay = useIframeOverlay();
    const rect = useOverlayMeasurement((metrics) => measureElementRect(element, metrics), [element, session.sessionId], {
        initialValue: null,
        equals: rectEquals,
        interests: ["viewport", "layout", "text", "adornment-data"],
    });
    useEffect(() => {
        setTooltipOpen(false);
    }, [
        session.sessionId,
        session.fieldLock?.fieldId,
        session.fieldLock?.item.id,
    ]);
    useEffect(() => {
        if (!tooltipOpen)
            return;
        const closeTooltip = () => setTooltipOpen(false);
        window.addEventListener("scroll", closeTooltip, true);
        window.addEventListener("resize", closeTooltip);
        const unsubscribeScroll = overlay.subscribeScroll(closeTooltip);
        return () => {
            window.removeEventListener("scroll", closeTooltip, true);
            window.removeEventListener("resize", closeTooltip);
            unsubscribeScroll();
        };
    }, [overlay, tooltipOpen]);
    if (rect) {
        return (_jsxs(Tooltip, { open: tooltipOpen, onOpenChange: setTooltipOpen, delayDuration: 250, disableHoverableContent: true, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs("div", { className: "badge-pad-sm absolute flex max-w-40 items-center gap-1 rounded text-xs text-white opacity-90 hover:opacity-100", onPointerEnter: () => setTooltipOpen(true), onPointerLeave: () => setTooltipOpen(false), onPointerDown: () => setTooltipOpen(false), onBlur: () => setTooltipOpen(false), style: {
                            left: rect.x + "px",
                            top: rect.y + "px",
                            background: session.color,
                        }, children: [avatarUrl && (_jsx(Avatar, { src: avatarUrl, name: displayName, className: "size-4 border border-white/40" })), _jsx("span", { className: "truncate", children: displayName })] }) }), _jsx(TooltipContent, { side: "top", className: "pointer-events-none max-w-xs", children: _jsxs("div", { className: "space-y-1 text-xs", children: [_jsxs("div", { className: "font-medium", children: ["Field locked by ", displayName] }), _jsx("div", { children: "This field is currently being edited by another user, so editing is blocked until their field lock is released." }), _jsxs("div", { className: "text-neutral-grey-50", children: ["Username: ", session.user.name] })] }) })] }));
    }
    return null;
}
//# sourceMappingURL=LockedFieldIndicator.js.map