import 'dart:io';
import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';
import 'app.dart';
import 'services/image_manager.dart';
import 'services/window_persistence.dart';

void main(List<String> args) async {
  WidgetsFlutterBinding.ensureInitialized();

  ImageManager.configureCache();

  await windowManager.ensureInitialized();

  // Restore saved window position/size or use defaults
  final saved = WindowPersistence.restore();
  final defaultSize = const Size(1280, 800);

  final windowOptions = WindowOptions(
    size: saved?.size ?? defaultSize,
    minimumSize: const Size(400, 300),
    backgroundColor: Colors.transparent,
    titleBarStyle: TitleBarStyle.hidden,
  );

  await windowManager.waitUntilReadyToShow(windowOptions, () async {
    if (saved != null) {
      final position = await WindowPersistence.cascadePosition(
        previousPosition: saved.position,
        previousSize: saved.size,
      );
      await windowManager.setPosition(position);
      await windowManager.setSize(saved.size);
    } else {
      await windowManager.center();
    }
    await windowManager.setResizable(true);
    await windowManager.show();
    await windowManager.focus();

    // Açılış konumunu hemen kaydet — sıradaki pencere güncel referans okusun
    final pos = await windowManager.getPosition();
    final size = await windowManager.getSize();
    WindowPersistence.saveSync(position: pos, size: size);
  });

  // Extract file paths from command-line arguments
  final filePaths = args.where((a) => !a.startsWith('-') && a != Platform.script.path).toList();

  runApp(ImajViewerApp(initialFiles: filePaths));
}
