using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame
{
///
/// 등급 투기장 화면(PD 2026-11-18 「투기장 UI 완료 (실제 게임에서 볼 수 있도록 반영해줘)」 · 아트 시안 mock_arena.png · Fable 검수 통과 · PD 4~7차 확정) —
/// 비무대 배경 + 계급 판 + 무대 위 내 수비대 5명(대기 숨) + 기록관 · 상인 NPC + 이름표(수비 편성 · 전투 기록 · 메달 상점) + 큰 게시판(상대 고르기 · 새로고침) + 목패 3(강한 · 비슷한 · 약한 상대).
/// 기능 = 예전 더미 화면(ArenaScreen.League)과 같음: 점수 · 등급 · 남은 입장 · 상대 3 · 새로고침 · 도전(LeagueGo) · 입장 구매(도전을 다 썼을 때 목패를 누르면 창) · 순위 표(서버 모드 · 순위 칩).
/// 표(Resources/UI/League · C45): 화면 설정 league_screen(키 · 값) · 자리 arena_spots(납품 그대로) · 글자 league_text(UiText) · 부품 parts/(아틀라스 UI_League · 9 분할 import.json). 그림을 바꾸면 이 폴더 파일만 바꿔 끼운다.
/// 층(P41 · 프로젝트 CLAUDE.md 「UI 캔버스·아틀라스 구조」): 화면(Event) → Content(화면 맞춤 배율 · Static) → Art(배경 · NPC · 계급 판 바탕 · Static) · Scene(유닛 대기 숨 · Frame) · Info(값 · 이름표 · 목패 · 누름 칸 · Event · 레이캐스터).
/// 게임에 데이터가 없는 값(기기 세이브의 순위 · 수비 기록 · 시즌 정산 시각 모름)은 설정 표 example_* (시안 예시 값) — 연무장 허브 상태 줄과 같은 방식.
///
public class ArenaLeague
{
public const string Table = "UI/League/league_screen";
readonly ArenaScreen screen;
readonly Dictionary> kv = new Dictionary>();
readonly Dictionary spots = new Dictionary(); // 자리 = 왼쪽 위 · 폭 · 높이(캔버스 px)
readonly Dictionary texts = new Dictionary();
string teamKey;
public RectTransform View { get; private set; }
public RectTransform Content { get; private set; }
public RectTransform Art { get; private set; }
public RectTransform Scene { get; private set; }
public RectTransform Info { get; private set; }
public ArenaHubView Fitter { get; private set; }
public bool Built { get; private set; }
/// 세운 유닛 · NPC · 목패 · 이름표 수(테스트).
public int UnitCount { get; private set; }
public int NpcCount { get; private set; }
public int PlaqueCount { get; private set; }
public int TagCount { get; private set; }
ArenaLeague(ArenaScreen s)
{
screen = s;
}
OutGameSession S
{
get { return screen.S; }
}
// ---------- 표 ----------
/// 설정 표 · 자리 표 · 글자 표를 읽는다(그림은 처음 열 때 Show) · 표가 없으면 null(호출 쪽 = 예전 더미 화면).
public static ArenaLeague Load(ArenaScreen s)
{
var rows = UiText.Rows(Table);
if (rows == null) return null;
var lg = new ArenaLeague(s);
foreach (var r in rows)
{
string k, v;
if (!r.TryGetValue("s_key", out k) || k.Length == 0) continue;
r.TryGetValue("s_value", out v);
List l;
if (!lg.kv.TryGetValue(k, out l)) lg.kv[k] = l = new List();
l.Add(v ?? "");
}
UiText.Use(lg.S_("texts"));
if (!lg.LoadSpots() || !UiText.Has(lg.S_("title_key"))) return null;
return lg;
}
public string S_(string key, string def = "")
{
List l;
return kv.TryGetValue(key, out l) && l.Count > 0 && l[0].Length > 0 ? l[0] : def;
}
string[] L(string key)
{
return S_(key).Split('|');
}
List All(string key)
{
var list = new List();
List l;
if (kv.TryGetValue(key, out l))
foreach (var v in l)
list.Add(v.Split('|'));
return list;
}
static float F(string v, float def = 0f)
{
float f;
return v != null && float.TryParse(v.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out f) ? f : def;
}
static float At(string[] a, int i, float def = 0f)
{
return a != null && i < a.Length && a[i].Trim().Length > 0 ? F(a[i], def) : def;
}
static string Str(string[] a, int i)
{
return a != null && i < a.Length ? a[i].Trim() : "";
}
static Color Col(string[] a, int i, Color def)
{
Color c;
return a != null && i < a.Length && ColorUtility.TryParseHtmlString(a[i].Trim(), out c) ? c : def;
}
static string N(int v)
{
return v.ToString("N0", CultureInfo.InvariantCulture);
}
bool LoadSpots()
{
var rows = UiText.Rows(S_("spots"));
if (rows == null) return false;
foreach (var r in rows)
{
string id;
if (!r.TryGetValue("s_id", out id) || id.Length == 0) continue;
string x, y, w, h;
r.TryGetValue("f_x", out x);
r.TryGetValue("f_y", out y);
r.TryGetValue("f_w", out w);
r.TryGetValue("f_h", out h);
float fw = F(w), fh = F(h);
spots[id] = new Rect(F(x) - fw * 0.5f, F(y) - fh * 0.5f, fw, fh);
}
return spots.Count > 0;
}
/// 자리(납품 표 · 없으면 null).
public Rect? Spot(string id)
{
Rect r;
return spots.TryGetValue(id, out r) ? r : (Rect?)null;
}
// ---------- 만들기 ----------
/// slot(화면 전체 · 제목 띠 뒤)에 처음 한 번 그림 층을 만들고 값 층을 다시 채운다 · 배경 그림이 없으면 false(호출 쪽 = 예전 더미 화면).
public bool Show(RectTransform slot)
{
if (!Built && !Build(slot)) return false;
Refresh();
return true;
}
bool Build(RectTransform slot)
{
var bgSp = Resources.Load(S_("bg"));
if (bgSp == null)
{
Debug.LogWarning("[TKS] 투기장 배경 없음: " + S_("bg"));
return false;
}
var cv = L("canvas");
var cs = new Vector2(At(cv, 0, bgSp.rect.width), At(cv, 1, bgSp.rect.height));
var bx = L("box");
var box = new Rect(At(bx, 0), At(bx, 1), At(bx, 2, cs.x), At(bx, 3, cs.y));
View = slot;
Content = UiKit.Rect("Content", View, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, cs);
UiLayer.Nest(Content.gameObject, UiRate.Static, false); // 화면 크기가 바뀔 때만 배율이 바뀜
Art = UiLayer.Group("Art", Content, UiRate.Static);
var bg = Art.gameObject.AddComponent();
bg.sprite = bgSp;
bg.raycastTarget = false;
Scene = UiLayer.Group("Scene", Content, UiRate.Frame);
Info = UiLayer.Group("Info", Content, UiRate.Event, true);
BuildNpcs();
BuildPanelBack();
// 재화 바 뒤 띠(시안 .top · 배경이 재화 바 밑까지 깔림)
UiKit.Paint(UiKit.TopBand("TopBand", View, 0f, OutGameRoot.TopBarH), Col(L("band_top"), 0, UiKit.Bg), false);
Fitter = View.gameObject.AddComponent();
Fitter.content = Content;
Fitter.canvasSize = cs;
Fitter.box = box;
Fitter.Fit(true);
Built = true;
return true;
}
static RectTransform Place(Transform p, string name, float x, float y, float w, float h, Vector2 pivot)
{
return UiKit.Rect(name, p, new Vector2(0f, 1f), pivot, new Vector2(x, -y), new Vector2(w, h));
}
static readonly Vector2 TopLeft = new Vector2(0f, 1f);
static readonly Vector2 TopCenter = new Vector2(0.5f, 1f);
static readonly Vector2 Center = new Vector2(0.5f, 0.5f);
Sprite Part(string name)
{
return name.Length > 0 ? Resources.Load(S_("parts") + "/" + name) : null;
}
/// 아이콘 지정 = 「part:이름」(이 화면 부품 폴더) · 그 밖 = 테마 아이콘 id · 빈 값 = 없음.
Sprite IconSprite(string spec)
{
if (string.IsNullOrEmpty(spec)) return null;
return spec.StartsWith("part:", StringComparison.Ordinal) ? Part(spec.Substring(5)) : UISkin.Icon(spec);
}
void AddShadow(Graphic g, string key)
{
var sh = L(key);
var s = g.gameObject.AddComponent();
s.effectDistance = new Vector2(At(sh, 0), At(sh, 1));
s.effectColor = Col(sh, 2, new Color(0f, 0f, 0f, 0.35f));
}
void AddShadow(Graphic g, string[] row, int i)
{
var s = g.gameObject.AddComponent();
s.effectDistance = new Vector2(At(row, i), At(row, i + 1));
s.effectColor = Col(row, i + 2, new Color(0f, 0f, 0f, 0.35f));
}
void BuildNpcs()
{
foreach (var n in All("npc")) // 자리|부품|키|왼끝 = 자리 x +|발 = 자리 y +
{
var sp = Spot(Str(n, 0));
var part = Part(Str(n, 1));
if (sp == null || part == null) continue;
var c = sp.Value.center;
float h = At(n, 2, 180f);
float w = h * part.rect.width / Mathf.Max(1f, part.rect.height);
var rt = Place(Art, "Npc_" + Str(n, 0), c.x + At(n, 3), c.y + At(n, 4) - h, w, h, TopLeft);
var img = rt.gameObject.AddComponent();
img.sprite = part;
img.raycastTarget = false;
AddShadow(img, "shadow");
NpcCount++;
}
}
/// 계급 판 바탕 · 진행 막대 홈(Static) — 값은 Info.
void BuildPanelBack()
{
var p = L("panel"); // x|y|폭|높이|색
var pn = Place(Art, "Panel", At(p, 0), At(p, 1), At(p, 2), At(p, 3), TopLeft);
UiKit.Skin(pn, "card", Col(p, 4, UiKit.Dark));
var b = L("panel_bar"); // 왼 x|위 y|폭|높이|안쪽|홈|채움
var track = Place(Art, "BarTrack", At(b, 0), At(b, 1), At(b, 2), At(b, 3), TopLeft);
var ti = track.gameObject.AddComponent();
ti.sprite = UiKit.Round;
ti.type = Image.Type.Sliced;
ti.color = Col(b, 5, Color.black);
ti.raycastTarget = false;
}
// ---------- 값(Event) ----------
/// 값 층을 다시 채움(입장 · 새로고침 · 서버 응답 · 편성 바뀜) · 유닛은 출전 편성이 바뀌었을 때만 다시 세움.
public void Refresh()
{
ContentTables.Reload();
var d = S.Save;
var team = d.ActivePreset != null ? d.ActivePreset.slots : new List();
var key = string.Join(",", team.ToArray());
if (key != teamKey)
{
teamKey = key;
UiKit.Clear(Scene);
UnitCount = 0;
BuildUnits(team);
}
UiKit.Clear(Info);
texts.Clear();
TagCount = 0;
PlaqueCount = 0;
BuildPress();
BuildPanelValues();
BuildTags(team);
BuildBoardHead();
BuildPlaques();
}
void BuildUnits(List team)
{
var slots = L("unit_slots");
float k = F(S_("unit_scale"), 0.2f);
var items = new List>();
for (int i = 0; i < team.Count && i < slots.Length; i++)
{
if (string.IsNullOrEmpty(team[i])) continue;
var sp = Spot(slots[i].Trim());
var h = S.Def(team[i]);
if (sp == null || h == null) continue;
items.Add(new KeyValuePair(new Vector2(sp.Value.center.x, sp.Value.yMax), h.art)); // 발 = 칸 아래끝
}
items.Sort((a, b) => a.Key.y != b.Key.y ? a.Key.y.CompareTo(b.Key.y) : a.Key.x.CompareTo(b.Key.x)); // 뒤(위) 먼저
foreach (var it in items)
{
var data = UnitArt.Load(it.Value);
Sprite[] fr;
if (data == null || data.Meta.pivot == null || data.Meta.pivot.Length < 2) continue;
if (!data.Clips.TryGetValue("front_idle", out fr) || fr.Length == 0) continue;
var size = (Vector2)fr[0].bounds.size * data.Meta.ppu * k; // 원화 프레임 px × 배율(시안 unitAt = meta frame × k)
var rt = UiKit.Rect("Unit_" + it.Value, Scene, TopLeft, new Vector2(data.Meta.pivot[0], data.Meta.pivot[1]), new Vector2(it.Key.x, -it.Key.y), size);
var img = rt.gameObject.AddComponent();
img.sprite = fr[0];
img.raycastTarget = false;
AddShadow(img, "shadow");
UiFrameAnim.Attach(img, data, "front_idle");
UnitCount++;
}
}
void BuildPress()
{
foreach (var pr in All("press")) // 자리|누르면
{
var sp = Spot(Str(pr, 0));
if (sp == null) continue;
var r = sp.Value;
var rt = Place(Info, "Press_" + Str(pr, 0), r.x, r.y, r.width, r.height, TopLeft);
var img = rt.gameObject.AddComponent();
img.color = new Color(1f, 1f, 1f, 0f);
img.canvasRenderer.cullTransparentMesh = true; // 누름만 · 그리지 않음
img.raycastTarget = true;
var b = rt.gameObject.AddComponent