import * as ProgressPrimitive from '@radix-ui/react-progress';

import * as React from 'react';

import { cn } from '@/lib/utils';

interface ProgressProps extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> {
  /**
   * A11Y-004: When true, shows a visible percentage label above the progress bar.
   * The percentage is also always present as an sr-only label for screen readers.
   */
  showLabel?: boolean;
  /** Custom label text. Defaults to "{value}%" when not provided. */
  label?: string;
}

const Progress = React.forwardRef<React.ElementRef<typeof ProgressPrimitive.Root>, ProgressProps>(
  ({ className, value, showLabel = false, label, ...props }, ref) => {
    const percentage = Math.round(value || 0);
    const labelText = label ?? `${percentage}%`;

    return (
      <div className="w-full">
        {showLabel && (
          <div className="flex justify-between items-center mb-1">
            <span className="text-xs text-muted-foreground font-medium">{labelText}</span>
          </div>
        )}
        <ProgressPrimitive.Root
          ref={ref}
          className={cn('relative h-4 w-full overflow-hidden rounded-full bg-secondary', className)}
          aria-valuenow={percentage}
          aria-valuemin={0}
          aria-valuemax={100}
          aria-label={labelText}
          {...props}
        >
          <ProgressPrimitive.Indicator
            className="h-full w-full flex-1 bg-primary transition-all duration-500 ease-out"
            style={{ transform: `translateX(-${100 - percentage}%)` }}
          />
        </ProgressPrimitive.Root>
        {/* Always available to screen readers even when showLabel=false */}
        {!showLabel && <span className="sr-only">{labelText}</span>}
      </div>
    );
  },
);
Progress.displayName = ProgressPrimitive.Root.displayName;

export { Progress };
