import { useEffect, useState } from "react";
import { searchUsers } from "./userService";
/** Strips a domain prefix like "sitecore\\jdoe" → "jdoe". */
export function formatAccountName(userName) {
    const trimmed = userName?.trim();
    if (!trimmed)
        return "Unknown user";
    const slashIndex = trimmed.lastIndexOf("\\");
    if (slashIndex >= 0 && slashIndex < trimmed.length - 1) {
        return trimmed.slice(slashIndex + 1);
    }
    return trimmed;
}
// Process-wide cache so the same author/visitor isn't looked up repeatedly across components.
const cache = new Map();
function cacheKey(userName) {
    return userName.trim().toLowerCase();
}
/** True when `fullName` is a real display name rather than the bare account name. */
function looksResolved(userName, fullName) {
    const trimmed = fullName?.trim();
    if (!trimmed)
        return false;
    if (trimmed.includes("\\"))
        return false;
    return (trimmed.localeCompare(userName, undefined, { sensitivity: "accent" }) !== 0);
}
/**
 * Resolves a user name to a friendly display name + avatar URL, seeding from any data the caller
 * already has and falling back to a cached `/parhelia/users` lookup. Used for comment authors,
 * locked-field indicators, and recent visitors — anywhere a user appears who may be offline.
 */
export function useResolvedUser(userName, seed) {
    const name = userName?.trim() || "";
    const seedDisplay = seed?.fullName?.trim() || formatAccountName(name);
    const [resolved, setResolved] = useState(() => {
        const cached = name ? cache.get(cacheKey(name)) : undefined;
        return {
            displayName: cached?.displayName || seedDisplay,
            avatarUrl: seed?.avatarUrl ?? cached?.avatarUrl ?? undefined,
        };
    });
    useEffect(() => {
        if (!name)
            return;
        const cached = cache.get(cacheKey(name));
        setResolved({
            displayName: cached?.displayName || seedDisplay,
            avatarUrl: seed?.avatarUrl ?? cached?.avatarUrl ?? undefined,
        });
        // A network lookup is only worth it when we lack either a real name or an avatar.
        const hasGoodDisplay = looksResolved(name, seed?.fullName);
        const hasAvatar = seed?.avatarUrl != null;
        if (cached || (hasGoodDisplay && hasAvatar))
            return;
        let cancelled = false;
        (async () => {
            try {
                const users = await searchUsers(name, 5);
                const exact = users.find((u) => u.userName.localeCompare(name, undefined, {
                    sensitivity: "accent",
                }) === 0) || users[0];
                if (!exact || cancelled)
                    return;
                const entry = {
                    displayName: exact.displayName?.trim() || seedDisplay,
                    avatarUrl: exact.avatarUrl ?? undefined,
                };
                cache.set(cacheKey(name), entry);
                setResolved({
                    displayName: entry.displayName,
                    avatarUrl: seed?.avatarUrl ?? entry.avatarUrl,
                });
            }
            catch {
                // Best effort — keep the seeded values.
            }
        })();
        return () => {
            cancelled = true;
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [name, seed?.fullName, seed?.avatarUrl, seedDisplay]);
    return resolved;
}
//# sourceMappingURL=userResolution.js.map