@using MudBlazor
@using OpenArchival.DataAccess
@using System.Text.RegularExpressions
@using System.Net

@namespace OpenArchival.Blazor.Blog

<MudLink Href="@($"/articles/{Post.Id}")" Target="_blank" Style="text-decoration: none; color: inherit;">
    <MudCard Style="@($"cursor: pointer; height: {Height}px; display: flex; flex-direction: column;")">
        @if (Post.MainPhoto != null)
        {
            <MudCardMedia Image="@($"/api/files/{Post.MainPhoto.Id}/small")" Height="150" />
        }
        else
        {
            <MudCardMedia Image="/images/placeholder.png" Height="150" />
        }

        <MudCardContent Style="flex-grow: 1; overflow-y: clip;">
            <MudText Typo="Typo.h5">@Post.Title</MudText>
            <MudText Typo="Typo.body2">@CreateContentSnippet(Post.Content)</MudText>
        </MudCardContent>
    </MudCard>
</MudLink>

@code {
    [Parameter]
    public required BlogPost Post { get; set; }

    [Parameter]
    public int Height { get; set; } = 300;

    private string CreateContentSnippet(string html, int maxLength = 150)
    {
        if (string.IsNullOrEmpty(html))
        {
            return string.Empty;
        }

        // Strip HTML tags
        string plainText = Regex.Replace(html, @"<[^>]+>", string.Empty);

        // Decode HTML entities
        plainText = WebUtility.HtmlDecode(plainText).Trim();

        if (plainText.Length > maxLength)
        {
            return plainText.Substring(0, maxLength) + "...";
        }

        return plainText;
    }
}
