#define DEBUG
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using AxCopilot.Services;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;

namespace AxCopilot.Views;

public class GuideViewerWindow : Window, IComponentConnector
{
	private string? _pendingHtml;

	private Uri? _pendingUri;

	internal TextBlock TitleText;

	internal TextBlock MaxBtnIcon;

	internal WebView2 GuideBrowser;

	private bool _contentLoaded;

	public GuideViewerWindow()
	{
		InitializeComponent();
		base.Loaded += OnLoaded;
		base.KeyDown += delegate(object _, KeyEventArgs e)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			if ((int)e.Key == 13)
			{
				Close();
			}
		};
		base.StateChanged += delegate
		{
			MaxBtnIcon.Text = ((base.WindowState == WindowState.Maximized) ? "\ue923" : "\ue922");
		};
	}

	private async void OnLoaded(object sender, RoutedEventArgs e)
	{
		bool devMode = (Application.Current as App)?.SettingsService?.Settings?.Llm?.DevMode == true;
		PrepareGuide(devMode);
		try
		{
			CoreWebView2Environment env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(Path.GetTempPath(), "AxCopilot_GuideViewer"));
			await GuideBrowser.EnsureCoreWebView2Async(env);
			if (_pendingHtml != null)
			{
				GuideBrowser.NavigateToString(_pendingHtml);
			}
			else if (_pendingUri != null)
			{
				GuideBrowser.Source = _pendingUri;
			}
		}
		catch (Exception ex)
		{
			Debug.WriteLine("WebView2 init error: " + ex.Message);
		}
	}

	public void PrepareGuide(bool devMode)
	{
		TitleText.Text = (devMode ? "AX Copilot 개발자 가이드" : "AX Copilot 사용 가이드");
		base.Title = (devMode ? "AX Copilot — 개발자 가이드" : "AX Copilot — 사용 가이드");
		try
		{
			string path = Path.GetDirectoryName(Environment.ProcessPath) ?? AppContext.BaseDirectory;
			string path2 = Path.Combine(path, "Assets");
			string text = (devMode ? Path.Combine(path2, "guide_dev.enc") : Path.Combine(path2, "guide_user.enc"));
			if (File.Exists(text))
			{
				_pendingHtml = GuideEncryptor.DecryptToString(text);
				return;
			}
			string text2 = (devMode ? Path.Combine(path2, "AX Copilot 개발자가이드.htm") : Path.Combine(path2, "AX Copilot 사용가이드.htm"));
			if (File.Exists(text2))
			{
				_pendingUri = new Uri(text2);
			}
			else
			{
				_pendingHtml = "<html><body style='font-family:Segoe UI;padding:40px;color:#666;'><h2>가이드를 찾을 수 없습니다</h2><p>경로: " + text + "</p></body></html>";
			}
		}
		catch (Exception ex)
		{
			_pendingHtml = "<html><body style='font-family:Segoe UI;padding:40px;color:#c00;'><h2>가이드 로드 오류</h2><p>" + ex.Message + "</p></body></html>";
		}
	}

	public void LoadGuide(bool devMode)
	{
		PrepareGuide(devMode);
		if (GuideBrowser.CoreWebView2 != null)
		{
			if (_pendingHtml != null)
			{
				GuideBrowser.NavigateToString(_pendingHtml);
			}
			else if (_pendingUri != null)
			{
				GuideBrowser.Source = _pendingUri;
			}
		}
	}

	private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
	{
		if (e.ClickCount == 2)
		{
			ToggleMaximize();
		}
		else
		{
			DragMove();
		}
	}

	private void MinBtn_Click(object sender, MouseButtonEventArgs e)
	{
		e.Handled = true;
		base.WindowState = WindowState.Minimized;
	}

	private void MaxBtn_Click(object sender, MouseButtonEventArgs e)
	{
		e.Handled = true;
		ToggleMaximize();
	}

	private void CloseBtn_Click(object sender, MouseButtonEventArgs e)
	{
		e.Handled = true;
		Close();
	}

	private void ToggleMaximize()
	{
		base.WindowState = ((base.WindowState != WindowState.Maximized) ? WindowState.Maximized : WindowState.Normal);
	}

	private void TitleBtn_Enter(object sender, MouseEventArgs e)
	{
		if (sender is Border border)
		{
			border.Background = (TryFindResource("ItemHoverBackground") as Brush) ?? new SolidColorBrush(Color.FromArgb(24, byte.MaxValue, byte.MaxValue, byte.MaxValue));
		}
	}

	private void CloseBtnEnter(object sender, MouseEventArgs e)
	{
		if (sender is Border border)
		{
			border.Background = new SolidColorBrush(Color.FromArgb(68, byte.MaxValue, 64, 64));
		}
	}

	private void TitleBtn_Leave(object sender, MouseEventArgs e)
	{
		if (sender is Border border)
		{
			border.Background = Brushes.Transparent;
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "10.0.5.0")]
	public void InitializeComponent()
	{
		if (!_contentLoaded)
		{
			_contentLoaded = true;
			Uri resourceLocator = new Uri("/AxCopilot;component/views/guideviewerwindow.xaml", UriKind.Relative);
			Application.LoadComponent(this, resourceLocator);
		}
	}

	[DebuggerNonUserCode]
	[GeneratedCode("PresentationBuildTasks", "10.0.5.0")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	void IComponentConnector.Connect(int connectionId, object target)
	{
		switch (connectionId)
		{
		case 1:
			((Border)target).MouseLeftButtonDown += TitleBar_MouseLeftButtonDown;
			break;
		case 2:
			TitleText = (TextBlock)target;
			break;
		case 3:
			((Border)target).MouseLeftButtonDown += MinBtn_Click;
			((Border)target).MouseEnter += TitleBtn_Enter;
			((Border)target).MouseLeave += TitleBtn_Leave;
			break;
		case 4:
			((Border)target).MouseLeftButtonDown += MaxBtn_Click;
			((Border)target).MouseEnter += TitleBtn_Enter;
			((Border)target).MouseLeave += TitleBtn_Leave;
			break;
		case 5:
			MaxBtnIcon = (TextBlock)target;
			break;
		case 6:
			((Border)target).MouseLeftButtonDown += CloseBtn_Click;
			((Border)target).MouseEnter += CloseBtnEnter;
			((Border)target).MouseLeave += TitleBtn_Leave;
			break;
		case 7:
			GuideBrowser = (WebView2)target;
			break;
		default:
			_contentLoaded = true;
			break;
		}
	}
}
