using System.Text;

namespace PlotLine.Services;

public static class AvatarHelper
{
    public static string Initials(string? displayName)
    {
        var words = SignificantWords(displayName).ToList();
        if (words.Count >= 2)
        {
            return string.Concat(words.Take(2).Select(word => char.ToUpperInvariant(word[0])));
        }

        if (words.Count == 1)
        {
            return char.ToUpperInvariant(words[0][0]).ToString();
        }

        return "?";
    }

    private static IEnumerable<string> SignificantWords(string? displayName)
    {
        if (string.IsNullOrWhiteSpace(displayName))
        {
            yield break;
        }

        var builder = new StringBuilder();
        foreach (var ch in displayName)
        {
            if (char.IsLetterOrDigit(ch))
            {
                builder.Append(ch);
                continue;
            }

            if (ch is '\'' or '\u2019')
            {
                continue;
            }

            if (builder.Length > 0)
            {
                yield return builder.ToString();
                builder.Clear();
            }
        }

        if (builder.Length > 0)
        {
            yield return builder.ToString();
        }
    }
}
