using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
///
/// The upgrade matrix as node graphs: the GreenHaul console shows CONTAINERS · CUTTING · SUIT · LOGISTICS · ECONOMY · AUTOMATION,
/// each branch growing out of the free Earth Uplink, the garage shows the FLEET. Click a node to inspect it, buy it from
/// the shared crew wallet.
///
public class ShopScreen
{
public VisualElement Card { get; }
readonly Label _money, _installs;
readonly Action _close;
public static readonly PerkTree[] TerminalTrees = { PerkTree.Containers, PerkTree.Cutting, PerkTree.Suit, PerkTree.Logistics, PerkTree.Economy, PerkTree.Automation };
readonly PerkTree[] _trees;
bool Hub => _trees == TerminalTrees;
int TreeCount => _trees.Length;
readonly Button[] _tabs;
readonly Label[] _tabBadges;
readonly VisualElement _graph, _canvas, _lines, _detail;
readonly Dictionary _nodes = new Dictionary();
VisualElement _hubNode;
PerkTree _tree = PerkTree.Containers;
PerkId _selected = PerkId.BinScissors;
const float ColW = 236f, RowH = 196f, Node = 112f, PadX = 30f, PadY = 22f;
// the canvas fits the widest / deepest tree so every tab has the same scale
static int MaxCol { get { int m = 0; foreach (var d in GameDefs.Perks) m = Mathf.Max(m, d.col); return m; } }
static int MaxRow { get { int m = 0; foreach (var d in GameDefs.Perks) m = Mathf.Max(m, d.row); return m; } }
static readonly float CanvasW = PadX * 2f + ColW * (MaxCol + 1), CanvasH = PadY + RowH * (MaxRow + 1) + Node + 64f;
static readonly string[] TreeNames = { Loc.N("CONTAINERS"), Loc.N("CUTTING"), Loc.N("SUIT"), Loc.N("LOGISTICS"), Loc.N("ECONOMY"), Loc.N("AUTOMATION") };
static readonly Color[] TreeColors =
{
new Color(0.9f, 0.72f, 0.24f), new Color(0.45f, 0.8f, 0.2f), new Color(0.85f, 0.75f, 0.4f), new Color(1f, 0.8f, 0.25f),
new Color(0.25f, 0.7f, 0.45f), new Color(0.3f, 0.66f, 0.86f),
};
TeamState Ts => TeamState.Instance;
public ShopScreen(VisualElement layer, Action close, PerkTree[] trees = null, string title = null)
{
_close = close;
_trees = trees ?? TerminalTrees;
_tabs = new Button[_trees.Length];
_tabBadges = new Label[_trees.Length];
_tree = _trees[0];
Card = UIK.El("card shop", layer);
Card.pickingMode = PickingMode.Position;
var header = UIK.El("card-header", Card);
var left = UIK.El(null, header);
left.style.flexDirection = FlexDirection.Row;
left.style.alignItems = Align.Center;
UIK.Text(title ?? Loc.T("UPGRADE MATRIX"), "t-h1 t-dark", left).style.marginRight = 20;
if (_trees == TerminalTrees) _installs = UIK.Text("", "t-h2 t-muted", left);
var right = UIK.El(null, header);
right.style.flexDirection = FlexDirection.Row;
right.style.alignItems = Align.Center;
var wallet = UIK.El("pill", right);
UIK.Img(AssetBank.I.Tex("icon_coin"), "check-icon", wallet);
_money = UIK.Text("$0", "t-h2 t-dark", wallet);
wallet.style.marginRight = 16;
UIK.Btn("X", close, "btn btn-red btn-small", right);
// tree tabs get their own row so they never collide with the wallet
var tabs = UIK.El("shop-tabs", Card);
for (int i = 0; i < TreeCount; i++)
{
int t = i;
// label as a child: a Button that has children is no longer measured by its own text
_tabs[i] = UIK.Btn("", () => SetTree(_trees[t], true), "tab", tabs);
UIK.Text(Loc.T(TreeNames[(int)_trees[i]]), "tab-label", _tabs[i]).pickingMode = PickingMode.Ignore;
_tabBadges[i] = UIK.Text("", "tab-badge", _tabs[i]);
}
var body = UIK.El("tree-body", Card);
_graph = UIK.El("tree-graph", body);
// nodes live on a fixed-size canvas that is scaled down to fit whatever room the graph gets
_canvas = UIK.El("tree-canvas", _graph);
_canvas.pickingMode = PickingMode.Ignore;
_canvas.style.width = CanvasW; _canvas.style.height = CanvasH;
_graph.RegisterCallback(_ => FitCanvas());
_lines = UIK.El("tree-lines", _canvas);
_lines.pickingMode = PickingMode.Ignore;
_lines.generateVisualContent += DrawLines;
_detail = UIK.El("tree-detail", body);
TeamState.Changed += Refresh;
Card.RegisterCallback(_ => TeamState.Changed -= Refresh);
// the wallet moves all the time: it recolours the prices, the pill and the tab counts, it doesn't rebuild the tree
UIK.FollowWallet(Card);
Card.schedule.Execute(Wallet).Every(250);
// open on the first tree that has something affordable
// a single tree needs no tab row
if (TreeCount == 1) tabs.style.display = DisplayStyle.None;
for (int i = 0; i < TreeCount; i++) if (Affordable(_trees[i]) > 0) { _tree = _trees[i]; break; }
SetTree(_tree, true);
}
int Affordable(PerkTree tree)
{
var ts = Ts;
if (!ts) return 0;
int n = 0;
foreach (var d in GameDefs.Perks)
if (d.tree == tree && ts.Level(d.id) < d.maxLevel && ts.PerkAvailable(d) && ts.Money.Value >= d.PriceFor(ts.Level(d.id))) n++;
return n;
}
public void SetTree(PerkTree tree, bool animate)
{
_tree = tree;
for (int i = 0; i < TreeCount; i++) _tabs[i].EnableInClassList("tab-on", _trees[i] == tree);
// select the cheapest thing you can buy right now, else the root
PerkDef pick = null;
var ts = Ts;
foreach (var d in GameDefs.Perks)
{
if (d.tree != tree) continue;
if (pick == null) pick = d;
if (ts && ts.Level(d.id) < d.maxLevel && ts.PerkAvailable(d) && (pick == null || !ts.PerkAvailable(pick) || ts.Level(pick.id) >= pick.maxLevel || d.PriceFor(ts.Level(d.id)) < pick.PriceFor(ts.Level(pick.id))))
pick = d;
}
if (pick != null) _selected = pick.id;
Rebuild(animate);
}
void Refresh() => Rebuild(false);
void FitCanvas()
{
var r = _graph.contentRect;
if (r.width < 1f || r.height < 1f) return;
float k = Mathf.Min(1f, Mathf.Min(r.width / CanvasW, r.height / CanvasH));
_canvas.style.transformOrigin = new TransformOrigin(0, 0);
_canvas.style.scale = new Scale(new Vector3(k, k, 1f));
_canvas.style.left = (r.width - CanvasW * k) * 0.5f;
_canvas.style.top = (r.height - CanvasH * k) * 0.5f;
}
Vector2 NodePos(PerkDef d) => new Vector2(PadX + d.col * ColW + (ColW - Node) * 0.5f, PadY + (d.row + (Hub ? 1 : 0)) * RowH);
Vector2 NodeCenter(PerkDef d) => NodePos(d) + new Vector2(Node, Node) * 0.5f;
static Vector2 HubPos => new Vector2(CanvasW * 0.5f - Node * 0.5f, PadY);
void Wallet()
{
var ts = Ts;
if (!ts) return;
_money.text = UIK.Money(ts.Money.Value);
if (_installs != null) _installs.text = $"{ts.Installs} / {TeamState.TotalInstalls}";
for (int i = 0; i < TreeCount; i++)
{
int n = Affordable(_trees[i]);
_tabBadges[i].text = n > 0 ? n.ToString() : "";
_tabBadges[i].style.display = n > 0 ? DisplayStyle.Flex : DisplayStyle.None;
}
}
void Rebuild(bool animate)
{
var ts = Ts;
if (!ts) return;
Wallet();
// nodes
foreach (var n in _nodes.Values) n.RemoveFromHierarchy();
_nodes.Clear();
_hubNode?.RemoveFromHierarchy();
if (Hub)
{
_hubNode = UIK.El("node node-maxed", _canvas);
_hubNode.style.left = HubPos.x; _hubNode.style.top = HubPos.y;
UIK.Img(AssetBank.I.Tex("icon_star"), "node-icon", _hubNode);
UIK.Text(Loc.T("Earth Uplink"), "node-name", _hubNode, false);
}
int k = 0;
foreach (var d in GameDefs.Perks)
{
if (d.tree != _tree) continue;
int lvl = ts.Level(d.id);
bool maxed = lvl >= d.maxLevel;
bool avail = ts.PerkAvailable(d);
bool afford = avail && !maxed && ts.Money.Value >= d.PriceFor(lvl);
var node = UIK.El("node", _canvas);
node.pickingMode = PickingMode.Position;
var pos = NodePos(d);
node.style.left = pos.x; node.style.top = pos.y;
if (maxed || lvl > 0 || !avail) node.AddToClassList(maxed ? "node-maxed" : lvl > 0 ? "node-owned" : "node-locked");
else UIK.Costs(node, d.PriceFor(lvl), "node-afford", "node-available");
if (d.id == _selected) node.AddToClassList("node-selected");
var icon = UIK.Img(AssetBank.I.Tex(d.icon), "node-icon", node);
icon.pickingMode = PickingMode.Ignore;
if (!avail) UIK.Text("?", "node-lock t-outline", node).pickingMode = PickingMode.Ignore;
if (d.maxLevel > 1) UIK.Text($"{lvl}/{d.maxLevel}", "node-level t-outline", node).pickingMode = PickingMode.Ignore;
else if (lvl > 0) UIK.Text(Loc.T("OWNED"), "node-level t-outline", node).pickingMode = PickingMode.Ignore;
var name = UIK.Text(d.name, "node-name", node, false);
name.pickingMode = PickingMode.Ignore;
var id = d.id;
node.RegisterCallback(_ => { _selected = id; Sfx.Play("ui_click", 0.6f, 1.1f); Rebuild(false); });
node.RegisterCallback(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
if (afford) Pulse(node);
_nodes[d.id] = node;
if (animate) UIK.PopIn(node, 0.03f * k, 0.35f);
k++;
}
_lines.MarkDirtyRepaint();
BuildDetail(animate);
}
static void Pulse(VisualElement e)
{
Tween.Run(e, 1.2f, t => { if (e.panel != null) e.style.scale = new Scale(Vector3.one * (1f + Mathf.Sin(t * Mathf.PI * 2f) * 0.035f)); }, Ease.Linear, 0f, () => { if (e.panel != null) Pulse(e); });
}
void DrawLines(MeshGenerationContext ctx)
{
var ts = Ts;
if (!ts) return;
var p = ctx.painter2D;
p.lineCap = LineCap.Round;
p.lineJoin = LineJoin.Round;
foreach (var d in GameDefs.Perks)
{
if (d.tree != _tree) continue;
if (Hub && d.requires.Length == 0) Link(p, HubPos + new Vector2(Node, Node) * 0.5f, NodeCenter(d), ts.Has(d.id));
foreach (var r in d.requires)
{
var rd = GameDefs.Perk(r);
// a root that needs a perk from another tree has no line to draw (the detail panel names it)
if (rd.tree != d.tree) continue;
Link(p, NodeCenter(rd), NodeCenter(d), ts.Has(d.id), ts.Has(r));
}
}
}
void Link(Painter2D p, Vector2 a, Vector2 b, bool mine, bool have = true)
{
// outline then fill, so lines read like the chunky UI borders
p.strokeColor = new Color(0.165f, 0.13f, 0.08f, 1f);
p.lineWidth = 16f;
Path(p, a, b);
p.strokeColor = mine ? TreeColors[(int)_tree] : have ? new Color(1f, 1f, 1f) : new Color(0.78f, 0.8f, 0.66f);
p.lineWidth = 9f;
Path(p, a, b);
}
static void Path(Painter2D p, Vector2 a, Vector2 b)
{
p.BeginPath();
p.MoveTo(a);
if (Mathf.Abs(a.x - b.x) < 1f) p.LineTo(b);
else
{
float midY = (a.y + b.y) * 0.5f;
p.BezierCurveTo(new Vector2(a.x, midY), new Vector2(b.x, midY), b);
}
p.Stroke();
}
void BuildDetail(bool animate)
{
var ts = Ts;
_detail.Clear();
var d = GameDefs.Perk(_selected);
if (d.tree != _tree) return;
int lvl = ts.Level(d.id);
bool maxed = lvl >= d.maxLevel;
bool avail = ts.PerkAvailable(d);
long price = d.PriceFor(lvl);
var top = UIK.El("detail-top", _detail);
top.style.backgroundColor = Color.Lerp(TreeColors[(int)_tree], Color.white, 0.55f);
UIK.Img(AssetBank.I.Tex(d.icon), "detail-icon", top);
UIK.Text(d.name, "t-h1 t-dark t-center detail-title", _detail);
if (d.maxLevel > 1)
{
var pips = UIK.El("item-level detail-pips", _detail);
for (int i = 0; i < d.maxLevel; i++) UIK.El(i < lvl ? "pip pip-on" : "pip", pips);
}
var desc = UIK.Text(d.desc, "item-desc t-center", _detail, false);
desc.style.whiteSpace = WhiteSpace.Normal;
if (d.effect != null)
{
var fx = UIK.El("detail-effect", _detail);
if (lvl > 0) UIK.Text(Loc.F("NOW {0}", d.EffectFor(lvl)), "t-small t-muted", fx, false);
if (!maxed) UIK.Text(Loc.F("NEXT {0}", d.EffectFor(lvl + 1)), "t-body t-dark", fx, false);
}
var spacer = UIK.El(null, _detail);
spacer.style.flexGrow = 1;
if (maxed) UIK.Text(d.maxLevel > 1 ? Loc.T("MAXED OUT!") : Loc.T("OWNED"), "price t-green t-outline t-center", _detail);
else if (!avail)
{
var names = new List();
foreach (var r in d.requires) if (ts.Level(r) < d.requireLevel) names.Add(d.requireLevel > 1 ? $"{GameDefs.Perk(r).name} {GameDefs.ToRoman(d.requireLevel)}" : GameDefs.Perk(r).name);
var req = UIK.Text(Loc.F("Requires {0}", string.Join(" + ", names)), "t-body t-muted t-center", _detail, false);
req.style.whiteSpace = WhiteSpace.Normal;
}
else
{
var b = UIK.Btn(lvl > 0 ? Loc.F("UPGRADE {0}", UIK.Money(price)) : Loc.F("UNLOCK {0}", UIK.Money(price)), () => Buy(d, UIK.CanPay(price)), "btn", _detail);
UIK.Costs(b, price);
b.style.alignSelf = Align.Stretch;
}
if (animate) UIK.SlideIn(_detail, new Vector2(40, 0), 0.05f, 0.3f);
}
void Buy(PerkDef d, bool afford)
{
_nodes.TryGetValue(d.id, out var node);
if (!afford)
{
Sfx.Play("error", 0.7f);
if (node != null) UIK.Punch(node, 0.08f, 0.3f);
Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn);
return;
}
Ts.BuyPerkRpc((int)d.id);
Sfx.Play("cash_register", 0.9f);
if (node != null) UIK.Punch(node, 0.3f, 0.45f);
var cam = CameraFx.Cam;
if (cam) Fx.Confetti(cam.transform.position + cam.transform.forward * 1.6f - cam.transform.up * 0.5f, 60, 4f);
}
}
}