using System.Collections.Generic;
using UnityEngine;

namespace ServiceSim
{
    /// <summary>
    /// 場所の名前を床の上に出す（見た目だけ）。
    ///
    /// 頭の上の字幕（ServiceSimLabels）は Scene ビューにだけ描くのでカメラに写らない。
    /// 場所の名前は真上の画面にも写したいので、文字の板（TextMesh）で置く。
    /// 当たりは付けないので NavMesh には焼かれない。
    ///
    ///   ・横書き。真上のカメラから見て、上が北の向きで読める
    ///   ・1つの場所に1つだけ。短い名前
    ///   ・文字の大きさはそろえる
    ///   ・場所の中に収まらなければ、場所の外に置いて細い線でつなぐ
    ///   ・名前どうしが重ならないよう、空いているほうへずらす
    ///
    /// 計測の回では出さない（見た目だけのものなので、速さを落とさないため）。
    /// Build Store と「見る用」の回でだけ作る。
    ///
    /// この script は見た目だけを扱う。店の形も人もロボットも動かさない。
    /// </summary>
    public static class PlaceNameLabels
    {
        const string RootName = "PlaceNames";

        /// <summary>1つぶんの名前（出す場所と、つなぎ先）</summary>
        struct Item
        {
            public string text;
            public PlanRect area;      // その場所の広がり（空なら点だけ）
            public Vector3 anchor;      // つなぎ先（場所の中心）
        }

        /// <summary>置いた結果（報告に出す）</summary>
        public struct Result
        {
            public int count;        // 出した名前の数
            public int moved;        // 重なりを避けてずらした数
            public int overlaps;     // それでも重なっている数（0 になること）
            public int leaders;      // 場所の外に出して線でつないだ数
        }

        /// <summary>
        /// 真上から見て読める名前を作り直す。
        /// 短い名前の対応表はここに持つ（場所の種類 → 出す名前）。
        /// </summary>
        public static Result Rebuild(StoreBuilder builder)
        {
            Result res = new Result();
            if (builder == null) return res;

            Transform root = Root(builder.transform);
            ClearChildren(root);

            StoreLayout layout = builder.layout;
            StorePlan plan = builder.Plan;
            if (layout == null || plan == null || !layout.showPlaceNames) return res;

            List<Item> items = Collect(builder, plan);

            float size = Mathf.Max(0.04f, layout.placeNameSize);
            List<Rect> taken = new List<Rect>();

            for (int i = 0; i < items.Count; i++)
            {
                Item it = items[i];

                // 文字の囲みの大きさ（日本語は1文字ぶんの幅で見積もる）
                float w = it.text.Length * size * 1.05f;
                float h = size * 1.3f;

                // 場所の中に収まるか。収まらなければ外（北か南の空いているほう）へ
                bool outside = it.area.IsEmpty || it.area.SizeX < w || it.area.SizeZ < h;
                Vector2 at = new Vector2(it.anchor.x, it.anchor.z);
                if (outside)
                {
                    at.y = it.area.IsEmpty ? it.anchor.z + h : it.area.zMax + h * 0.9f;
                    res.leaders++;
                }

                // 重なりを避けて、north→south→east→west の順に少しずつずらす
                Rect r = new Rect(at.x - w * 0.5f, at.y - h * 0.5f, w, h);
                Vector2 moved;
                bool ok = Avoid(r, taken, h, w, out moved);
                if (moved != at) res.moved++;
                if (!ok) res.overlaps++;
                at = moved;

                r = new Rect(at.x - w * 0.5f, at.y - h * 0.5f, w, h);
                taken.Add(r);

                Label(root, it.text, at, layout, size);
                if (outside || Vector2.Distance(at, new Vector2(it.anchor.x, it.anchor.z)) > h)
                    Leader(root, at, new Vector2(it.anchor.x, it.anchor.z), layout);
                res.count++;
            }
            return res;
        }

        public static void Clear(StoreBuilder builder)
        {
            if (builder == null) return;
            ClearChildren(Root(builder.transform));
        }

        // ---------------- 出す名前を集める（1つの場所に1つだけ）----------------

        static List<Item> Collect(StoreBuilder builder, StorePlan plan)
        {
            // 出す場所と、短い名前。ここに無い種類（事務所・ドリンクバーの前／列・レジの列）は出さない
            PlaceKind[] kinds =
            {
                PlaceKind.Entrance, PlaceKind.Vestibule, PlaceKind.Waiting,
                PlaceKind.Register, PlaceKind.RegisterBack, PlaceKind.Kitchen,
                PlaceKind.FoodPass, PlaceKind.DishReturn, PlaceKind.Pantry,
                PlaceKind.DrinkBar, PlaceKind.Toilet
            };
            string[] names =
            {
                "入口", "風除室", "待合",
                "レジ", "レジの内側", "厨房",
                "受け渡し口", "返却口", "パントリー",
                "ドリンクバー", "トイレ"
            };

            List<Item> list = new List<Item>();
            for (int k = 0; k < kinds.Length; k++)
            {
                // 同じ種類が2つ以上あっても、広がりをまとめて1つだけ出す
                PlanRect area = new PlanRect(0f, 0f, 0f, 0f);
                Vector3 point = Vector3.zero;
                bool found = false, hasArea = false;

                for (int i = 0; i < plan.places.Count; i++)
                {
                    PlanPlace p = plan.places[i];
                    if (p.kind != kinds[k]) continue;
                    if (!found) { point = p.point; found = true; }
                    if (p.rect.IsEmpty) continue;
                    area = hasArea ? Union(area, p.rect) : p.rect;
                    hasArea = true;
                }
                if (!found) continue;

                Item it = new Item();
                it.text = names[k];
                it.area = hasArea ? area : new PlanRect(0f, 0f, 0f, 0f);
                it.anchor = hasArea ? area.Center : point;
                list.Add(it);
            }

            // 待機の点は「◯◯待機×2」とまとめて1つだけ
            AddStandby(list, builder.RobotStandbyPoints, "ロボット待機");
            AddStandby(list, builder.StaffStandbyPoints, "スタッフ待機");
            return list;
        }

        static void AddStandby(List<Item> list, IList<Vector3> points, string name)
        {
            if (points == null || points.Count == 0) return;

            Vector3 sum = Vector3.zero;
            for (int i = 0; i < points.Count; i++) sum += points[i];

            Item it = new Item();
            it.text = points.Count > 1 ? name + "×" + points.Count : name;
            it.area = new PlanRect(0f, 0f, 0f, 0f);
            it.anchor = sum / points.Count;
            list.Add(it);
        }

        static PlanRect Union(PlanRect a, PlanRect b)
        {
            return new PlanRect(Mathf.Min(a.xMin, b.xMin), Mathf.Min(a.zMin, b.zMin),
                                Mathf.Max(a.xMax, b.xMax), Mathf.Max(a.zMax, b.zMax));
        }

        // ---------------- 重なりを避ける ----------------

        /// <summary>
        /// すでに置いた囲みと重なるなら、北・南・東・西へ少しずつずらして空きを探す。
        /// 見つかれば true。見つからなければ元の位置のまま false。
        /// </summary>
        static bool Avoid(Rect r, List<Rect> taken, float h, float w, out Vector2 at)
        {
            Vector2 start = r.center;
            at = start;
            if (!Hits(r, taken)) return true;

            Vector2[] dirs =
            {
                new Vector2(0f, 1f), new Vector2(0f, -1f),
                new Vector2(1f, 0f), new Vector2(-1f, 0f)
            };
            for (int step = 1; step <= 8; step++)
            {
                for (int d = 0; d < dirs.Length; d++)
                {
                    Vector2 c = start + new Vector2(dirs[d].x * w * 0.6f * step,
                                                    dirs[d].y * h * 1.15f * step);
                    Rect t = new Rect(c.x - w * 0.5f, c.y - h * 0.5f, w, h);
                    if (Hits(t, taken)) continue;
                    at = c;
                    return true;
                }
            }
            return false;
        }

        static bool Hits(Rect r, List<Rect> taken)
        {
            for (int i = 0; i < taken.Count; i++) if (r.Overlaps(taken[i])) return true;
            return false;
        }

        // ---------------- 置く ----------------

        static Transform Root(Transform parent)
        {
            Transform t = parent.Find(RootName);
            if (t == null)
            {
                GameObject go = new GameObject(RootName);
                go.transform.SetParent(parent, false);
                t = go.transform;
            }
            return t;
        }

        static void ClearChildren(Transform root)
        {
            if (root == null) return;
            for (int i = root.childCount - 1; i >= 0; i--)
            {
                GameObject go = root.GetChild(i).gameObject;
                if (Application.isPlaying) Object.Destroy(go);
                else Object.DestroyImmediate(go);
            }
        }

        static void Label(Transform root, string text, Vector2 at, StoreLayout layout, float size)
        {
            GameObject go = new GameObject("PlaceName_" + text);
            go.transform.SetParent(root, false);
            go.transform.position = new Vector3(at.x, layout.placeNameHeight, at.y);

            // 真上から見て横書き・上が北。
            // 文字の右（+X）→ 東、文字の上（+Y）→ 北（+Z）になる向き
            go.transform.rotation = Quaternion.Euler(90f, 0f, 0f);

            TextMesh tm = go.AddComponent<TextMesh>();
            tm.text = text;
            tm.anchor = TextAnchor.MiddleCenter;
            tm.alignment = TextAlignment.Center;
            tm.characterSize = size;      // 大きさは全部そろえる
            tm.fontSize = 64;
            tm.lineSpacing = 1f;
            tm.richText = false;
            tm.color = new Color(0.08f, 0.09f, 0.12f);

            Font font = JapaneseFont();
            if (font != null) tm.font = font;

            MeshRenderer mr = go.GetComponent<MeshRenderer>();
            if (mr == null) return;
            Material mat = font != null ? font.material : null;
            if (mat == null)
            {
                Shader sh = Shader.Find("GUI/Text Shader");
                if (sh != null) mat = new Material(sh);
            }
            if (mat != null) mr.sharedMaterial = mat;
            mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            mr.receiveShadows = false;
        }

        /// <summary>名前と場所をつなぐ細い線（当たりなし）</summary>
        static void Leader(Transform root, Vector2 from, Vector2 to, StoreLayout layout)
        {
            Vector2 d = to - from;
            float len = d.magnitude;
            if (len < 0.05f) return;

            GameObject go = GameObject.CreatePrimitive(PrimitiveType.Quad);
            go.name = "PlaceName_Leader";
            Object.DestroyImmediate(go.GetComponent<Collider>());
            go.transform.SetParent(root, false);
            go.transform.position = new Vector3((from.x + to.x) * 0.5f,
                                                layout.placeNameHeight - 0.005f,
                                                (from.y + to.y) * 0.5f);
            float deg = -Mathf.Atan2(d.y, d.x) * Mathf.Rad2Deg;
            go.transform.rotation = Quaternion.Euler(90f, deg, 0f);
            go.transform.localScale = new Vector3(len, 0.02f, 1f);

            MeshRenderer mr = go.GetComponent<MeshRenderer>();
            Shader sh = Shader.Find("GUI/Text Shader");
            if (sh != null)
            {
                Material m = new Material(sh);
                m.color = new Color(0.25f, 0.27f, 0.32f);
                mr.sharedMaterial = m;
            }
            mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            mr.receiveShadows = false;
        }

        static Font _font;
        static bool _tried;

        /// <summary>日本語が出るフォント（組み込みの Arial には日本語が無い）</summary>
        static Font JapaneseFont()
        {
            if (_tried) return _font;
            _tried = true;
            string[] names =
            {
                "Hiragino Sans", "HiraginoSans-W3", "Hiragino Kaku Gothic ProN",
                "Yu Gothic", "YuGothic", "Noto Sans CJK JP", "Arial Unicode MS"
            };
            try { _font = Font.CreateDynamicFontFromOSFont(names, 64); }
            catch { _font = null; }
            return _font;
        }
    }
}
