using Verse;
using RimWorld;

namespace ArachnaeSwarm
{
    public class HediffComp_HiveMindDrone : HediffComp
    {
        public HediffCompProperties_HiveMindDrone Props => (HediffCompProperties_HiveMindDrone)this.props;

        public int TicksUnlinked => ticksUnlinked; // Expose as public property
        private int ticksUnlinked = 0;

        public override void CompExposeData()
        {
            base.CompExposeData();
            Scribe_Values.Look(ref ticksUnlinked, "ticksUnlinked", 0);
        }

        public override void CompPostTick(ref float severityAdjustment)
        {
            base.CompPostTick(ref severityAdjustment);

            // Only check if pawn is spawned and on a map
            if (parent.pawn.Spawned && parent.pawn.Map != null)
            {
                // We use parent.pawn.IsHashIntervalTick(60) for performance
                if (!parent.pawn.IsHashIntervalTick(60))
                    return;

                Hediff_HiveMindDrone droneHediff = parent as Hediff_HiveMindDrone;
                if (droneHediff == null) return; // Should not happen

                Pawn masterPawn = droneHediff.target as Pawn;

                if (masterPawn == null || masterPawn.Destroyed || masterPawn.Dead || !masterPawn.health.hediffSet.HasHediff(HediffDef.Named("ARA_HiveMindMaster")))
                {
                    // Master is invalid or unlinked, start/continue unlinked timer
                    ticksUnlinked += 60; // Increment by 60 because we check every 60 ticks
                    if (ticksUnlinked >= Props.unlinkedDieDelayTicks)
                    {
                        Log.Message($"[ArachnaeSwarm] Drone {parent.pawn.LabelShort} was unlinked from master for too long and will die. Forcing death.");
                        // Ensure the pawn is killed only once and prevent further ticks
                        if (!parent.pawn.Dead && !parent.pawn.Destroyed)
                        {
                            parent.pawn.Kill(null, parent);
                        }
                    }
                }
                else
                {
                    // Master is valid, reset unlinked timer
                    ticksUnlinked = 0;
                }
            }
        }
    }
}