import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'services/audio_service.dart';
import 'services/call_session.dart';
import 'ui/screens/home_screen.dart';

/// Entry point.
///
/// Creates singleton [AudioService] and [CallSession] that live for the
/// application lifetime, then hands them to the UI tree.
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // Force portrait orientation — prevents mic/speaker routing changes on rotate.
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  // Dark status bar on transparent background.
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarColor:           Colors.transparent,
    statusBarIconBrightness:  Brightness.light,
    systemNavigationBarColor: Color(0xFF0D0D1A),
  ));

  final audio   = AudioService();
  final session = CallSession(audio);

  runApp(SecureCallApp(session: session));
}

class SecureCallApp extends StatefulWidget {
  final CallSession session;
  const SecureCallApp({super.key, required this.session});

  @override
  State<SecureCallApp> createState() => _SecureCallAppState();
}

class _SecureCallAppState extends State<SecureCallApp>
    with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    widget.session.dispose();
    super.dispose();
  }

  /// Pause TX/RX when the app is backgrounded; resume requires manual PTT.
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused ||
        state == AppLifecycleState.detached) {
      widget.session.pttRelease();
      widget.session.stopListening();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SecureCall',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        brightness:  Brightness.dark,
        colorScheme: const ColorScheme.dark(
          primary:   Color(0xFF00C853),
          secondary: Color(0xFF00B0FF),
          surface:   Color(0xFF1A1A2E),
        ),
        scaffoldBackgroundColor: const Color(0xFF0D0D1A),
        fontFamily: 'Roboto',
        useMaterial3: true,
      ),
      home: HomeScreen(session: widget.session),
    );
  }
}
