import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:onsolgo/navigation_hub.dart';
import 'package:onsolgo/screens/auth/login_screen.dart';
import 'package:onsolgo/core/constants.dart';
import 'firebase_options.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (!kIsWeb) {
    // 1. INITIALIZE AD ENGINE
    MobileAds.instance.initialize();

    // 2. CONFIGURE TEST DEVICE (Mandatory for Pixel 10 Pro)
    // This ID comes directly from your console logs
    RequestConfiguration configuration = RequestConfiguration(
        testDeviceIds: ["949E2F2F6403B732392FF2648C5D9B85"]);
    MobileAds.instance.updateRequestConfiguration(configuration);
  }

  PaintingBinding.instance.imageCache.maximumSizeBytes = 300 * 1024 * 1024;
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  FirebaseFirestore.instance.settings = const Settings(persistenceEnabled: true);

  runApp(const OnsolGoApp());
}

class OnsolGoApp extends StatelessWidget {
  const OnsolGoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'ONSOL-GO!',
      theme: ThemeData(
        useMaterial3: true,
        brightness: Brightness.dark,
        scaffoldBackgroundColor: Colors.black,
        canvasColor: Colors.black,
        colorScheme: ColorScheme.fromSeed(
          seedColor: kOnsolGold,
          brightness: Brightness.dark,
          surface: Colors.black,
          surfaceTint: Colors.transparent,
        ),
        appBarTheme: const AppBarTheme(backgroundColor: Colors.black, surfaceTintColor: Colors.transparent, elevation: 0),
        cardTheme: const CardThemeData(color: Colors.black, surfaceTintColor: Colors.transparent),
      ),
      home: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, authSnapshot) {
          if (authSnapshot.hasData) {
            return StreamBuilder<DocumentSnapshot>(
              stream: FirebaseFirestore.instance.collection('users').doc(authSnapshot.data!.uid).snapshots(),
              builder: (context, userSnapshot) {
                if (!userSnapshot.hasData) return const Scaffold(body: Center(child: CircularProgressIndicator(color: kOnsolGold)));
                if (!userSnapshot.data!.exists) return const NavigationHub();
                var userData = userSnapshot.data!.data() as Map<String, dynamic>;
                if (userData['isBanned'] == true) {
                  return const Scaffold(
                    body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                      Icon(Icons.gavel, color: Colors.red, size: 80),
                      Text("EXILED", style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold, fontSize: 32, letterSpacing: 10)),
                      Text("REMOVED FROM THE ORDER", style: TextStyle(color: Colors.white54, fontSize: 10)),
                    ])),
                  );
                }
                return const NavigationHub();
              },
            );
          }
          return const LoginScreen();
        },
      ),
    );
  }
}