<script lang="ts">
  import { ChevronDown, ChevronsUpDown, ChevronUp } from 'lucide-svelte';
  import type { TableController } from './table.svelte';

  let {
    label,
    column,
    controller
  }: {
    label: string;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    controller: TableController<any>;
    column: string;
  } = $props();

  const active = $derived(controller.sortKey === column);
</script>

<button
  type="button"
  class="sort-header"
  class:active
  aria-label={`Sort by ${label}${active ? (controller.sortDir === 'asc' ? ', ascending' : ', descending') : ''}`}
  onclick={() => controller.toggleSort(column)}
>
  <span>{label}</span>
  {#if active}
    {#if controller.sortDir === 'asc'}
      <ChevronUp size={13} strokeWidth={2.6} />
    {:else}
      <ChevronDown size={13} strokeWidth={2.6} />
    {/if}
  {:else}
    <ChevronsUpDown size={13} strokeWidth={2} />
  {/if}
</button>

<style>
  .sort-header {
    display: inline-flex;
    align-items: center;
    gap: 0.28rem;
    width: 100%;
    min-height: 26px;
    padding: 0;
    border: 0;
    background: transparent;
    /* Inherit the .log-head typography (size/weight/transform/letter-spacing). */
    color: inherit;
    font: inherit;
    letter-spacing: inherit;
    text-transform: inherit;
    text-align: left;
    cursor: pointer;
    user-select: none;
  }

  .sort-header :global(svg) {
    flex-shrink: 0;
    opacity: 0.4;
    transition: opacity 120ms ease;
  }

  .sort-header:hover {
    color: var(--color-text-primary);
  }

  .sort-header:hover :global(svg) {
    opacity: 0.7;
  }

  .sort-header.active {
    color: var(--color-brand);
  }

  .sort-header.active :global(svg) {
    opacity: 1;
  }

  .sort-header:focus-visible {
    outline: 2px solid var(--color-brand);
    outline-offset: 2px;
    border-radius: 0.3rem;
  }
</style>
