import './PipelineProgress.css';
import type { StageMap, StageStatus } from '../types/index.js';

export interface StageEntry {
  key: string;
  label: string;
}

export interface StageGroup {
  label: string;
  stages: StageEntry[];
}

interface PipelineProgressProps {
  stageGroups: StageGroup[];
  stages: StageMap;
  onRetry?: () => void;
}

function StageIcon({ status }: { status: StageStatus }) {
  switch (status) {
    case 'done':
      return <span class="stage-icon stage-done">✓</span>;
    case 'error':
      return <span class="stage-icon stage-error">✗</span>;
    case 'running':
      return <span class="stage-icon stage-running spinner">⟳</span>;
    case 'skipped':
      return <span class="stage-icon stage-skipped">—</span>;
    default:
      return <span class="stage-icon stage-pending">○</span>;
  }
}

export function PipelineProgress({ stageGroups, stages, onRetry }: PipelineProgressProps) {
  const hasError = Object.values(stages).some((s) => s === 'error');

  return (
    <div class="pipeline-progress">
      <h3 class="pipeline-title">{hasError ? 'Pipeline Failed' : 'Generating Recommendations…'}</h3>
      {stageGroups.map((group, gi) => (
        <div key={gi} class={`pipeline-pass-group${gi > 0 ? ' pipeline-pass-group--extra' : ''}`}>
          {group.label && <div class="pipeline-pass-label">{group.label}</div>}
          <ul class="pipeline-steps">
            {group.stages.map(({ key, label }) => {
              const status: StageStatus = stages[key] ?? 'pending';
              return (
                <li key={key} class={`pipeline-step pipeline-step--${status}`}>
                  <StageIcon status={status} />
                  <span class="pipeline-step-label">{label}</span>
                </li>
              );
            })}
          </ul>
        </div>
      ))}
      {hasError && onRetry && (
        <div class="pipeline-retry">
          <button class="btn-primary" onClick={onRetry}>Re-run Pipeline</button>
        </div>
      )}
    </div>
  );
}
