using System.Windows;
using DansoriEQ.App.Apo;
using Wpf.Ui.Appearance;

namespace DansoriEQ.App;

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        // PoC hook (Path B / Lottie). Run "DansoriEQ.App.exe --lottie" to open only the
        // Lottie test window, bypassing the normal splash/APO/main flow. Remove after decision.
        if (e.Args.Length > 0 && e.Args[0] == "--lottie")
        {
            ShutdownMode = ShutdownMode.OnMainWindowClose;
            var poc = new LottiePocWindow();
            MainWindow = poc;
            poc.Show();
            return;
        }

        // Keep the app alive while pre-main dialogs (splash / APO setup) open and close;
        // otherwise closing the splash with no other window would shut the app down.
        ShutdownMode = ShutdownMode.OnExplicitShutdown;

        // Surface unhandled UI-thread exceptions instead of silently terminating.
        DispatcherUnhandledException += (_, args) =>
        {
            System.Windows.MessageBox.Show(
                args.Exception.ToString(),
                "오류가 발생했습니다",
                MessageBoxButton.OK, MessageBoxImage.Error);
            args.Handled = true;   // keep the app alive
        };

        var s = AppSettings.Load();
        var theme = s.Theme switch
        {
            "light" => ApplicationTheme.Light,
            _ => ApplicationTheme.Dark
        };
        ApplicationThemeManager.Apply(theme);

        // Brand splash (이소리·이단) — brief, before the setup flow.
        try { new SplashWindow().ShowDialog(); } catch { /* splash is non-essential */ }

        var apoDir = ApoWriterFactory.ResolveConfigDir();
        if (apoDir is null)
        {
            new ApoSetupWindow().ShowDialog();
        }
        else if (!ApoConfigInstaller.IsIncluded(apoDir))
        {
            new ApoLinkWindow(apoDir).ShowDialog();
        }
        else
        {
            ApoConfigInstaller.EnsureAiEqFile(apoDir);
        }

        var main = new MainWindow();
        MainWindow = main;
        main.Show();

        // Now that the main window exists, tie app lifetime to it.
        ShutdownMode = ShutdownMode.OnMainWindowClose;
    }
}
