using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Hua.Todo.Avalonia.Models;
using Hua.Todo.Avalonia.Services;
using System;

namespace Hua.Todo.Avalonia.Views;

/// <summary>
/// 应用主窗口。
/// 负责承载 WebView（前端 UI）并在导航完成后注入前端契约字段。
/// </summary>
public partial class MainWindow : Window
{
    private readonly AppSettings _appSettings;
    private readonly IEmbeddedWebServerService _webServer;

    /// <summary>
    /// 创建用于设计器预览的主窗口实例。
    /// </summary>
    public MainWindow()
    {
        InitializeComponent();
        _appSettings = new AppSettings();
        _webServer = new EmbeddedWebServerService(_appSettings);
    }

    /// <summary>
    /// 创建运行时主窗口实例。
    /// </summary>
    /// <param name="appSettings">应用配置。</param>
    /// <param name="webServer">嵌入式 WebServer。</param>
    public MainWindow(AppSettings appSettings, IEmbeddedWebServerService webServer)
    {
        InitializeComponent();
        _appSettings = appSettings;
        _webServer = webServer;

        SetupWebView();
    }

    private void SetupWebView()
    {
        try
        {
            MainWebView.Url = 
                _appSettings.WebServer.IsUsingStatic 
                    ? new Uri(_appSettings.WebServer.HostUrl) 
                    : new Uri(_appSettings.WebServer.ForEndUrl);

            MainWebView.NavigationCompleted += async (s, e) =>
            {
                try
                {
                    if (_webServer.IsRunning)
                    {
                        var apiBase = $"{_webServer.BaseUrl.TrimEnd('/')}/api";
                        await MainWebView.ExecuteScriptAsync($"window.__API_BASE_URL__ = '{apiBase}';");
                    }

                    await MainWebView.ExecuteScriptAsync(@"
                        window.mauiInterop = {
                            onHotKeyConfigUpdated: null,
                            openHotKeySettings: function(config) {
                                const event = new CustomEvent('openHotKeySettings', { detail: config });
                                window.dispatchEvent(event);
                            },
                            updateHotKeyConfig: function(modifiers, key, isEnabled) {
                                const event = new CustomEvent('updateHotKeyConfig', {
                                    detail: { modifiers, key, isEnabled }
                                });
                                window.dispatchEvent(event);
                            }
                        };

                        window.addEventListener('hotKeyConfigChanged', function(e) {
                            if (window.mauiInterop.onHotKeyConfigUpdated) {
                                window.mauiInterop.onHotKeyConfigUpdated(e.detail);
                            }
                        });
                    ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[MainWindow] WebView script injection failed: {ex.Message}");
                }
            };
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[MainWindow] WebView initialization failed: {ex}");
            Content = new TextBlock
            {
                Text = "WebView 初始化失败。请检查运行环境依赖（Windows 需要 WebView2 Runtime；Linux 需要 WebKitGTK）。",
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                TextWrapping = TextWrapping.Wrap
            };
        }
    }
}
