import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'screens/screens.dart';
import 'storage/local_storage.dart';
import 'theme.dart';

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

  // Initialize database
  await LocalStorage.database;

  // Set preferred orientations
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  runApp(const AddMonthsApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Add Months',
      debugShowCheckedModeBanner: false,
      theme: buildAppTheme(),
      home: const AppRouter(),
    );
  }
}

class AppRouter extends StatefulWidget {
  const AppRouter({super.key});

  @override
  State<AppRouter> createState() => _AppRouterState();
}

class _AppRouterState extends State<AppRouter> {
  bool _loading = true;
  bool _hasCompletedOnboarding = false;

  @override
  void initState() {
    super.initState();
    _checkState();
  }

  Future<void> _checkState() async {
    // Check if user has ever completed a run (has saved data)
    final hasData = await LocalStorage.hasCompletedSetup();
    setState(() {
      _hasCompletedOnboarding = hasData;
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    // First launch: show onboarding
    // Returning users: show welcome screen (where they can start fresh or continue)
    if (_hasCompletedOnboarding) {
      return const WelcomeScreen();
    }

    return const OnboardingScreen();
  }
}
