import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:pdfrx/pdfrx.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'editor/pdf/pen_capture_region.dart';
import 'providers/settings_provider.dart';
import 'screens/home_screen.dart';
import 'services/database_service.dart';

Future<void> main() async {
  // Kind-aware binding (extends WidgetsFlutterBinding) must be the active
  // binding before runApp so the M1 spike's PenCaptureRegion can gate
  // hit-testing by pointer kind. Safe for the rest of the app: with no pen
  // region mounted it behaves exactly like the default binding.
  PenCaptureBinding.ensureInitialized();
  // pdfrx native engine init (required before any PdfViewer is built).
  pdfrxFlutterInitialize();

  // Ensure DB is ready before the app starts so providers can use it eagerly
  await DatabaseService.getInstance();

  // Initialize SharedPreferences
  await SharedPreferences.getInstance();

  runApp(const ProviderScope(child: BadNoteApp()));
}

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

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

    // Material You: prefer the OS dynamic color (Windows/Android system accent);
    // fall back to the user's seed color when the platform provides none.
    return DynamicColorBuilder(
      builder: (lightDynamic, darkDynamic) {
        final lightScheme = lightDynamic?.harmonized() ??
            ColorScheme.fromSeed(
              seedColor: settings.colorSchemeSeed,
              brightness: Brightness.light,
            );
        final darkScheme = darkDynamic?.harmonized() ??
            ColorScheme.fromSeed(
              seedColor: settings.colorSchemeSeed,
              brightness: Brightness.dark,
            );
        return MaterialApp(
          title: 'BadNote',
          themeMode: settings.themeMode,
          theme: _theme(lightScheme),
          darkTheme: _theme(darkScheme),
          home: const HomeScreen(),
        );
      },
    );
  }

  ThemeData _theme(ColorScheme scheme) => ThemeData(
        colorScheme: scheme,
        useMaterial3: true,
        textTheme: GoogleFonts.interTextTheme(
          ThemeData(brightness: scheme.brightness).textTheme,
        ),
      );
}
