import 'package:autos/core/routing/app_router.dart';
import 'package:autos/core/routing/navigation_service.dart';
import 'package:autos/core/theme/app_theme.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:autos/presentation/screens/auth/login_screen.dart';
import 'package:autos/presentation/screens/dashboard/dashboard_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // ONESIGNAL SETUP (ADDED SAFELY)
  OneSignal.Debug.setLogLevel(OSLogLevel.verbose);
  OneSignal.initialize("271c3931-07ee-46b6-8629-7f0d63f58085");
  OneSignal.Notifications.requestPermission(false);

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

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

  @override
  ConsumerState<MyApp> createState() => _MyAppState();
}

class _MyAppState extends ConsumerState<MyApp> {
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _restoreSession();
  }

  Future<void> _restoreSession() async {
    final userNotifier = ref.read(userProvider.notifier);

    // ✅ Load user from secure storage (UNCHANGED)
    await userNotifier.loadUserFromStorage();

    // ✅ Stop loading after user is restored (UNCHANGED)
    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    // ✅ Loading screen (UNCHANGED)
    if (_isLoading) {
      return const MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Center(child: CircularProgressIndicator()),
        ),
      );
    }

    final userState = ref.watch(userProvider);
    final user = userState.value;

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Autos",
      theme: AppTheme.lightTheme,

      // ✅ Dynamic home based on session (UNCHANGED)
      home: user != null ? const DashboardScreen() : const LoginScreen(),

      navigatorKey: NavigationService.navigatorKey,
      onGenerateRoute: AppRouter.generateRoute,
    );
  }
}
