export default function MissionRail({
  chapters,
  runQuestions,
  completed,
  currentChapterId,
  onSelect
}) {
  const chapterProgress = chapters.map((chapter) => {
    const selected = runQuestions.filter(
      (question) => question.chapterId === chapter.id
    );
    const done = selected.filter((question) =>
      completed.includes(question.id)
    ).length;
    return { ...chapter, selected, done, complete: done === selected.length };
  });
  const firstOpen = chapterProgress.findIndex((chapter) => !chapter.complete);

  return (
    <nav className="mission-rail" aria-label="Kapitel">
      <div className="rail-heading">
        <span>KAPITELLOG</span>
        <strong>{completed.length}/{runQuestions.length}</strong>
      </div>
      <ol>
        {chapterProgress.map((chapter, index) => {
          const isOpen =
            chapter.complete || index === firstOpen || firstOpen === -1;
          const isCurrent = currentChapterId === chapter.id;
          return (
            <li key={chapter.id}>
              <button
                type="button"
                className={`${chapter.complete ? "done" : ""} ${isCurrent ? "current" : ""}`}
                disabled={!isOpen}
                onClick={() => onSelect(chapter.id)}
                aria-current={isCurrent ? "step" : undefined}
              >
                <span className="mission-number">
                  {chapter.complete ? "✓" : chapter.number}
                </span>
                <span className="mission-nav-copy">
                  <strong>{chapter.topic}</strong>
                  <small>
                    {chapter.done}/{chapter.selected.length} Fragen
                  </small>
                </span>
                {!isOpen && <span className="lock-glyph">×</span>}
              </button>
            </li>
          );
        })}
      </ol>
    </nav>
  );
}
