using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace MyCodeEditor; // можно любое, но запомни для поиска в VL

public static class GammaWpfEditorHost
{
    private static Thread? _uiThread;
    private static Window? _window;

    public static void Toggle()
    {
        // 1) Первый вызов: поднимаем STA поток и окно
        if (_uiThread is null || !_uiThread.IsAlive)
        {
            _uiThread = new Thread(() =>
            {
                // Важно: WPF требует STA
                _window = new Window
                {
                    Title = "Gamma Editor Host (WPF test)",
                    Width = 900,
                    Height = 600,
                    Content = new TextBlock
                    {
                        Text = "WPF host OK. Next step: RoslynPad editor control.",
                        Margin = new Thickness(20),
                        TextWrapping = TextWrapping.Wrap
                    }
                };

                _window.Closed += (_, __) =>
                {
                    _window = null;
                    System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvokeShutdown(
                        System.Windows.Threading.DispatcherPriority.Background);
                };

                _window.Show();

                // Простая message loop без Application.Current
                System.Windows.Threading.Dispatcher.Run();
            });

            _uiThread.IsBackground = true;
            _uiThread.SetApartmentState(ApartmentState.STA);
            _uiThread.Start();

            return;
        }

        // 2) Повторные вызовы: show/hide через Dispatcher окна
        _window?.Dispatcher.Invoke(() =>
        {
            if (_window is null) return;

            if (_window.IsVisible)
                _window.Hide();
            else
            {
                _window.Show();
                _window.Activate();
            }
        });
    }
}
