import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

part 'onboarding_event.dart';
part 'onboarding_state.dart';

class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
  OnboardingBloc() : super(const OnboardingInitial()) {
    on<OnboardingNextPressed>(_onNextPressed);
    on<OnboardingSkipPressed>(_onSkipPressed);
    on<OnboardingPageChanged>(_onPageChanged);
  }

  void _onNextPressed(OnboardingNextPressed event, Emitter<OnboardingState> emit) {
    final int currentIndex = _getCurrentIndex();
    if (currentIndex == event.totalPages - 1) {
      emit(OnboardingNavigateToLogin());
    } else {
      emit(OnboardingUpdate(currentIndex + 1));
    }
  }

  void _onSkipPressed(OnboardingSkipPressed event, Emitter<OnboardingState> emit) {
    emit(OnboardingNavigateToLogin());
  }

  void _onPageChanged(OnboardingPageChanged event, Emitter<OnboardingState> emit) {
    emit(OnboardingUpdate(event.index));
  }

  int _getCurrentIndex() {
    if (state is OnboardingInitial) {
      return (state as OnboardingInitial).currentIndex;
    } else if (state is OnboardingUpdate) {
      return (state as OnboardingUpdate).currentIndex;
    }
    return 0;
  }
}
