using FairyView;

namespace StandardScene.CarTypes
{
    /// <summary>
    /// 长文本只读查看面板（CycleGUI 版，替代原 WinForms <c>TextViewer</c> 窗体）。
    /// 保留可实例化 + <see cref="Show"/> 以兼容 <c>new TextViewer().Show()</c> 与 <see cref="UpdateText"/> 调用。
    /// </summary>
    public class TextViewer
    {
        private Panel _panel;
        private volatile string _text = "";

        /// <summary>打开（或置前）文本查看面板。</summary>
        public void Show() => Open();

        /// <summary>打开（或置前）文本查看面板。</summary>
        public void Open()
        {
            if (_panel != null)
            {
                try
                {
                    _panel.BringToFront();
                    return;
                }
                catch
                {
                    _panel = null;
                }
            }

            var panel = GUI.DeclarePanel()
                .ShowTitle("TextViewer")
                .ForceFloat()
                .InitSize(800, 600)
                .InitPos(false, 0, 0, 0.5f, 0.5f, 0.5f, 0.5f);
            _panel = panel;
            panel.IfTerminalQuit(() => { if (_panel == panel) _panel = null; });

            panel.Define(pb =>
            {
                if (pb.Closing())
                {
                    panel.Exit();
                    if (_panel == panel) _panel = null;
                    return;
                }

                pb.SelectableText(null, _text ?? "", copyButton: true);
                pb.Panel.Repaint(repaintTimeMs: 200);
            });
        }

        /// <summary>更新显示文本并触发面板重绘（可从非渲染线程调用）。</summary>
        public void UpdateText(string str)
        {
            _text = str ?? "";
            _panel?.Repaint();
        }
    }
}
