import 'package:flutter/material.dart';
import 'package:sizer/sizer.dart';

import './services/app_state_service.dart';
import './services/supabase_service.dart';
import './services/api_client.dart';
import 'core/app_export.dart';

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

  try {
    // Initialize Supabase (required for app functionality)
    try {
      await SupabaseService.initialize();
      debugPrint('✅ Supabase initialized successfully');
    } catch (e) {
      debugPrint('❌ Supabase initialization failed: $e');
      debugPrint('   Make sure to run with: ./scripts/run-flutter-supabase.sh');
      // Continue - app will show error UI
    }

    // Initialize API Client (optional, for PostgreSQL backend)
    try {
      final apiBaseUrl = ApiClient.getBaseUrl();
      ApiClient.instance.initialize(baseUrl: apiBaseUrl);
      debugPrint('✅ API Client initialized: $apiBaseUrl');
    } catch (e) {
      debugPrint('⚠️ API Client initialization skipped: $e');
    }

    // Initialize global app state
    await AppStateService().initialize();
    debugPrint('✅ App state initialized successfully');
  } catch (e) {
    debugPrint('❌ Initialization failed: $e');
    // Continue running the app even if initialization fails
  }

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return Sizer(
      builder: (context, orientation, deviceType) {
        return AnimatedBuilder(
          animation: AppStateService(),
          builder: (context, child) {
            return MaterialApp(
              title: 'SIBU - Sistema de Transporte',
              theme: AppTheme.lightTheme,
              darkTheme: AppTheme.darkTheme,
              themeMode: ThemeMode.system,
              debugShowCheckedModeBanner: false,
              builder: (context, child) {
                return MediaQuery(
                  data: MediaQuery.of(context).copyWith(
                    textScaler: TextScaler.linear(1.0),
                  ),
                  child: child!,
                );
              },
              routes: AppRoutes.routes,
              initialRoute: AppRoutes.splash,
            );
          },
        );
      },
    );
  }
}
