import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../bloc/onboarding_bloc.dart';
import '../bloc/onboarding_event.dart';
import '../bloc/onboarding_state.dart';
import '../widgets/build_page_widget.dart';

class WelcomeLayout extends StatelessWidget {
  final PageController _pageController = PageController();
  WelcomeLayout({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: BlocListener<OnboardingBloc, OnboardingState>(
        // Define the listener for the BlocListener
        listener: (context, state) {
          // If the state is OnboardingPageChanged, animate to the corresponding page
          if (state is OnboardingPageChanged) {
            _pageController.animateToPage(
              state.currentPage,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          }
        },
        child: PageView.builder(
          controller: _pageController,
          itemCount: 3, // Number of onboarding pages
          itemBuilder: (context, index) {
            return buildPage(context, index, _pageController);
          },
          onPageChanged: (index) {
            // Dispatch the JumpToPage event to update the current page
            context.read<OnboardingBloc>().add(JumpToPage(index));
          },
        ),
      ),
    );
  }
}
