import React from 'react';
import { useShadeRuntimeTheme } from '../../ShadeRuntimeProvider.js';

export interface ProgressBarProps {
  /** Progress in [0, 1]. Undefined → indeterminate. */
  percent?: number;
  height?: number;
  className?: string;
  style?: React.CSSProperties;
}

export function ProgressBar({
  percent,
  height = 6,
  className,
  style,
}: ProgressBarProps): React.ReactElement {
  const theme = useShadeRuntimeTheme();
  const track = theme.progressTrack ?? theme.border;
  const fill = theme.progressFill ?? theme.accent;
  const indeterminate = theme.progressFillIndeterminate ?? theme.accentMuted;
  const isIndeterminate = percent === undefined;
  const widthPct = isIndeterminate ? 100 : Math.max(0, Math.min(1, percent)) * 100;
  return (
    <div
      className={className}
      role="progressbar"
      aria-valuemin={0}
      aria-valuemax={100}
      {...(percent !== undefined ? { 'aria-valuenow': Math.round(percent * 100) } : {})}
      style={{
        width: '100%',
        height,
        background: track,
        borderRadius: height / 2,
        overflow: 'hidden',
        position: 'relative',
        ...style,
      }}
    >
      <div
        style={{
          width: `${widthPct}%`,
          height: '100%',
          background: isIndeterminate ? indeterminate : fill,
          transition: isIndeterminate ? undefined : 'width 0.18s linear',
        }}
      />
    </div>
  );
}
