using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
namespace TKS.OutGame
{
///
/// 맹장 토벌전 화면(PD 2026-11-18 「맹장 토벌전 메뉴가 제대로 보여지지 않고 있어 … 정상적으로 게임에서 확인할 수 있도록 반영해줘」 · 아트 시안 content_screens_2/raid_banner/final/mock_raid.png) —
/// 탭(토벌 · 순위 · 훈장 상점) + 메인 맹장 카드(배너 · 태그 · 이름 · 칭호 · 군령 · 교대 · 맹장/패턴/약점 칸 · 오늘 기록 · 넘김 · 상세 정보 · 도전) + 서브 맹장 카드(연습 · 도전) + 주간 점수 띠(순위 · 내역 · 누적 단계 상자).
/// 기능 = 예전 더미 화면(ArenaScreen.BuildRaid2)과 같음: 맹장 = RaidRules.BossOf · 도전 · 연습 = ArenaScreen.RaidGo · 상점 구매 = ArenaScreen.RaidBuyPick · 순위 표 = Net.RankPanel(서버 모드) · 해금 전 = 같은 화면(도전 = 잠김 버튼) + 화면 위 잠김 덮개(LockOverlay · ArenaScreen.ShowRaidView · PD 2026-11-18).
/// 표(C45): 화면 = Resources/UI/Raid/raid_screen(키 · 값 · 배치 · 색 · 시안 예시 값) · 글자 = raid_text(UiText) · 맹장 값 = 게임 표 ContentModes/raid_*(RaidData) · 배너 = ContentModes/Art/raid_banner_<id>.
/// 층(P41): 화면 → 본문 맞춤(UiFitHeight) → Art(카드 테 · 배너 · 점수 띠 바탕 · Static) · Info(값 · 탭 · 버튼 · 누름 칸 · Event + 레이캐스터) · Clock(교대 남은 시간 · 1초마다 · Frame).
/// 게임에 데이터가 없는 값(오늘 기록 · 기기 세이브의 순위)은 설정 표 example_* (시안 예시 값) — 투기장 화면과 같은 방식.
///
public class ArenaRaid
{
public const string Table = "UI/Raid/raid_screen";
readonly ArenaScreen screen;
readonly Dictionary> kv = new Dictionary>();
readonly Dictionary bosses = new Dictionary();
readonly Dictionary btns = new Dictionary();
readonly Dictionary texts = new Dictionary();
readonly Dictionary buttons = new Dictionary();
public RectTransform View { get; private set; }
public RectTransform Design { get; private set; }
public RectTransform Art { get; private set; }
public RectTransform Info { get; private set; }
public RectTransform Clock { get; private set; }
public bool Built { get; private set; }
public bool Locked { get; private set; }
/// 지금 탭 동작(raid · shop).
public string Tab { get; private set; }
/// 메인 카드 넘김(0 = 이번 주 · k = k 주 뒤 메인 미리 보기).
public int Preview { get; private set; }
public string MainId { get; private set; }
public string SubId { get; private set; }
public string ShownMainId { get; private set; }
public int CardCount { get; private set; }
public int TileCount { get; private set; }
public int ShopRows { get; private set; }
/// 마지막으로 연 상세 정보 창의 맹장(테스트).
public string LastDetail { get; private set; }
DateTime mainEnd = DateTime.MaxValue, subEnd = DateTime.MaxValue; // 현지 시각
string nextMainName = "", nextSubName = "";
Text mainClock, subClock;
Color strokeC = Color.black;
float strokeW = 3f;
ArenaRaid(ArenaScreen s)
{
screen = s;
Tab = "raid";
}
OutGameSession S
{
get { return screen.S; }
}
// ---------- 표 ----------
/// 설정 표 · 글자 표를 읽는다(그림은 처음 열 때 Show) · 표가 없으면 null(호출 쪽 = 예전 더미 화면).
public static ArenaRaid Load(ArenaScreen s)
{
var rows = UiText.Rows(Table);
if (rows == null) return null;
var rd = new ArenaRaid(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 (!rd.kv.TryGetValue(k, out l)) rd.kv[k] = l = new List();
l.Add(v ?? "");
}
foreach (var b in rd.All("boss"))
if (Str(b, 0).Length > 0) rd.bosses[Str(b, 0)] = b;
foreach (var b in rd.All("btn"))
if (Str(b, 0).Length > 0) rd.btns[Str(b, 0)] = b;
UiText.Use(rd.S_("texts"));
if (!UiText.Has(rd.S_("title_key"))) return null;
return rd;
}
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(long v)
{
return v.ToString("N0", CultureInfo.InvariantCulture);
}
static string Pct(float mult)
{
return Mathf.RoundToInt((mult - 1f) * 100f).ToString(CultureInfo.InvariantCulture);
}
/// 제목 띠 부제(메인 점수 보너스 % 넣음).
public string Subtitle
{
get { return UiText.F(S_("subtitle_key"), new[] { Pct(RaidData.ScoreMult(RaidData.Main)) }); }
}
/// 값 글자(테스트 · 없으면 null).
public string TextOf(string name)
{
Text t;
return texts.TryGetValue(name, out t) && t != null ? t.text : null;
}
/// 버튼(테스트 · 이름 = Go_main · Go_sub · Detail_main · Practice_sub · Buy_<물품> …).
public Button ButtonOf(string name)
{
Button b;
return buttons.TryGetValue(name, out b) ? b : null;
}
/// 글자 이름 목록(테스트 · 값 자리 남음 검사).
public IEnumerable> Texts
{
get { return texts; }
}
Sprite Banner(string id)
{
return string.IsNullOrEmpty(id) ? null : Resources.Load(S_("banner") + id);
}
/// 아이콘 지정 = 「res:경로」(Resources) · 그 밖 = 테마 아이콘 id.
static Sprite IconSprite(string spec)
{
if (string.IsNullOrEmpty(spec)) return null;
return spec.StartsWith("res:", StringComparison.Ordinal) ? Resources.Load(spec.Substring(4)) : UISkin.Icon(spec);
}
static Sprite fadeH;
/// 왼쪽 불투명 → 오른쪽 투명 가로 그라데이션(시안 linear-gradient(90deg) · 색 = Image.color).
static Sprite FadeH
{
get
{
if (fadeH != null) return fadeH;
const int n = 64;
var tex = new Texture2D(n, 1, TextureFormat.RGBA32, false);
tex.wrapMode = TextureWrapMode.Clamp;
tex.hideFlags = HideFlags.DontSave;
var px = new Color[n];
for (int i = 0; i < n; i++) px[i] = new Color(1f, 1f, 1f, 1f - i / (n - 1f));
tex.SetPixels(px);
tex.Apply();
fadeH = Sprite.Create(tex, new Rect(0, 0, n, 1), new Vector2(0.5f, 0.5f), 100f);
fadeH.hideFlags = HideFlags.DontSave;
return fadeH;
}
}
// ---------- 만들기 ----------
/// slot(화면 전체 · 제목 띠 뒤)에 처음 한 번 층을 만들고 내용을 다시 채운다 · 배너가 하나도 없으면 false(호출 쪽 = 예전 더미 화면).
public bool Show(RectTransform slot)
{
if (!Built)
{
bool any = false;
foreach (var b in RaidData.Bosses())
if (Banner(b.id) != null)
{
any = true;
break;
}
if (!any)
{
Debug.LogWarning("[TKS] 맹장 배너 없음: " + S_("banner"));
return false;
}
View = slot;
var body = UiKit.Fill("Body", View, 0f, 0f, OutGameRoot.TopBarH + OutGameRoot.HeaderH, OutGameRoot.TabBarH);
var fit = UiKit.Rect("Fit", body, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), Vector2.zero, new Vector2(OutGameRoot.Reference.x, OutGameRoot.BodyH));
fit.gameObject.AddComponent().designHeight = OutGameRoot.BodyH; // 본문 높이 맞춤(다른 화면 Body 와 같음)
Design = UiKit.Rect("Design", fit, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), Vector2.zero, new Vector2(OutGameRoot.Reference.x, OutGameRoot.BodyH));
Art = UiLayer.Group("Art", Design, UiRate.Static);
Info = UiLayer.Group("Info", Design, UiRate.Event, true);
Clock = UiLayer.Group("Clock", Design, UiRate.Frame);
Clock.gameObject.AddComponent().owner = this;
Built = true;
}
Rebuild();
return true;
}
/// 쪽을 새로 열 때 = 토벌 탭 · 이번 주 메인.
public void ResetView()
{
Tab = "raid";
Preview = 0;
}
void Rebuild()
{
ContentTables.Reload();
UiKit.Clear(Art);
UiKit.Clear(Info);
UiKit.Clear(Clock);
texts.Clear();
buttons.Clear();
mainClock = subClock = null;
CardCount = TileCount = ShopRows = 0;
var st = L("stroke");
strokeC = Col(st, 0, UiKit.Stroke);
strokeW = At(st, 1, 3f);
var d = S.Save;
var now = S.Now;
Locked = !RaidRules.Unlocked(d);
if (Locked && Tab == "shop") Tab = "raid";
MainId = RaidRules.BossOf(d, RaidData.Main, now);
SubId = RaidRules.BossOf(d, RaidData.Sub, now);
Times(now);
Tabs();
if (Tab == "shop")
{
Shop(d, now);
return;
}
int n = RaidData.Bosses().Count;
Preview = n > 0 ? (Preview % n + n) % n : 0;
ShownMainId = Preview == 0 ? MainId : PreviewBoss(Preview);
var cd = L("card");
float y = At(cd, 1, 114f), step = At(cd, 3, 640f) + At(cd, 4, 14f);
var main = RaidData.Get(ShownMainId);
if (main != null) Card(RaidData.Main, main, y, Preview, n);
var sub = RaidData.Get(SubId);
if (sub != null) Card(RaidData.Sub, sub, y + step, 0, n);
Strip(d);
Tick();
}
// ---------- 일정(교대 시각 · 다음 맹장) — RaidData.Schedule 을 날짜만 바꿔 불러 찾음(새 규칙 없음) ----------
int MainDays
{
get { return Mathf.Max(1, ContentTables.Int(RaidData.Mode, "main_days")); }
}
void Times(DateTime now)
{
mainEnd = subEnd = DateTime.MaxValue;
nextMainName = nextSubName = "";
int week;
string m, s;
RaidData.Schedule(now, out week, out m, out s);
var day0 = now.ToLocalTime().Date;
for (int k = 1; k <= MainDays + 1; k++)
{
var t = day0.AddDays(k); // 현지 자정(Schedule 은 현지 날짜만 봄)
int w2;
string m2, s2;
RaidData.Schedule(t, out w2, out m2, out s2);
if (subEnd == DateTime.MaxValue && (s2 != s || w2 != week))
{
subEnd = t;
nextSubName = NameOf(s2);
}
if (w2 != week)
{
mainEnd = t;
nextMainName = NameOf(m2);
break;
}
}
}
static string NameOf(string id)
{
var b = RaidData.Get(id);
return b != null ? b.nameKo : id ?? "";
}
DateTime PreviewStart(int k)
{
return mainEnd == DateTime.MaxValue ? mainEnd : mainEnd.AddDays((k - 1) * MainDays);
}
string PreviewBoss(int k)
{
var t = PreviewStart(k);
if (t == DateTime.MaxValue) return MainId;
int w;
string m, s;
RaidData.Schedule(t, out w, out m, out s);
return m;
}
string LeftDH(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.Days > 0) return UiText.F("raid_left_dh", new[] { t.Days.ToString(CultureInfo.InvariantCulture), t.Hours.ToString(CultureInfo.InvariantCulture) });
return UiText.F("raid_left_hm", new[] { t.Hours.ToString(CultureInfo.InvariantCulture), t.Minutes.ToString(CultureInfo.InvariantCulture) });
}
static string LeftHMS(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
return ((int)t.TotalHours).ToString("00", CultureInfo.InvariantCulture) + ":" + t.Minutes.ToString("00", CultureInfo.InvariantCulture) + ":" + t.Seconds.ToString("00", CultureInfo.InvariantCulture);
}
string MainTime(DateTime nowL)
{
if (Preview > 0) return UiText.F("raid_time_future", new[] { LeftDH(PreviewStart(Preview) - nowL) });
return UiText.F("raid_time_main", new[] { LeftDH(mainEnd - nowL), nextMainName });
}
string SubTime(DateTime nowL)
{
return UiText.F("raid_time_sub", new[] { LeftHMS(subEnd - nowL), nextSubName });
}
/// 교대 남은 시간 다시 씀(RaidClock · 0.5 초마다) · 교대 시각을 넘으면 화면을 다시 그림.
internal void Tick()
{
if (!Built || Tab != "raid") return;
var nowL = S.Now.ToLocalTime();
if (nowL >= subEnd || nowL >= mainEnd)
{
if (screen.Page == 4 && screen.RaidVisible) screen.Refresh();
return;
}
if (mainClock != null)
{
var s = MainTime(nowL);
if (mainClock.text != s) mainClock.text = s;
}
if (subClock != null)
{
var s = SubTime(nowL);
if (subClock.text != s) subClock.text = s;
}
}
// ---------- 부품 ----------
static readonly Vector2 TopLeft = new Vector2(0f, 1f);
const float RoundRadius = 22f; // UiKit.Round 모서리 반지름(px)
/// 둥근 판(왼쪽 위 기준 · 모서리 반지름 rad = UiKit.Round 9 분할 배율로).
static Image RoundImg(Transform p, string name, float x, float y, float w, float h, Color c, float rad)
{
var img = UiKit.At(p, name, x, y, w, h).gameObject.AddComponent();
RoundStyle(img, c, rad);
return img;
}
static void RoundStyle(Image img, Color c, float rad)
{
img.sprite = UiKit.Round;
img.type = Image.Type.Sliced;
img.pixelsPerUnitMultiplier = RoundRadius / Mathf.Max(1f, rad);
img.color = c;
img.raycastTarget = false;
}
/// 테 두른 둥근 판(바깥 = 테 색 · 안 = 바탕) · 반환 = 바깥(크기를 바꾸면 안도 따라감).
static RectTransform Boxed(Transform p, string name, float x, float y, float w, float h, Color fill, Color border, float bw, float rad, bool raycast)
{
var outer = RoundImg(p, name, x, y, w, h, border, rad);
outer.raycastTarget = raycast;
var inner = UiKit.Fill("Fill", outer.transform, bw, bw, bw, bw).gameObject.AddComponent();
RoundStyle(inner, fill, rad - bw);
return outer.rectTransform;
}
Text Txt(Transform p, string name, string s, int size, Color c, bool title, bool stroke, TextAnchor a, float x, float y, float w, float h)
{
var t = UiKit.Label(p, s, size, c, a, TopLeft, TopLeft, new Vector2(x, -y), new Vector2(w, h));
if (title) UISkin.UseTitle(t);
if (stroke) UISkin.Stroke(t, strokeC, strokeW);
t.horizontalOverflow = HorizontalWrapMode.Overflow;
t.raycastTarget = false;
t.name = name;
texts[name] = t;
return t;
}
/// 태그(시안 .tag = 테 · 둥근 · 제목 글꼴) · 반환 = 폭.
float Tag(Transform p, string name, string s, float x, float y, Color bg, Color fg)
{
var tg = L("tag"); // 위|높이|좌우 여백|테|모서리|글자|태그 사이|테 색
return Pill(p, name, s, x, y, At(tg, 1, 42f), At(tg, 2, 14f), At(tg, 3, 4f), At(tg, 4, 12f), (int)At(tg, 5, 26f), bg, fg, Col(tg, 7, Color.black), true);
}
float Pill(Transform p, string name, string s, float x, float y, float h, float pad, float bw, float rad, int fs, Color bg, Color fg, Color border, bool title)
{
var box = Boxed(p, name, x, y, 10f, h, bg, border, bw, rad, false);
var t = Txt(box, name + "Text", s, fs, fg, title, false, TextAnchor.MiddleCenter, 0f, 0f, 10f, h);
float w = Mathf.Ceil(t.preferredWidth) + 2f * (pad + bw);
box.sizeDelta = new Vector2(w, h);
t.rectTransform.sizeDelta = new Vector2(w, h);
return w;
}
/// 버튼(표 btn 줄 = id|폭|스킨|틴트|글자색|외곽선|글자 키) · 오른끝 right 에 붙여 놓고 왼끝 x 를 돌려줌.
float Btn(Transform p, string name, string id, float right, float y, float h, Action act, bool on)
{
string[] row;
if (!btns.TryGetValue(id, out row)) row = new string[0];
var bt = L("buttons");
float w = At(row, 1, 170f);
float x = right - w;
var b = UiKit.SkinBtn(p, name, Str(row, 2), Col(row, 3, Color.white), "", 10, Color.white, x, y, w, h, act);
var bl = b.GetComponentInChildren();
if (bl != null) bl.gameObject.SetActive(false);
Txt(b.transform, name + "Text", UiText.T(Str(row, 6)), (int)At(bt, 4, 32f), Col(row, 4, Color.white), true, At(row, 5) > 0f, TextAnchor.MiddleCenter, 0f, -At(bt, 5, 4f), w, h);
b.interactable = on;
buttons[name] = b;
return x;
}
// ---------- 탭 ----------
void Tabs()
{
var tb = L("tabs"); // 왼|위|폭|높이|사이|테|모서리|글자|테 색|꺼짐|켜짐|글자색
var tabs = All("tab");
int n = tabs.Count;
if (n == 0) return;
float x0 = At(tb, 0, 24f), y = At(tb, 1, 22f), w = At(tb, 2, 1032f), h = At(tb, 3, 78f), gap = At(tb, 4, 18f);
float tw = (w - gap * (n - 1)) / n;
for (int i = 0; i < n; i++)
{
string act = Str(tabs[i], 0);
bool on = act == Tab;
var box = Boxed(Info, "Tab_" + act, x0 + i * (tw + gap), y, tw, h, Col(tb, on ? 10 : 9, UiKit.Dark), Col(tb, 8, Color.black), At(tb, 5, 5f), At(tb, 6, 18f), true);
Txt(box, "TabText_" + act, UiText.T(Str(tabs[i], 1)), (int)At(tb, 7, 34f), Col(tb, 11, Color.white), true, false, TextAnchor.MiddleCenter, 0f, 0f, tw, h);
var b = box.gameObject.AddComponent