import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart'; // 🔥 penting untuk kIsWeb

import 'screens/login_screen.dart';
import 'screens/dashboard_screen.dart';

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

  // 🔥 FIX: beda config untuk Web & Android
  if (kIsWeb) {
    await Firebase.initializeApp(
      options: const FirebaseOptions(
        apiKey: "AIzaSyCUWqvWU8QVDG8fEMf4MkTAxPe7JkxHxNw",
        appId: "1:891255404913:web:b2b9fb4aa2224250301ed0",
        messagingSenderId: "891255404913",
        projectId: "sigesit-48741",
        authDomain: "sigesit-48741.firebaseapp.com",
        databaseURL: "https://sigesit-48741-default-rtdb.firebaseio.com",
        storageBucket: "sigesit-48741.firebasestorage.app",
        measurementId: "G-SXC9T26ZPL",
      ),
    );
  } else {
    // 🤖 Android
    await Firebase.initializeApp(
      options: const FirebaseOptions(
        apiKey: "AIzaSyC8UGmmWnMYx959UPy-CQefsC-4rxegLqg",
        appId: "1:891255404913:android:ec766602dbad46f6301ed0",
        messagingSenderId: "891255404913",
        projectId: "sigesit-48741",
        databaseURL: "https://sigesit-48741-default-rtdb.firebaseio.com",
        storageBucket: "sigesit-48741.firebasestorage.app",
      ),
    );
  }

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Selada Hidroponik',
      theme: ThemeData(
        primarySwatch: Colors.green,
        useMaterial3: true,
      ),
      home: const AuthWrapper(),
    );
  }
}

class AuthWrapper extends StatelessWidget {
  const AuthWrapper({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(
                color: Color(0xFF2E7D32),
              ),
            ),
          );
        }

        // ❌ Error Firebase
        if (snapshot.hasError) {
          return const Scaffold(
            body: Center(
              child: Text("Terjadi kesalahan koneksi ke Firebase"),
            ),
          );
        }

        // ✅ Sudah login
        if (snapshot.hasData) {
          return const DashboardScreen();
        }

        // 🔐 Belum login
        return const LoginScreen();
      },
    );
  }
}
