import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_vodozemac/flutter_vodozemac.dart' as vod;
import 'package:media_kit/media_kit.dart';
import 'package:pyramid/core/app.dart';
import 'package:pyramid/core/background_push.dart';
import 'package:pyramid/core/matrix_client.dart';
import 'package:pyramid/features/auth/login_notifier.dart';
import 'package:pyramid/widgets/pyramid_loader.dart';

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

  if (Platform.isAndroid) {
    // Firebase must be initialised first, then the background handler registered.
    try { await Firebase.initializeApp(); } catch (_) {}
    FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
    // Store the background-engine callback handle so PushService.kt /
    // ReplyReceiver can decrypt + send encrypted replies when the app is killed.
    await registerBgEngineHandle();
  }

  // Catch unhandled async exceptions to prevent silent crashes
  FlutterError.onError = (details) {
    FlutterError.presentError(details);
  };

  await vod.init();

  // Hide status bar and navigation bar for immersive feel
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  
  runApp(const ProviderScope(child: PyramidBootstrap()));
}

class PyramidBootstrap extends ConsumerWidget {
  const PyramidBootstrap({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final clientAsync = ref.watch(matrixClientProvider);

    return clientAsync.when(
      loading: () => const MaterialApp(
        home: Scaffold(body: Center(child: PyramidLoader(size: 80))),
      ),
      error: (e, _) => MaterialApp(
        home: Scaffold(body: Center(child: Text('Fehler: $e'))),
      ),
      data: (_) {
        // Homeserver einmalig aus SharedPreferences laden
        initHomeserver(ref);
        return const PyramidApp();
      },
    );
  }
}
