import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:firebase_core/firebase_core.dart';
import 'ui/theme/app_theme.dart';
import 'screens/onboarding/onboarding_flow.dart';
import 'screens/tabs/main_shell.dart';
import 'services/auth_service.dart';
import 'services/firestore_service.dart';
import 'firebase_options.dart';
import 'screens/auth/login_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  try {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
  } catch (e) {
    print("Firebase init error (likely missing config): $e");
  }

  runApp(const ProviderScope(child: HeyAyuelApp()));
}

class HeyAyuelApp extends ConsumerStatefulWidget {
  const HeyAyuelApp({super.key});

  @override
  ConsumerState<HeyAyuelApp> createState() => _HeyAyuelAppState();
}

class _HeyAyuelAppState extends ConsumerState<HeyAyuelApp> {
  @override
  Widget build(BuildContext context) {
    final authState = ref.watch(authStateProvider);
    final userProfileAsync = ref.watch(userProfileProvider);

    return MaterialApp(
      title: 'Hey Ayuel',
      theme: AppTheme.themeData,
      debugShowCheckedModeBanner: false,
      home: authState.when(
        data: (user) {
          if (user == null) {
            return const LoginScreen();
          }

          return userProfileAsync.when(
            data: (profile) {
              if (profile == null || !profile.onboardingComplete) {
                return const OnboardingFlow();
              }
              return const MainShell();
            },
            loading: () => const Scaffold(
              body: Center(child: CircularProgressIndicator()),
            ),
            error: (e, st) => Scaffold(body: Center(child: Text("Error: $e"))),
          );
        },
        loading: () =>
            const Scaffold(body: Center(child: CircularProgressIndicator())),
        error: (e, st) => Scaffold(body: Center(child: Text("Auth Error: $e"))),
      ),
    );
  }
}
