import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'client_main_state.dart';

class ClientMainCubit extends Cubit<ClientMainState> implements Disposable {
  ClientMainCubit() : super(const ClientMainState()) {
    Modular.to.addListener(_onRouteChanged);
    _onRouteChanged();
  }

  void _onRouteChanged() {
    final String path = Modular.to.path;
    int newIndex = state.currentIndex;

    // Detect which tab is active based on the route path
    // Using contains() to handle child routes and trailing slashes
    if (path.contains('/client-main/coverage')) {
      newIndex = 0;
    } else if (path.contains('/client-main/billing')) {
      newIndex = 1;
    } else if (path.contains('/client-main/home')) {
      newIndex = 2;
    } else if (path.contains('/client-main/orders')) {
      newIndex = 3;
    } else if (path.contains('/client-main/reports')) {
      newIndex = 4;
    }

    if (newIndex != state.currentIndex) {
      emit(state.copyWith(currentIndex: newIndex));
    }
  }

  void navigateToTab(int index) {
    if (index == state.currentIndex) return;

    switch (index) {
      case 0:
        Modular.to.navigate('/client-main/coverage');
        break;
      case 1:
        Modular.to.navigate('/client-main/billing');
        break;
      case 2:
        Modular.to.navigate('/client-main/home');
        break;
      case 3:
        Modular.to.navigate('/client-main/orders');
        break;
      case 4:
        Modular.to.navigate('/client-main/reports');
        break;
    }
    // State update will happen via _onRouteChanged
  }

  @override
  void dispose() {
    Modular.to.removeListener(_onRouteChanged);
    close();
  }
}
