import * as React from "react";

export interface ProgressBarSegment {
  value: number;
  color?: string;
  label?: React.ReactNode;
}

export interface ProgressBarProps {
  /** Simple single-fill mode (uses --fg). Mutually exclusive with `segments`. */
  percent?: number;
  /** Stacked multi-fill mode with an optional legend row. */
  segments?: ProgressBarSegment[];
  /** Defaults to true when more than one segment is given. */
  showLegend?: boolean;
  className?: string;
}

export function ProgressBar({ percent, segments, showLegend, className }: ProgressBarProps) {
  const classes = ["ads-progress-bar"];
  if (className) classes.push(className);

  if (segments && segments.length > 0) {
    const total = segments.reduce((sum, s) => sum + s.value, 0) || 1;
    const legend = showLegend ?? segments.length > 1;
    return (
      <div className={classes.join(" ")}>
        <div className="ads-bar">
          {segments.map((seg, i) => (
            <i
              key={i}
              style={{ flex: seg.value / total, background: seg.color ?? "var(--fg)" }}
            />
          ))}
        </div>
        {legend && (
          <div className="ads-legend">
            {segments.map((seg, i) => (
              <span key={i}>
                <i style={{ background: seg.color ?? "var(--fg)" }} />
                {seg.label}
              </span>
            ))}
          </div>
        )}
      </div>
    );
  }

  const clamped = Math.max(0, Math.min(100, percent ?? 0));
  return (
    <div className={classes.join(" ")}>
      <div className="ads-balken">
        <i style={{ width: `${clamped}%` }} />
      </div>
    </div>
  );
}
