using System;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
public partial class TeamState
{
/// Sector, what it paid.
public static event Action SectorClosed;
/// Who, which landmark, what it paid.
public static event Action MarkFound;
float _mownAt;
void WatchSectors()
{
MowMap.SectorDone += OnSectorDone;
Found.OnListChanged += _ => { if (Landmarks.Instance) Landmarks.Instance.Refresh(); Changed?.Invoke(); };
if (Landmarks.Instance) Landmarks.Instance.Refresh();
}
void UnwatchSectors() => MowMap.SectorDone -= OnSectorDone;
/// Each peer finishes sectors for itself, a little apart: whoever gets there first tells the host.
void OnSectorDone(int id)
{
if (IsServer) ServerCloseSector(id);
else SectorDoneRpc(id);
}
[Rpc(SendTo.Server)]
void SectorDoneRpc(int id, RpcParams rpc = default) => ServerCloseSector(id);
void ServerCloseSector(int id)
{
if (id < 0 || id >= HexGrid.Cells || !MowMap.Claim(id)) return;
double pay = GameDefs.SectorBonus(Level(PerkId.RegionBonus)) * Crops.Pays(Crops.At(id));
Money.Value += pay;
Earned.Value += pay;
Closed.Value++;
SectorClosedRpc(id, pay);
}
[Rpc(SendTo.Everyone)]
void SectorClosedRpc(int id, double pay)
{
MowMap.Close(id);
SectorClosed?.Invoke(id, pay);
}
/// What the crew has mown; the whole planet once the last sector with grass on it is done.
static double MownNow()
{
double area = MowMap.MownArea();
return MowMap.Left == 0 ? GameDefs.PlanetArea : System.Math.Min(area, GameDefs.PlanetArea * 0.99998d);
}
void TickSectors()
{
if (Time.time < _mownAt) return;
_mownAt = Time.time + 1f;
Mown.Value = MownNow();
}
// ───────────────────────── stakes & survey points ─────────────────────────
[Rpc(SendTo.Server)]
public void ClaimMarkRpc(int id, RpcParams rpc = default)
{
var who = PlayerOf(rpc.Receive.SenderClientId);
if (!who || id < 0 || id >= Landmarks.Count || Found.Contains(id)) return;
if ((who.transform.position - Landmarks.Spot(id)).sqrMagnitude > 64f) return;
double pay = Landmarks.Pay(id);
Found.Add(id);
Money.Value += pay;
Earned.Value += pay;
MarkFoundRpc(who.DisplayName, id, pay);
}
[Rpc(SendTo.Everyone)]
void MarkFoundRpc(FixedString64Bytes who, int id, double pay) => MarkFound?.Invoke(who.ToString(), id, pay);
public int FoundCount(bool points)
{
int n = 0;
foreach (int id in Found) if (Landmarks.IsPoint(id) == points) n++;
return n;
}
}
}