using System.Linq;
using RimWorld;
using Verse;

namespace ArachnaeSwarm
{
    public class Hediff_HiveMindDrone : HediffWithTarget
    {
        public override string LabelBase
        {
            get
            {
                string baseLabel = base.LabelBase + " (" + (target != null ? target.LabelShortCap : "未连接") + ")";
                
                // Get the HediffComp_HiveMindDrone to access ticksUnlinked
                HediffComp_HiveMindDrone comp = this.TryGetComp<HediffComp_HiveMindDrone>();
                if (comp != null)
                {
                    // Safely cast target to Pawn for Dead and health checks
                    Pawn masterPawn = target as Pawn;

                    if (masterPawn == null || masterPawn.Destroyed || masterPawn.Dead || !masterPawn.health.hediffSet.HasHediff(HediffDef.Named("ARA_HiveMindMaster")))
                    {
                        float timeLeftSecs = (comp.Props.unlinkedDieDelayTicks - comp.TicksUnlinked) / 60f;
                        if (timeLeftSecs > 0)
                        {
                            return baseLabel + " (死亡倒计时: " + timeLeftSecs.ToString("F1") + "s)";
                        }
                    }
                }
                return baseLabel;
            }
        }

        public override void PostAdd(DamageInfo? dinfo)
        {
            base.PostAdd(dinfo);
            // No direct linking in PostAdd, master will link manually
        }

        public override bool ShouldRemove
        {
            get
            {
                // Only remove if base ShouldRemove is true, OR if pawn is dead
                // We do NOT want to remove it just because target is invalid, as the Comp will handle delayed death
                if (base.ShouldRemove && pawn.Dead)
                {
                    return true;
                }
                // Also remove if pawn is no longer spawned or on a map
                if (!pawn.Spawned || pawn.Map == null)
                {
                    return true;
                }
                return false; // Let the Comp handle the unlinked death
            }
        }

        public override void PostRemoved()
        {
            base.PostRemoved();
            // Deregister from the master when this hediff is removed
            // Ensure target is a Pawn and not dead before attempting to deregister
            if (this.target is Pawn master && master != null && !master.Destroyed && !master.Dead)
            {
                var masterHediff = master.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("ARA_HiveMindMaster")) as Hediff_HiveMindMaster;
                masterHediff?.DeregisterDrone(this.pawn);
            }
        }
        // PostTick logic moved to HediffComp_HiveMindDrone
    }
}