import { ChangeDetectionStrategy, Component, contentChildren, signal } from '@angular/core';
import { StepComponent } from './step.component';
import { NgClass } from '@angular/common';

@Component({
  selector: 'app-stepper',
  imports: [NgClass],
  templateUrl: './stepper.component.html',
  styleUrl: './stepper.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class StepperComponent {
  readonly steps = contentChildren(StepComponent);
  readonly currentStepIndex = signal(0);

  next() {
    const currentSteps = this.steps();
    const currentIndex = this.currentStepIndex();
    if (currentIndex < currentSteps.length - 1) {
      const currentStep = currentSteps[currentIndex];
      if (currentStep.isValid()) {
        this.currentStepIndex.set(currentIndex + 1);
      }
    }
  }

  previous() {
    const currentIndex = this.currentStepIndex();
    if (currentIndex > 0) {
      this.currentStepIndex.set(currentIndex - 1);
    }
  }

  goToStep(index: number) {
    const targetIndex = index;
    // Only allow navigating to completed steps or the current one
    if (targetIndex < this.currentStepIndex()) {
      this.currentStepIndex.set(targetIndex);
    }
  }
}
