import * as React from 'react';

import { TableHead } from '@/Components/ui/table';
import { cn } from '@/lib/utils';

interface SortHeaderProps {
  column: string;
  /** Plain text or simple ReactNode — must NOT contain interactive elements (buttons, links).
   *  Use the separate `tooltip` prop when you need an InfoTooltip alongside the label. */
  label: React.ReactNode;
  currentSort?: string;
  currentDir?: string;
  onSort: (column: string) => void;
  className?: string;
  /** Optional tooltip rendered outside the sort button, preventing nested-button violations. */
  tooltip?: React.ReactNode;
}

export function SortHeader({
  column,
  label,
  currentSort,
  currentDir,
  onSort,
  className,
  tooltip,
}: SortHeaderProps) {
  const isActive = currentSort === column;
  return (
    // The interactive element is the inner <button>, not the <th> itself. This avoids
    // nested-interactive-element violations (WCAG 1.3.1 / 4.1.2): the sort button
    // contains only text, while the optional tooltip is rendered as a sibling outside
    // the button so its own trigger button does not nest inside ours.
    <TableHead
      className={cn('select-none', className)}
      role="columnheader"
      aria-sort={isActive ? (currentDir === 'asc' ? 'ascending' : 'descending') : 'none'}
    >
      <span className="inline-flex items-center gap-1">
        <button
          type="button"
          className="inline-flex items-center gap-1 cursor-pointer hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
          onClick={() => onSort(column)}
        >
          {label}
          {isActive && <span className="ml-0.5">{currentDir === 'asc' ? '↑' : '↓'}</span>}
        </button>
        {tooltip}
      </span>
    </TableHead>
  );
}
