// ============================
// main.dart
// ============================

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

import 'firebase_options.dart';
import 'widgets/whatsapp_notification.dart';

// IMPORT PAGE
import 'screen/welcome.dart';
import 'screen/login.dart';
import 'screen/signup.dart';
import 'screen/dashboard.dart';
import 'screen/notifikasi.dart';
import 'screen/history.dart';

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

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

    // REALTIME CACHE
    if (!kIsWeb) {
      FirebaseDatabase.instance.setPersistenceEnabled(true);
    }
  } catch (e) {
    debugPrint("Firebase Init Error: $e");
  }

  runApp(const SafebiteApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      debugShowCheckedModeBanner: false,
      title: 'Safebite',

      theme: ThemeData(
        useMaterial3: true,
        colorSchemeSeed: const Color(0xFF4DB6AC),
        scaffoldBackgroundColor: const Color(0xFFF2F6F6),
      ),

      initialRoute: '/',

      routes: {
        '/': (context) => AuthGate(),
        '/welcome': (context) => WelcomePage(),
        '/login': (context) => LoginPage(),
        '/signup': (context) => RegisterPage(),
        '/dashboard': (context) => const DashboardPage(),
        '/notifikasi': (context) => const NotifikasiPage(),
        '/history': (context) => const RiwayatPage(),
      },
    );
  }
}

// ============================
// AUTH CHECK
// ============================

class AuthGate extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),

      builder: (context, snapshot) {

        if (snapshot.hasError) {

          debugPrint("AUTH ERROR: ${snapshot.error}");

          return WelcomePage();
        }

        if (snapshot.connectionState ==
            ConnectionState.waiting) {

          return const Scaffold(
            backgroundColor: Color(0xFFF2F6F6),
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }

        if (snapshot.hasData) {

          return const DashboardPage();
        }

        return WelcomePage();
      },
    );
  }
}