using UnityEngine;

namespace ServiceSim
{
    /// <summary>
    /// 最初に作った「左右振り分け型」の店（同じ卓を格子に並べ、細い通路が枝分かれする形）。
    /// 比べる用に残してある。StoreLayout_Grid.asset がこれ。
    ///
    /// 数字はすべてこの .asset に置く。
    /// </summary>
    [CreateAssetMenu(menuName = "ServiceSim/Store Layout (Grid)", fileName = "StoreLayout_Grid")]
    public class GridStoreLayout : StoreLayout
    {
        [Header("卓の並び")]
        [Tooltip("置く卓の数。スロット数より少ない分はドリンクバーなどに使う")]
        public int tableCount = 35;

        [Tooltip("太い通路から枝分かれする細い通路の中心位置（Z, m）")]
        public float[] branchAisleCenterZ = { 4.9f, 9.3f, 13.7f };

        [Tooltip("1本の細い通路の片側に並べる卓の数。通路の南北2列ぶんが置かれる")]
        public int unitsPerBranchSide = 6;

        [Tooltip("卓の並ぶ間隔（X, m）")]
        public float unitPitchX = 1.4f;

        [Tooltip("太い通路にいちばん近い卓の中心位置（X, m）")]
        public float firstUnitCenterX = 1.35f;

        [Tooltip("ドリンクバーに使うスロット番号（0 起点）")]
        public int drinkBarSlotIndex = 35;

        [Header("通路")]
        [Tooltip("厨房から伸びる太い通路の幅（m）")]
        public float mainAisleWidth = 1.5f;

        [Tooltip("奥（東の端）に、3本の細い通路をつなぐ横通路を作るか")]
        public bool rearCrossAisle = false;

        [Header("卓と椅子（箱で作る）")]
        public Vector3 tableSize = new Vector3(1.2f, 0.72f, 0.8f);
        public Vector3 chairSize = new Vector3(0.45f, 0.45f, 0.4f);

        [Tooltip("卓の中心から椅子の中心までの横ずれ（X, m）。1卓に4脚")]
        public float chairOffsetX = 0.3f;

        [Tooltip("卓と卓のあいだの仕切り板の高さ（m）")]
        public float boothDividerHeight = 1.2f;

        [Header("厨房の受け渡し口")]
        public Vector3 passCounterSize = new Vector3(1.6f, 1.0f, 0.5f);

        [Tooltip("ロボットが料理を受け取る位置（通路上, m）")]
        public Vector3 passPoint = new Vector3(0f, 0f, 0.15f);

        [Header("レジ・トイレ・ドリンクバー")]
        public Vector3 registerCounterSize = new Vector3(2.0f, 1.0f, 0.6f);
        public float registerCenterX = 2.4f;
        public Vector3 toiletBlockSize = new Vector3(2.4f, 2.4f, 1.6f);
        public float toiletCenterX = 7.6f;

        [Tooltip("レジ・トイレの手前に取る、人が立つ余地（m）")]
        public float poiApproachGap = 0.7f;

        [Tooltip("ドリンクバーの高さ（m）")]
        public float drinkBarHeight = 1.1f;

        [Header("手前の広場")]
        [Tooltip("受け渡し口の前に取る広場の奥行き（m）。レジ・トイレ・待合に使う")]
        public float frontPocketDepth = 3.4f;

        public override string StoreKindName { get { return "格子型（比べる用）"; } }

        // ---- 計算で出る値 ----

        float UnitDepth { get { return chairSize.z * 2f + tableSize.z; } }
        int BranchCount { get { return branchAisleCenterZ != null ? branchAisleCenterZ.Length : 0; } }
        int SlotCount { get { return BranchCount * 2 * unitsPerBranchSide; } }
        float UnitCenterX(int i) { return firstUnitCenterX + i * unitPitchX; }
        float TableBlockMaxX { get { return UnitCenterX(unitsPerBranchSide - 1) + tableSize.x * 0.5f; } }
        float InteriorMinX { get { return -mainAisleWidth * 0.5f; } }
        float InteriorMaxX { get { return TableBlockMaxX + (rearCrossAisle ? MaxAisleWidth : 0f); } }
        float InteriorMinZ
        {
            get { return BranchCount == 0 ? 0f : branchAisleCenterZ[0] - MaxAisleWidth * 0.5f - UnitDepth - frontPocketDepth; }
        }
        float InteriorMaxZ
        {
            get { return BranchCount == 0 ? 0f : branchAisleCenterZ[BranchCount - 1] + MaxAisleWidth * 0.5f + UnitDepth; }
        }

        static float SideSign(int side) { return side == 0 ? -1f : 1f; }

        protected override StorePlan Compose()
        {
            StorePlan plan = new StorePlan();
            if (BranchCount == 0 || tableCount > SlotCount) return plan;

            float w = AisleWidth;
            float unitDepth = UnitDepth;
            float h = wallHeight;
            float x0 = InteriorMinX, x1 = InteriorMaxX;
            float z0 = InteriorMinZ, z1 = InteriorMaxZ;
            float eastX0 = mainAisleWidth * 0.5f;
            float tableMaxX = TableBlockMaxX;
            float off = DeliveryOffset();

            plan.AddFloor(new PlanRect(x0, z0, x1, z1));

            // 壁
            float t = wallThickness;
            plan.AddBox("Wall_South", BoxStyle.Wall, new PlanRect(x0 - t, z0 - t, x1 + t, z0), h);
            plan.AddBox("Wall_North", BoxStyle.Wall, new PlanRect(x0 - t, z1, x1 + t, z1 + t), h);
            plan.AddBox("Wall_West", BoxStyle.Wall, new PlanRect(x0 - t, z0 - t, x0, z1 + t), h);
            plan.AddBox("Wall_East", BoxStyle.Wall, new PlanRect(x1, z0 - t, x1 + t, z1 + t), h);

            // 受け渡し口のカウンター
            plan.AddPlace(PlaceKind.FoodPass, "PassCounter",
                PlanRect.FromSize(x0, z0, passCounterSize.x, passCounterSize.z),
                passCounterSize.y, passPoint, true);

            // 卓の列
            int nextTableId = 1;
            for (int k = 0; k < BranchCount; k++)
            {
                float zc = branchAisleCenterZ[k];
                for (int side = 0; side < 2; side++)
                {
                    float sign = SideSign(side);
                    float rowNear = zc + sign * (w * 0.5f);
                    float rowFar = zc + sign * (w * 0.5f + unitDepth);

                    for (int u = 0; u < unitsPerBranchSide; u++)
                    {
                        int slot = k * 2 * unitsPerBranchSide + side * unitsPerBranchSide + u;
                        float cx = UnitCenterX(u);

                        if (slot == drinkBarSlotIndex || nextTableId > tableCount)
                        {
                            plan.AddPlace(PlaceKind.DrinkBar, "DrinkBar",
                                new PlanRect(cx - tableSize.x * 0.5f, Mathf.Min(rowNear, rowFar),
                                             cx + tableSize.x * 0.5f, Mathf.Max(rowNear, rowFar)),
                                drinkBarHeight, new Vector3(cx, 0f, zc + sign * off), true);
                            continue;
                        }

                        float tz = zc + sign * (w * 0.5f + chairSize.z + tableSize.z * 0.5f);

                        PlanSeat seat = new PlanSeat();
                        seat.tableId = nextTableId++;
                        seat.kind = SeatKind.IslandTable;
                        seat.tableRect = PlanRect.FromCenter(new Vector3(cx, 0f, tz), tableSize.x, tableSize.z);
                        seat.tableHeight = tableSize.y;
                        seat.deliveryPoint = new Vector3(cx, 0f, zc + sign * off);
                        seat.aisleIndex = 1 + k;   // 0 は太い通路

                        float chairZ = tableSize.z * 0.5f + chairSize.z * 0.5f;
                        for (int sx = -1; sx <= 1; sx += 2)
                        {
                            for (int sz = -1; sz <= 1; sz += 2)
                            {
                                PlanChair chair = new PlanChair();
                                chair.rect = PlanRect.FromCenter(
                                    new Vector3(cx + sx * chairOffsetX, 0f, tz + sz * chairZ),
                                    chairSize.x, chairSize.z);
                                chair.height = chairSize.y;
                                chair.pullable = (sz < 0) == (sign > 0);
                                chair.pullDirection = new Vector3(0f, 0f, -sign);
                                seat.chairs.Add(chair);
                            }
                        }
                        plan.seats.Add(seat);
                    }

                    // 卓と卓のあいだの仕切り板
                    for (int u = 0; u < unitsPerBranchSide - 1; u++)
                    {
                        float gx0 = UnitCenterX(u) + tableSize.x * 0.5f;
                        float gx1 = UnitCenterX(u + 1) - tableSize.x * 0.5f;
                        plan.AddBox("BoothDivider", BoxStyle.Divider,
                            new PlanRect(gx0, Mathf.Min(rowNear, rowFar), gx1, Mathf.Max(rowNear, rowFar)),
                            boothDividerHeight);
                    }
                }
            }

            // 通路以外のすき間をふさぐ
            for (int k = 0; k < BranchCount - 1; k++)
            {
                float za = branchAisleCenterZ[k] + w * 0.5f + unitDepth;
                float zb = branchAisleCenterZ[k + 1] - w * 0.5f - unitDepth;
                plan.AddBox("GapBetweenBranch", BoxStyle.Wall, new PlanRect(eastX0, za, tableMaxX, zb), h);
            }
            float zn = branchAisleCenterZ[BranchCount - 1] + w * 0.5f + unitDepth;
            plan.AddBox("NorthFiller", BoxStyle.Wall, new PlanRect(eastX0, zn, tableMaxX, z1), h);
            float zm = branchAisleCenterZ[BranchCount - 1] + w * 0.5f;
            plan.AddBox("MainAisleEnd", BoxStyle.Wall, new PlanRect(x0, zm, eastX0, z1), h);

            if (rearCrossAisle)
            {
                float cx0 = tableMaxX, cx1 = x1, crossEast = tableMaxX + w;
                float zS = branchAisleCenterZ[0] - w * 0.5f;
                float zN = branchAisleCenterZ[BranchCount - 1] + w * 0.5f;
                plan.AddBox("RearSouthFiller", BoxStyle.Wall, new PlanRect(cx0, z0, cx1, zS), h);
                plan.AddBox("RearNorthFiller", BoxStyle.Wall, new PlanRect(cx0, zN, cx1, z1), h);
                plan.AddBox("RearEastFiller", BoxStyle.Wall, new PlanRect(crossEast, zS, cx1, zN), h);
            }

            // レジ・トイレ
            plan.AddPlace(PlaceKind.Register, "RegisterCounter",
                new PlanRect(registerCenterX - registerCounterSize.x * 0.5f, z0,
                             registerCenterX + registerCounterSize.x * 0.5f, z0 + registerCounterSize.z),
                registerCounterSize.y,
                new Vector3(registerCenterX, 0f, z0 + registerCounterSize.z + poiApproachGap), true);

            plan.AddPlace(PlaceKind.Toilet, "ToiletBlock",
                new PlanRect(toiletCenterX - toiletBlockSize.x * 0.5f, z0,
                             toiletCenterX + toiletBlockSize.x * 0.5f, z0 + toiletBlockSize.z),
                toiletBlockSize.y,
                new Vector3(toiletCenterX, 0f, z0 + toiletBlockSize.z + poiApproachGap), true);

            // 通路（0 番は太い通路）
            plan.AddAisle("MainAisle", new PlanRect(x0, z0, eastX0, zm), false, passPoint);
            for (int k = 0; k < BranchCount; k++)
            {
                float zc = branchAisleCenterZ[k];
                plan.AddAisle("BranchAisle" + (k + 1).ToString("00"),
                    new PlanRect(eastX0, zc - w * 0.5f, tableMaxX, zc + w * 0.5f), true,
                    new Vector3(-aisleEntranceSideOffset, 0f, zc - aisleEntranceSetback));
            }
            if (rearCrossAisle)
            {
                plan.AddAisle("RearCrossAisle",
                    new PlanRect(tableMaxX, branchAisleCenterZ[0] - w * 0.5f,
                                 tableMaxX + w, branchAisleCenterZ[BranchCount - 1] + w * 0.5f),
                    false, passPoint);
            }

            return plan;
        }
    }
}
