using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

namespace ServiceSim
{
    /// <summary>
    /// 床の塗り分け（見た目だけ）。
    ///
    /// Unity の NavMesh の表示は「通行者の中心が行ける場所」なので、見る人には
    /// 「ロボットはこの細い帯しか通れない」と読めてしまう。人に見せる絵では
    /// 「体が入れる床」を塗る。
    ///
    ///   水色　　：ロボットの体が入れる床
    ///             ロボット用 NavMesh（navAgentRadius で焼いたもの）の歩ける面を、
    ///             navAgentRadius だけ外へ広げた範囲。
    ///             0.5 m より狭いすき間はそもそも NavMesh が無いので、塗られずに残る
    ///   薄い黄色：人だけが入れる床
    ///             人用 NavMesh（人の半径で焼いたもの）を人の半径だけ外へ広げた範囲から、
    ///             水色の範囲を引いたところ
    ///
    /// 塗りは当たりを持たない板（1色につき1枚のメッシュ）なので、
    /// NavMesh には焼かれず、計算に使う NavMesh そのものは変わらない。
    ///
    /// この script は見た目だけを扱う。店の形も人もロボットも動かさない。
    /// </summary>
    public class FloorPaint : MonoBehaviour
    {
        /// <summary>塗り分けの結果（報告に出す）</summary>
        public struct Result
        {
            public float robotAreaM2;    // ロボットの体が入れる床の広さ
            public float peopleAreaM2;   // 人だけが入れる床の広さ
            public int robotQuads;       // 塗りに使った四角の数
            public int peopleQuads;
            public float cellSize;
            public bool ok;
            public string note;
        }

        /// <summary>
        /// 塗り分けを作り直す。
        /// robotTri は navAgentRadius で焼いた面、peopleTri は人の半径で焼いた面。
        /// </summary>
        public static Result Rebuild(Transform parent, StoreLayout layout, Bounds bounds,
                                     NavMeshTriangulation robotTri, NavMeshTriangulation peopleTri,
                                     float personRadius, StorePlan plan,
                                     Material robotMat, Material peopleMat)
        {
            Result res = new Result();
            res.ok = false;

            Clear(parent);
            if (layout == null) { res.note = "StoreLayout がありません"; return res; }

            float cell = Mathf.Max(0.02f, layout.floorPaintCellSize);
            res.cellSize = cell;

            float x0 = bounds.min.x, z0 = bounds.min.z;
            int nx = Mathf.CeilToInt(bounds.size.x / cell) + 1;
            int nz = Mathf.CeilToInt(bounds.size.z / cell) + 1;
            if (nx <= 0 || nz <= 0 || (long)nx * nz > 4000000)
            {
                res.note = "塗る範囲が大きすぎます（floorPaintCellSize を大きくしてください）";
                return res;
            }

            bool[] robotCore = Rasterize(robotTri, x0, z0, cell, nx, nz);
            bool[] peopleCore = Rasterize(peopleTri, x0, z0, cell, nx, nz);

            bool[] robot = Dilate(robotCore, nx, nz, layout.navAgentRadius / cell);
            bool[] people = Dilate(peopleCore, nx, nz, personRadius / cell);

            // 広げると壁や卓の中へはみ出す（壁の厚み 0.15 m より広げる分が大きいため）。
            // 置いてあるもの（壁・卓・椅子・ベンチ・カウンター・厨房・事務所）の下は塗らない
            bool[] blocked = RasterizeSolids(plan, x0, z0, cell, nx, nz);
            if (blocked != null)
            {
                for (int i = 0; i < robot.Length; i++)
                    if (blocked[i]) { robot[i] = false; people[i] = false; }
            }

            // 人だけが入れる床 ＝ 人の範囲 − ロボットの範囲
            for (int i = 0; i < people.Length; i++) if (robot[i]) people[i] = false;

            float y = Mathf.Max(0.001f, layout.floorPaintHeight);
            res.robotQuads = Build(parent, "FloorPaint_Robot", robot, nx, nz, x0, z0, cell, y, robotMat);
            res.peopleQuads = Build(parent, "FloorPaint_People", people, nx, nz, x0, z0, cell, y, peopleMat);

            res.robotAreaM2 = Count(robot) * cell * cell;
            res.peopleAreaM2 = Count(people) * cell * cell;
            res.ok = true;
            res.note = "ok";
            return res;
        }

        /// <summary>塗りを消す</summary>
        public static void Clear(Transform parent)
        {
            if (parent == null) return;
            for (int i = parent.childCount - 1; i >= 0; i--)
            {
                Transform t = parent.GetChild(i);
                if (!t.name.StartsWith("FloorPaint_")) continue;
                if (Application.isPlaying) Destroy(t.gameObject);
                else DestroyImmediate(t.gameObject);
            }
        }

        // ---------------- 格子に落とす ----------------

        /// <summary>歩ける三角形を格子に塗る（三角形ごとに、その囲み箱の中だけ見る）</summary>
        static bool[] Rasterize(NavMeshTriangulation tri, float x0, float z0, float cell, int nx, int nz)
        {
            bool[] grid = new bool[nx * nz];
            if (tri.indices == null || tri.vertices == null) return grid;

            int triCount = tri.indices.Length / 3;
            for (int t = 0; t < triCount; t++)
            {
                // Not Walkable（area 1）は NavMesh に入らないが、念のため外す
                if (tri.areas != null && t < tri.areas.Length && tri.areas[t] == 1) continue;

                Vector3 a = tri.vertices[tri.indices[t * 3]];
                Vector3 b = tri.vertices[tri.indices[t * 3 + 1]];
                Vector3 c = tri.vertices[tri.indices[t * 3 + 2]];

                int ix0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(a.x, Mathf.Min(b.x, c.x)) - x0) / cell) - 1);
                int ix1 = Mathf.Min(nx - 1, Mathf.CeilToInt((Mathf.Max(a.x, Mathf.Max(b.x, c.x)) - x0) / cell) + 1);
                int iz0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(a.z, Mathf.Min(b.z, c.z)) - z0) / cell) - 1);
                int iz1 = Mathf.Min(nz - 1, Mathf.CeilToInt((Mathf.Max(a.z, Mathf.Max(b.z, c.z)) - z0) / cell) + 1);

                for (int iz = iz0; iz <= iz1; iz++)
                {
                    float pz = z0 + (iz + 0.5f) * cell;
                    for (int ix = ix0; ix <= ix1; ix++)
                    {
                        int k = iz * nx + ix;
                        if (grid[k]) continue;
                        float px = x0 + (ix + 0.5f) * cell;
                        if (InTriangle(px, pz, a, b, c)) grid[k] = true;
                    }
                }
            }
            return grid;
        }

        /// <summary>
        /// 置いてあるもの（通れないもの）の footprint を格子に塗る。
        /// 床・通路の色板・座る場所の見た目は通れるので入れない。
        /// </summary>
        static bool[] RasterizeSolids(StorePlan plan, float x0, float z0, float cell, int nx, int nz)
        {
            if (plan == null) return null;
            bool[] g = new bool[nx * nz];

            for (int i = 0; i < plan.boxes.Count; i++)
            {
                PlanBox b = plan.boxes[i];
                if (b.style == BoxStyle.Floor || b.style == BoxStyle.AisleMark ||
                    b.style == BoxStyle.BenchSeat) continue;
                Fill(g, b.rect, x0, z0, cell, nx, nz);
            }
            for (int i = 0; i < plan.places.Count; i++)
            {
                PlanPlace p = plan.places[i];
                if (!p.solid || p.rect.IsEmpty) continue;
                Fill(g, p.rect, x0, z0, cell, nx, nz);
            }
            return g;
        }

        static void Fill(bool[] g, PlanRect r, float x0, float z0, float cell, int nx, int nz)
        {
            int ix0 = Mathf.Max(0, Mathf.FloorToInt((r.xMin - x0) / cell));
            int ix1 = Mathf.Min(nx - 1, Mathf.CeilToInt((r.xMax - x0) / cell) - 1);
            int iz0 = Mathf.Max(0, Mathf.FloorToInt((r.zMin - z0) / cell));
            int iz1 = Mathf.Min(nz - 1, Mathf.CeilToInt((r.zMax - z0) / cell) - 1);
            for (int iz = iz0; iz <= iz1; iz++)
                for (int ix = ix0; ix <= ix1; ix++) g[iz * nx + ix] = true;
        }

        static bool InTriangle(float px, float pz, Vector3 a, Vector3 b, Vector3 c)
        {
            float d1 = Side(px, pz, a, b);
            float d2 = Side(px, pz, b, c);
            float d3 = Side(px, pz, c, a);
            bool neg = d1 < 0f || d2 < 0f || d3 < 0f;
            bool pos = d1 > 0f || d2 > 0f || d3 > 0f;
            return !(neg && pos);
        }

        static float Side(float px, float pz, Vector3 p, Vector3 q)
        {
            return (px - q.x) * (p.z - q.z) - (p.x - q.x) * (pz - q.z);
        }

        /// <summary>丸く広げる（半径はマスの数）</summary>
        static bool[] Dilate(bool[] grid, int nx, int nz, float radiusCells)
        {
            int r = Mathf.FloorToInt(radiusCells + 0.5f);
            if (r <= 0) return (bool[])grid.Clone();

            // 広げる形（円）のマスの並びを先に作る
            List<int> dx = new List<int>();
            List<int> dz = new List<int>();
            float r2 = radiusCells * radiusCells;
            for (int j = -r; j <= r; j++)
                for (int i = -r; i <= r; i++)
                    if (i * i + j * j <= r2 + 0.01f) { dx.Add(i); dz.Add(j); }

            bool[] outGrid = new bool[grid.Length];
            int n = dx.Count;
            for (int iz = 0; iz < nz; iz++)
            {
                int row = iz * nx;
                for (int ix = 0; ix < nx; ix++)
                {
                    if (!grid[row + ix]) continue;
                    for (int k = 0; k < n; k++)
                    {
                        int jx = ix + dx[k];
                        if (jx < 0 || jx >= nx) continue;
                        int jz = iz + dz[k];
                        if (jz < 0 || jz >= nz) continue;
                        outGrid[jz * nx + jx] = true;
                    }
                }
            }
            return outGrid;
        }

        static int Count(bool[] g)
        {
            int n = 0;
            for (int i = 0; i < g.Length; i++) if (g[i]) n++;
            return n;
        }

        // ---------------- 四角にまとめてメッシュにする ----------------

        /// <summary>
        /// 塗るマスを大きな四角にまとめて、1枚のメッシュにする。
        /// 当たりは付けない（NavMesh に焼かれないようにする）。四角の数を返す。
        /// </summary>
        static int Build(Transform parent, string name, bool[] grid, int nx, int nz,
                         float x0, float z0, float cell, float y, Material mat)
        {
            bool[] used = new bool[grid.Length];
            List<Vector3> verts = new List<Vector3>();
            List<int> tris = new List<int>();
            int quads = 0;

            for (int iz = 0; iz < nz; iz++)
            {
                for (int ix = 0; ix < nx; ix++)
                {
                    int k = iz * nx + ix;
                    if (!grid[k] || used[k]) continue;

                    // 右へ伸ばす
                    int w = 1;
                    while (ix + w < nx && grid[iz * nx + ix + w] && !used[iz * nx + ix + w]) w++;

                    // 上へ伸ばす（同じ幅ぶん続くあいだ）
                    int h = 1;
                    while (iz + h < nz)
                    {
                        bool full = true;
                        for (int i = 0; i < w; i++)
                        {
                            int kk = (iz + h) * nx + ix + i;
                            if (!grid[kk] || used[kk]) { full = false; break; }
                        }
                        if (!full) break;
                        h++;
                    }

                    for (int j = 0; j < h; j++)
                        for (int i = 0; i < w; i++) used[(iz + j) * nx + ix + i] = true;

                    float ax = x0 + ix * cell, az = z0 + iz * cell;
                    float bx = ax + w * cell, bz = az + h * cell;
                    int v = verts.Count;
                    verts.Add(new Vector3(ax, 0f, az));
                    verts.Add(new Vector3(bx, 0f, az));
                    verts.Add(new Vector3(bx, 0f, bz));
                    verts.Add(new Vector3(ax, 0f, bz));
                    tris.Add(v); tris.Add(v + 2); tris.Add(v + 1);
                    tris.Add(v); tris.Add(v + 3); tris.Add(v + 2);
                    quads++;
                }
            }

            if (quads == 0) return 0;

            GameObject go = new GameObject(name);
            go.transform.SetParent(parent, false);
            go.transform.position = new Vector3(0f, y, 0f);

            Mesh mesh = new Mesh();
            mesh.name = name;
            mesh.indexFormat = verts.Count > 65000
                ? UnityEngine.Rendering.IndexFormat.UInt32
                : UnityEngine.Rendering.IndexFormat.UInt16;
            mesh.SetVertices(verts);
            mesh.SetTriangles(tris, 0);
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();

            go.AddComponent<MeshFilter>().sharedMesh = mesh;
            MeshRenderer mr = go.AddComponent<MeshRenderer>();
            if (mat != null) mr.sharedMaterial = mat;
            mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            mr.receiveShadows = false;
            return quads;
        }
    }
}
