@page "/calendar" @attribute [Authorize] @using WebApp.Components.Shared.Components @using WebApp.Models @using WebApp.Services @using Heron.MudCalendar @using Microsoft.Extensions.Logging @inject IEventOccurrenceService EventOccurrenceService @inject ILogger Logger Import @if (_calendarItems == null) { Loading calendar events... } else { } @code { private List? _calendarItems; private DateTime _calendarDate = DateTime.Today; protected override async Task OnInitializedAsync() { await LoadCalendarEvents(); } private async Task LoadCalendarEvents() { try { Logger.LogInformation("Loading calendar events"); var occurrences = await EventOccurrenceService.GetEventOccurrencesAsync(); if (occurrences == null) { Logger.LogWarning("Service returned null occurrences"); _calendarItems = new List(); return; } Logger.LogDebug("Received {Count} occurrences from service", occurrences.Count()); var items = new List(); foreach (var occ in occurrences) { try { if (occ == null) { Logger.LogWarning("Null occurrence found, skipping"); continue; } if (string.IsNullOrEmpty(occ.Name)) { Logger.LogWarning("Occurrence with Id={Id} has null or empty Name", occ.Id); } var calendarItem = new CalendarEventItem(occ, occ.EventDefinition); items.Add(calendarItem); } catch (Exception ex) { Logger.LogError(ex, "Error creating CalendarEventItem for occurrence Id={Id}, Name={Name}", occ?.Id, occ?.Name); // Continue processing other items } } _calendarItems = items; Logger.LogInformation("Created {Count} calendar items from {OccurrenceCount} occurrences", _calendarItems.Count, occurrences.Count()); // Find the next date with events _calendarDate = GetNextDateWithEvents(); } catch (Exception ex) { Logger.LogError(ex, "Error loading calendar events"); _calendarItems = new List(); } finally { StateHasChanged(); } } private DateTime GetNextDateWithEvents() { try { if (_calendarItems == null || !_calendarItems.Any()) { Logger.LogDebug("No calendar items available, returning today's date"); return DateTime.Today; } var today = DateTime.Today; var nextEvent = _calendarItems .Where(item => { try { return item != null && item.Start.Date >= today; } catch (Exception ex) { Logger.LogWarning(ex, "Error checking item date, skipping item"); return false; } }) .OrderBy(item => item.Start) .FirstOrDefault(); if (nextEvent != null) { return nextEvent.Start.Date; } // Fallback to first event if no future events var firstEvent = _calendarItems .Where(item => item != null) .OrderBy(item => item.Start) .FirstOrDefault(); if (firstEvent != null) { return firstEvent.Start.Date; } return DateTime.Today; } catch (Exception ex) { Logger.LogError(ex, "Error in GetNextDateWithEvents"); return DateTime.Today; } } }