@props([
    'columns' => [],
])

<thead>
    <tr>
        @foreach ($columns as $column)
            @php
                $label = is_array($column) ? ($column['label'] ?? '') : $column;
                $align = is_array($column) ? ($column['align'] ?? null) : null;
                $width = is_array($column) ? ($column['width'] ?? null) : null;
                $sortKey = is_array($column) ? ($column['sort'] ?? null) : null;
                $class = $align === 'end' ? 'text-end' : ($align === 'center' ? 'text-center' : '');
                $currentSort = request('sort');
                $currentDir = strtolower((string) request('dir', 'asc')) === 'desc' ? 'desc' : 'asc';
                $isActive = $sortKey && $currentSort === $sortKey;
                $nextDir = $isActive && $currentDir === 'asc' ? 'desc' : 'asc';
                // Third click clears sort when already desc
                $clearSort = $isActive && $currentDir === 'desc';
            @endphp
            <th @class([$class => $class, 'erp-th-sortable' => (bool) $sortKey]) @if ($width) style="width: {{ $width }}" @endif>
                @if ($sortKey)
                    @php
                        $query = request()->except(['page']);
                        if ($clearSort) {
                            unset($query['sort'], $query['dir']);
                        } else {
                            $query['sort'] = $sortKey;
                            $query['dir'] = $nextDir;
                        }
                        $href = url()->current().'?'.http_build_query($query);
                        $icon = ! $isActive ? 'fe-chevrons-up' : ($currentDir === 'asc' ? 'fe-chevron-up' : 'fe-chevron-down');
                        $aria = ! $isActive
                            ? __('common.sort_none')
                            : ($currentDir === 'asc' ? __('common.sort_asc') : __('common.sort_desc'));
                    @endphp
                    <a href="{{ $href }}" class="erp-sort-link text-decoration-none" aria-label="{{ $label }} — {{ $aria }}">
                        <span>{{ $label }}</span>
                        <i class="fe {{ $icon }} erp-sort-link__icon @if($isActive) is-active @endif" aria-hidden="true"></i>
                    </a>
                @else
                    {{ $label }}
                @endif
            </th>
        @endforeach
    </tr>
</thead>
