@page "/feiertage"
@rendermode InteractiveWebAssembly
@attribute [Authorize]
@inject IHolidayService HolidayService
@inject ITimetrackerService TrackerService
@inject AuthenticationStateProvider AuthStateProvider

<PageTitle>Feiertage – Timetracker</PageTitle>

@if (_loading)
{
    <MudStack AlignItems="AlignItems.Center" Class="mt-16" Spacing="3">
        <MudProgressCircular Color="Color.Tertiary" Indeterminate="true" Size="Size.Large" />
        <MudText Color="Color.Secondary">Lade Feiertage…</MudText>
    </MudStack>
}
else
{
    <MudStack Spacing="3">

        @* ── Header ── *@
        <MudPaper Elevation="4" Class="pa-5 rounded-xl"
                  Style="background: #0F766E; color: white;">
            <MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween">
                <MudIconButton Icon="@Icons.Material.Filled.ChevronLeft"
                               Style="color:white" Size="Size.Large" OnClick="PrevYear" />
                <MudStack Spacing="0" AlignItems="AlignItems.Center">
                    <MudText Typo="Typo.h5" Style="color:white; font-weight:700; letter-spacing:0.5px">
                        Feiertage @_year
                    </MudText>
                    <MudText Typo="Typo.caption" Style="color:rgba(255,255,255,0.72)">
                        @_subLabel
                    </MudText>
                </MudStack>
                <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="0">
                    @if (_year != DateTime.Today.Year)
                    {
                        <MudButton Variant="Variant.Text" Style="color:white"
                                   OnClick="GoToCurrentYear" Size="Size.Small">
                            Heute
                        </MudButton>
                    }
                    <MudIconButton Icon="@Icons.Material.Filled.ChevronRight"
                                   Style="color:white" Size="Size.Large" OnClick="NextYear" />
                </MudStack>
            </MudStack>
        </MudPaper>

        @if (_holidays.Count == 0)
        {
            @* ── Keine Daten ── *@
            <MudPaper Elevation="2" Class="pa-8 rounded-xl text-center">
                <MudIcon Icon="@Icons.Material.Filled.Celebration"
                         Style="font-size:4rem; color:#B2DFDB;" Class="mb-3" />
                <MudText Typo="Typo.h6" Color="Color.Secondary">
                    Keine Feiertage für @_year gespeichert.
                </MudText>
                <MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-1">
                    Gehe zu <b>Einstellungen → Feiertage</b> und klicke „Von API laden".
                </MudText>
            </MudPaper>
        }
        else
        {
            @* ── Kacheln nach Monat gruppiert ── *@
            @foreach (var group in _holidays.GroupBy(h => h.Date.Month).OrderBy(g => g.Key))
            {
                <MudStack Spacing="2">
                    <MudText Typo="Typo.overline" Color="Color.Secondary"
                             Style="font-weight:700; letter-spacing:2px; padding-left:4px">
                        @_deCulture.DateTimeFormat.GetMonthName(group.Key).ToUpper()
                    </MudText>
                    <MudGrid Spacing="3">
                        @foreach (var h in group.OrderBy(x => x.Date))
                        {
                            var isPast   = h.Date < DateOnly.FromDateTime(DateTime.Today);
                            var isToday  = h.Date == DateOnly.FromDateTime(DateTime.Today);
                            var daysLeft = h.Date.DayNumber - DateOnly.FromDateTime(DateTime.Today).DayNumber;

                            <MudItem xs="12" sm="6" md="4" lg="3">
                                <MudCard Elevation="@(isToday ? 6 : 2)" Class="rounded-xl h-100"
                                         Style="@($"border-top: 4px solid {(isToday ? "#FF6F00" : isPast ? "#B2DFDB" : "#00897B")}; opacity:{(isPast && !isToday ? "0.7" : "1")};")">
                                    <MudCardContent Class="pa-4">
                                        <MudStack Spacing="2">

                                            @* Icon + Datum *@
                                            <MudStack Row="true" AlignItems="AlignItems.Center"
                                                      Justify="Justify.SpaceBetween">
                                                <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
                                                    <MudIcon Icon="@Icons.Material.Filled.Celebration"
                                                             Style="@($"color:{(isToday ? "#FF6F00" : isPast ? "#80CBC4" : "#00897B")}; font-size:1.3rem")" />
                                                    <MudText Typo="Typo.caption"
                                                             Style="@($"color:{(isToday ? "#FF6F00" : isPast ? "#90A4AE" : "#00897B")}; font-weight:700")">
                                                        @h.Date.ToString("dd. MMM", _deCulture)
                                                    </MudText>
                                                </MudStack>

                                                @if (isToday)
                                                {
                                                    <MudChip T="string" Size="Size.Small" Variant="Variant.Filled"
                                                             Style="height:20px; font-size:10px; font-weight:700; background:#FF6F00; color:white;">
                                                        HEUTE
                                                    </MudChip>
                                                }
                                                else if (!isPast)
                                                {
                                                    <MudChip T="string" Size="Size.Small" Variant="Variant.Outlined"
                                                             Style="@($"height:20px; font-size:10px; color:#00897B; border-color:#00897B;")">
                                                        @(daysLeft == 1 ? "morgen" : $"in {daysLeft} Tagen")
                                                    </MudChip>
                                                }
                                                else
                                                {
                                                    <MudChip T="string" Size="Size.Small" Variant="Variant.Outlined"
                                                             Style="height:20px; font-size:10px; color:#90A4AE; border-color:#CFD8DC;">
                                                        vergangen
                                                    </MudChip>
                                                }
                                            </MudStack>

                                            @* Name *@
                                            <MudText Typo="Typo.h6"
                                                     Style="@($"font-weight:700; line-height:1.3; color:{(isPast && !isToday ? "#90A4AE" : "inherit")}")">
                                                @h.Name
                                            </MudText>

                                            @* Wochentag *@
                                            <MudText Typo="Typo.caption" Color="Color.Secondary">
                                                @h.Date.ToString("dddd, dd. MMMM yyyy", _deCulture)
                                            </MudText>

                                        </MudStack>
                                    </MudCardContent>
                                </MudCard>
                            </MudItem>
                        }
                    </MudGrid>
                </MudStack>
            }

            @* ── Zusammenfassung ── *@
            <MudPaper Elevation="2" Class="pa-4 rounded-xl"
                      Style="background: linear-gradient(90deg, rgba(15,118,110,0.08) 0%, transparent 100%); border-left: 4px solid #0F766E;">
                <MudStack Row="true" Spacing="4" Wrap="Wrap.Wrap" AlignItems="AlignItems.Center">
                    <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
                        <MudIcon Icon="@Icons.Material.Filled.Celebration" Style="color:#00897B" />
                        <MudText Typo="Typo.body2" Style="font-weight:600">@_holidays.Count Feiertage gesamt</MudText>
                    </MudStack>
                    <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
                        <MudIcon Icon="@Icons.Material.Filled.CheckCircle" Style="color:#4CAF50" />
                        <MudText Typo="Typo.body2" Color="Color.Secondary">
                            @_holidays.Count(h => h.Date < DateOnly.FromDateTime(DateTime.Today)) vergangen
                        </MudText>
                    </MudStack>
                    <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
                        <MudIcon Icon="@Icons.Material.Filled.Schedule" Style="color:#FF9800" />
                        <MudText Typo="Typo.body2" Color="Color.Secondary">
                            @_holidays.Count(h => h.Date >= DateOnly.FromDateTime(DateTime.Today)) noch ausstehend
                        </MudText>
                    </MudStack>
                    @{
                        var next = _holidays
                            .Where(h => h.Date > DateOnly.FromDateTime(DateTime.Today))
                            .OrderBy(h => h.Date)
                            .FirstOrDefault();
                    }
                    @if (next != null)
                    {
                        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
                            <MudIcon Icon="@Icons.Material.Filled.NavigateNext" Style="color:#00897B" />
                            <MudText Typo="Typo.body2" Color="Color.Secondary">
                                Nächster: <b>@next.Name</b> (@next.Date.ToString("dd. MMM", _deCulture))
                            </MudText>
                        </MudStack>
                    }
                </MudStack>
            </MudPaper>
        }

    </MudStack>
}

@code {
    private static readonly System.Globalization.CultureInfo _deCulture = new("de-DE");

    private bool _loading = true;
    private int _year = DateTime.Today.Year;
    private List<PublicHoliday> _holidays = [];
    private string _subLabel = "";

    private int _userId;
    private AppSettings _settings = new();

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthStateProvider.GetAuthenticationStateAsync();
        var claim = authState.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
        if (claim != null)
        {
            _userId = int.Parse(claim.Value);
            _settings = await TrackerService.GetSettingsAsync(_userId);
        }
        await LoadHolidays();
        _loading = false;
    }

    private async Task LoadHolidays()
    {
        _holidays = await HolidayService.GetHolidaysAsync(_year, _settings.GermanState);
        var count = _holidays.Count;
        var past  = _holidays.Count(h => h.Date < DateOnly.FromDateTime(DateTime.Today));
        _subLabel = count == 0
            ? "Keine Daten gespeichert"
            : $"{count} Feiertage · {past} vergangen · {count - past} ausstehend";
    }

    private async Task PrevYear()       { _year--; await LoadHolidays(); }
    private async Task NextYear()       { _year++; await LoadHolidays(); }
    private async Task GoToCurrentYear(){ _year = DateTime.Today.Year; await LoadHolidays(); }
}
