@inject Web.Services.DocsService DocsService

<div class="top-row ps-3 navbar navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="">Web</a>
        <button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
</div>

<div class="@NavMenuCssClass nav-scrollable" @onclick="ToggleNavMenu">
    <nav class="nav flex-column">
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                <span class="bi bi-house-door-fill-nav-menu" aria-hidden="true"></span> Home
            </NavLink>
        </div>
 
        @if (groupedNotes == null)
        {
            <div class="nav-item px-3"><span class="nav-link text-secondary">Loading...</span></div>
        }
        else
        {
            @foreach (var group in groupedNotes)
            {
                <div class="nav-item px-3 nav-section-header">@group.Category</div>
                @foreach (var note in group.Notes)
                {
                    <div class="nav-item px-3 nav-item-doc">
                        <NavLink class="nav-link" href="@($"docs/{note.Slug}")">
                            @note.Title
                        </NavLink>
                    </div>
                }
            }
        }
    </nav>
</div>

@code {
    private bool collapseNavMenu = true;
    private List<NoteGroup>? groupedNotes;

    private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;

    private void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }

    protected override async Task OnInitializedAsync()
    {
        var index = await DocsService.GetIndexAsync();
        groupedNotes = (index.Notes ?? new())
            .GroupBy(n => string.IsNullOrEmpty(n.Category) ? "Uncategorized" : n.Category)
            .OrderBy(g => g.Key)
            .Select(g => new NoteGroup { Category = g.Key, Notes = g.OrderBy(n => n.Title).ToList() })
            .ToList();
    }

    private class NoteGroup
    {
        public string Category { get; set; } = "";
        public List<Web.Models.NoteInfo> Notes { get; set; } = new();
    }
}
