using System.Text;
using AvatarRefinery.Editor.Core;

namespace AvatarRefinery.Editor.UI
{
    /// <summary>IMGUI表示用のテキスト整形。</summary>
    public static class UiText
    {
        /// <summary>
        /// Unity IMGUI は半角スペースを改行位置とみなし、日本語の連続を1語として扱う。
        /// 「SDK のビルド画面」のように日本語と英単語の間にスペースがあると、英単語だけが行末に孤立して不自然な折り返しになる。
        /// → CJK文字に隣接するスペースを取り除く(英単語同士のスペースは残す)。
        /// </summary>
        public static string Wrap(string s)
        {
            if (string.IsNullOrEmpty(s) || s.IndexOf(' ') < 0) return s;
            var sb = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                if (c == ' ')
                {
                    bool prevCjk = i > 0 && IsCjk(s[i - 1]);
                    bool nextCjk = i + 1 < s.Length && IsCjk(s[i + 1]);
                    // 行頭のインデント用スペースは残す
                    bool lineStart = i == 0 || s[i - 1] == '\n' || (i > 0 && s[i - 1] == ' ' && (i == 1 || s[i - 2] == '\n'));
                    if ((prevCjk || nextCjk) && !lineStart) continue;
                }
                sb.Append(c);
            }
            return sb.ToString();
        }

        public static bool IsCjk(char c)
        {
            return (c >= 0x3000 && c <= 0x30FF)   // 記号・ひらがな・カタカナ
                || (c >= 0x4E00 && c <= 0x9FFF)   // 漢字
                || (c >= 0xFF00 && c <= 0xFFEF)   // 全角英数・記号
                || (c >= 0x3400 && c <= 0x4DBF);  // 漢字拡張A
        }

        /// <summary>UIで描画できる重要度アイコン(Unityの既定フォントは ⛔📉 を描画できないため)。</summary>
        public static string SeverityIcon(Severity s)
        {
            switch (s)
            {
                case Severity.Blocker: return "●";
                case Severity.Broken: return "▲";
                case Severity.Performance: return "▼";
                default: return "i";
            }
        }

        public static string SeverityColorHex(Severity s)
        {
            switch (s)
            {
                case Severity.Blocker: return "#ff5c5c";
                case Severity.Broken: return "#ffb347";
                case Severity.Performance: return "#ffd94d";
                default: return "#8ecdf5";
            }
        }

        public static string SeverityIconRich(Severity s) => $"<color={SeverityColorHex(s)}>{SeverityIcon(s)}</color>";
    }
}
