import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:firebase_auth/firebase_auth.dart';

import 'pages/start_page.dart';
import 'pages/main_page.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "RFID App",

      // 🔥 OPTIONAL THEME (BIAR CONSISTENT)
      theme: ThemeData(
        primaryColor: const Color(0xff3b82f6),
        scaffoldBackgroundColor: Colors.grey[100],
      ),

      home: const AuthGate(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        // 🔄 LOADING
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        // ✅ SUDAH LOGIN → MASUK MAIN PAGE (ADA NAVBAR)
        if (snapshot.hasData) {
          return const MainPage();
        }

        // ❌ BELUM LOGIN → TAMPILKAN START PAGE
        return const StartPage();
      },
    );
  }
}
