"use client";
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import React from "react";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { searchUsers } from "../services/userService";
const trailingTokenPunctuation = /[,;:.!?\])}'"]$/;
const displayCache = new Map();
const pendingDisplayLookups = new Map();
function isAlphaNumeric(value) {
    return /^[a-z0-9]$/i.test(value);
}
function isCanonicalMention(candidate) {
    return candidate.includes("\\") || candidate.includes("/");
}
function normalizeUserName(value) {
    return value.trim().toLowerCase();
}
function parseMentionSegments(text) {
    const segments = [];
    for (let index = 0; index < text.length; index++) {
        if (text[index] !== "@")
            continue;
        if (index > 0 && isAlphaNumeric(text[index - 1] ?? ""))
            continue;
        let end = index + 1;
        while (end < text.length && !/\s/.test(text[end] ?? "")) {
            end++;
        }
        let mentionEnd = end;
        while (mentionEnd > index + 1 &&
            trailingTokenPunctuation.test(text[mentionEnd - 1] ?? "")) {
            mentionEnd--;
        }
        const candidate = text.slice(index + 1, mentionEnd);
        if (!candidate || !isCanonicalMention(candidate))
            continue;
        segments.push({
            start: index,
            end: mentionEnd,
            candidate,
        });
        index = mentionEnd - 1;
    }
    return segments;
}
async function resolveMentionDisplay(candidate) {
    const cacheKey = normalizeUserName(candidate);
    const cached = displayCache.get(cacheKey);
    if (cached)
        return cached;
    const pending = pendingDisplayLookups.get(cacheKey);
    if (pending)
        return pending;
    const lookup = searchUsers(candidate, 8)
        .then((users) => {
        const exact = users.find((user) => normalizeUserName(user.userName) === cacheKey);
        const userName = exact?.userName?.trim() || candidate;
        const displayName = exact?.displayName?.trim() || userName;
        const display = { userName, displayName };
        displayCache.set(cacheKey, display);
        return display;
    })
        .catch(() => {
        const display = { userName: candidate, displayName: candidate };
        displayCache.set(cacheKey, display);
        return display;
    })
        .finally(() => {
        pendingDisplayLookups.delete(cacheKey);
    });
    pendingDisplayLookups.set(cacheKey, lookup);
    return lookup;
}
function useMentionDisplays(segments) {
    const mentionKeys = React.useMemo(() => Array.from(new Set(segments.map((segment) => normalizeUserName(segment.candidate)))), [segments]);
    const [displays, setDisplays] = React.useState({});
    React.useEffect(() => {
        let cancelled = false;
        const cachedDisplays = mentionKeys.reduce((current, key) => {
            const cached = displayCache.get(key);
            if (cached)
                current[key] = cached;
            return current;
        }, {});
        if (Object.keys(cachedDisplays).length > 0) {
            setDisplays((current) => ({ ...current, ...cachedDisplays }));
        }
        const unresolved = mentionKeys.filter((key) => !displayCache.has(key));
        if (unresolved.length === 0)
            return undefined;
        Promise.all(unresolved.map((key) => {
            const segment = segments.find((candidate) => normalizeUserName(candidate.candidate) === key);
            return segment
                ? resolveMentionDisplay(segment.candidate).then((display) => [key, display])
                : null;
        })).then((entries) => {
            if (cancelled)
                return;
            setDisplays((current) => {
                const next = { ...current };
                entries.forEach((entry) => {
                    if (entry)
                        next[entry[0]] = entry[1];
                });
                return next;
            });
        });
        return () => {
            cancelled = true;
        };
    }, [mentionKeys, segments]);
    return displays;
}
export function MentionText({ text }) {
    const value = text || "";
    const segments = React.useMemo(() => parseMentionSegments(value), [value]);
    const displays = useMentionDisplays(segments);
    const parts = [];
    let cursor = 0;
    for (const segment of segments) {
        if (cursor < segment.start) {
            parts.push(value.slice(cursor, segment.start));
        }
        const key = normalizeUserName(segment.candidate);
        const display = displays[key] ?? {
            userName: segment.candidate,
            displayName: segment.candidate,
        };
        const label = display.displayName || display.userName;
        parts.push(_jsxs(Tooltip, { delayDuration: 250, children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs("span", { className: "text-feedback-blue font-medium", children: ["@", label] }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: display.userName })] }, `${segment.start}-${segment.end}`));
        cursor = segment.end;
    }
    if (cursor < value.length) {
        parts.push(value.slice(cursor));
    }
    return _jsx(_Fragment, { children: parts });
}
//# sourceMappingURL=MentionText.js.map