@namespace Lumeo
@typeparam TItem

<thead data-slot="datagrid-header" class="@CssClass" @attributes="AdditionalAttributes">
    <tr role="row" aria-rowindex="1">
        @* Row reorder handle column *@
        @if (Context?.RowReorderable == true)
        {
            <th role="columnheader" class="px-1 py-2 w-8 bg-muted/30"></th>
        }

        @if (Context?.SelectionMode == DataGridSelectionMode.Multiple)
        {
            <th role="columnheader" class="px-3 py-2 w-10 bg-muted/30">
                <Checkbox Checked="@AllSelected"
                          IsIndeterminate="@SomeSelected"
                          CheckedChanged="@OnSelectAllChanged" />
            </th>
        }
        else if (Context?.SelectionMode == DataGridSelectionMode.Single)
        {
            <th role="columnheader" class="px-3 py-2 w-10 bg-muted/30"></th>
        }

        @if (HasDetailTemplate)
        {
            <th role="columnheader" class="px-1 py-2 w-8 bg-muted/30"></th>
        }

        @if (Context is not null)
        {
            var colIndex = 0;
            var leading = LeadingColumnCount;
            @foreach (var column in Context.VisibleColumns)
            {
                var idx = colIndex;
                var sortDir = GetSortDirection(column);
                var hasFilter = HasFilter(column);
                var isFilterOpen = ActiveFilterColumn == column.Field;
                <DataGridHeaderCell @key="column.Id" TItem="TItem"
                                    Column="column"
                                    ColumnIndex="idx"
                                    AriaColIndex="@(leading + idx + 1)"
                                    SortDirection="sortDir"
                                    HasActiveFilter="hasFilter"
                                    IsFilterOpen="isFilterOpen"
                                    Reorderable="Reorderable"
                                    SortPriority="GetSortPriority(column)"
                                    TotalSortCount="GetTotalSortCount()"
                                    OnFilterToggle="@(() => OnFilterToggle.InvokeAsync(column.Field))"
                                    OnFilterApply="OnFilterApply"
                                    OnColumnReorder="OnColumnReorder" />
                colIndex++;
            }
        }

        @* Row edit action column placeholder in header *@
        @if (Context?.EditMode == DataGridEditMode.Row)
        {
            <th role="columnheader" class="px-3 py-2 w-10 bg-muted/30"></th>
        }
    </tr>
</thead>

@code {
    [CascadingParameter] private DataGridContext<TItem>? Context { get; set; }
    [Parameter] public bool HasDetailTemplate { get; set; }
    [Parameter] public string? ActiveFilterColumn { get; set; }
    [Parameter] public bool Reorderable { get; set; }
    [Parameter] public EventCallback<string?> OnFilterToggle { get; set; }
    [Parameter] public EventCallback<FilterApplyEventArgs> OnFilterApply { get; set; }
    [Parameter] public EventCallback<ColumnReorderEventArgs> OnColumnReorder { get; set; }
    [Parameter] public string? Class { get; set; }
    [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object>? AdditionalAttributes { get; set; }

    private string CssClass => $"sticky top-0 z-20 bg-card [&_tr]:border-b [&_tr]:border-border/40 {Class}".Trim();

    /// <summary>Number of non-data leading columns (reorder handle, selection,
    /// detail toggle) rendered before the first data column. Used to offset
    /// 1-based <c>aria-colindex</c> values.</summary>
    private int LeadingColumnCount
    {
        get
        {
            var n = 0;
            if (Context?.RowReorderable == true) n++;
            if (Context?.SelectionMode != DataGridSelectionMode.None) n++;
            if (HasDetailTemplate) n++;
            return n;
        }
    }

    private bool AllSelected =>
        Context is not null &&
        Context.DisplayedItems.Count > 0 &&
        Context.SelectedItems.Count >= Context.DisplayedItems.Count;

    private bool SomeSelected =>
        Context is not null &&
        Context.SelectedItems.Count > 0 &&
        Context.SelectedItems.Count < Context.DisplayedItems.Count;

    private SortDirection GetSortDirection(DataGridColumn<TItem> column)
    {
        if (Context is null || column.Field is null) return SortDirection.None;
        var sort = Context.Sorts.FirstOrDefault(s => s.Field == column.Field);
        return sort?.Direction ?? SortDirection.None;
    }

    private bool HasFilter(DataGridColumn<TItem> column)
    {
        if (Context is null || column.Field is null) return false;
        return Context.Filters.Any(f => f.Field == column.Field);
    }

    private int GetSortPriority(DataGridColumn<TItem> column)
    {
        if (Context is null || column.Field is null) return 0;
        var idx = Context.Sorts.FindIndex(s => s.Field == column.Field && s.Direction != SortDirection.None);
        return idx >= 0 ? idx + 1 : 0;
    }

    private int GetTotalSortCount() => Context?.Sorts.Count(s => s.Direction != SortDirection.None) ?? 0;

    private void OnSelectAllChanged(bool value)
    {
        if (Context is null) return;
        if (value)
            Context.SelectAll();
        else
            Context.ClearSelection();
    }
}
