using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace FrontOffice.Main.Pages.Blog;

public partial class Post
{
    [Inject] private IJSRuntime JS { get; set; } = default!;
    [Parameter] public string Slug { get; set; } = string.Empty;

    [Inject] private BlogPostService BlogPostService { get; set; } = default!;

    private BlogPostDetailDto? _post;
    private bool _isLoading = true;

    protected override async Task OnParametersSetAsync()
    {
        if (string.IsNullOrWhiteSpace(Slug)) return;

        _isLoading = true;
        StateHasChanged();

        try
        {
            _post = await BlogPostService.GetBySlugAsync(Slug);

            // Fire-and-forget: increment view count
            if (_post != null)
            {
                _ = BlogPostService.IncrementViewCountAsync(_post.Id);
            }
        }
        catch
        {
            _post = null;
        }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private void NavigateToCategoryFilter(long categoryId)
    {
        Navigation.NavigateTo($"/blog?category={categoryId}");
    }

    private async Task GoBack() => await JS.InvokeVoidAsync("history.back");
}
