using System;using System.Linq;using System.Collections.Generic;
 internal static class LashDeathSlamRules
 {
  internal const int MaxTargets=32;
  internal const float GrabRadius=35f,ImpactRadius=6f,Damage=8.75f,PullSeconds=.3f,SlamSpeed=40.64f;
  internal static bool InSphere(Vector3 center,Vector3 point)=> (point-center).sqrMagnitude<=GrabRadius*GrabRadius;
  internal static CharacterBody[] Acquire(CharacterBody owner)
  {
   if(!owner||!owner.teamComponent)return new CharacterBody[0];
   var teams=TeamMask.GetUnprotectedTeams(owner.teamComponent.teamIndex);
   // Enumerate bodies, not hurtbox colliders: one enemy per body, all directions.
   return CharacterBody.readOnlyInstancesList.Where(t=>t&&t!=owner&&t.healthComponent&&t.healthComponent.alive&&t.teamComponent&&teams.HasTeam(t.teamComponent.teamIndex)&&InSphere(owner.corePosition,t.corePosition))
    .OrderBy(t=>(t.corePosition-owner.corePosition).sqrMagnitude).Take(MaxTargets).ToArray();
  }
  internal static void WriteTargets(NetworkWriter writer,GameObject[] targets)
  {writer.Write((byte)Mathf.Min(MaxTargets,targets.Length));foreach(var obj in targets.Take(MaxTargets))writer.Write(obj);}
  internal static GameObject[] ReadTargets(NetworkReader reader)
  {int count=reader.ReadByte();if(count>MaxTargets)throw new InvalidOperationException("Invalid Death Slam target count");var result=new GameObject[count];for(int i=0;i<count;i++)result[i]=reader.ReadGameObject();return result;}
  internal static Vector3 Gather(CharacterBody owner,int index)
  {var forward=Vector3.ProjectOnPlane(owner.inputBank.aimDirection,Vector3.up).normalized;if(forward.sqrMagnitude<.01f)forward=owner.transform.forward;var side=Vector3.Cross(Vector3.up,forward);return owner.footPosition+forward*3+side*((index%5)-2)*.55f;}
  internal static Vector3 Spread(int index){float a=index*2.399963f,r=Mathf.Min(2.4f,.6f*Mathf.Sqrt(index));return new Vector3(Mathf.Cos(a)*r,0,Mathf.Sin(a)*r);}
  internal static void Release(GameObject[] targets)
  {if(!NetworkServer.active)return;foreach(var obj in targets){var victim=obj?obj.GetComponent<LashSlamVictim>():null;if(victim)victim.Release();}}
 }
 public sealed class LashDeathSlamThrowState:LashCastState
 {
  internal GameObject[] Targets=new GameObject[0];internal Vector3 Landing;
  Vector3 origin;float duration;bool landed,advancing;
  public override void OnEnter()
  {
   base.OnEnter();origin=characterBody.footPosition;duration=Mathf.Clamp(Vector3.Distance(origin,Landing)/LashDeathSlamRules.SlamSpeed,.25f,1.5f);
   if(characterMotor)characterMotor.onHitGroundAuthority+=Landed;
   controller?.Motion("ability_deathslam_throw_inair",2.267f,true);LashEffects.Cast(characterBody,"deathslam_throw",.7f);LashAudio.Play(gameObject,"lash_death_slam_launch",.8f);
   if(NetworkServer.active){int i=0;foreach(var obj in Targets){var target=obj?obj.GetComponent<CharacterBody>():null;if(!target||!target.healthComponent||!target.healthComponent.alive||target.isBoss)continue;var held=obj.GetComponent<LashSlamVictim>();if(!held){held=obj.AddComponent<LashSlamVictim>();held.Begin(characterBody);}int slot=i++;held.Throw(Landing+LashDeathSlamRules.Spread(slot),LashDeathSlamRules.Gather(characterBody,slot),duration);}}
  }
  void Landed(ref CharacterMotor.HitGroundInfo info){if(fixedAge>=LashDeathSlamRules.PullSeconds)landed=true;}
  public override void FixedUpdate()
  {
   base.FixedUpdate();if(!isAuthority)return;
   bool diving=fixedAge>=LashDeathSlamRules.PullSeconds;
   bool contact=diving&&characterMotor&&(landed||characterMotor.isGrounded);
   if(diving&&!contact&&characterMotor)
   {
    var c=characterMotor.GetComponent<CapsuleCollider>();var foot=characterBody.footPosition;
    if(c){var b=c.bounds;foot=new Vector3(b.center.x,b.min.y,b.center.z);}
    contact=Physics.Raycast(foot+Vector3.up*.1f,Vector3.down,out var hit,.3f,LayerIndex.world.mask,QueryTriggerInteraction.Ignore)&&hit.normal.y>.35f;
   }
   if(contact)
   {advancing=true;outer.SetNextState(new LashDeathSlamImpactState{Targets=Targets,Point=characterBody.footPosition});return;}
   if(characterMotor)
   {
    if(!diving){var v=characterMotor.velocity;v.y=0;characterMotor.velocity=v;}
    else
    {
     var desired=LashSlamTrajectory.Sample(origin,origin,Landing,fixedAge,duration);
     var v=(desired-characterBody.footPosition)/Time.fixedDeltaTime;
     // Once the sampled path ends, continue down until collision confirms contact.
     if(fixedAge>=LashDeathSlamRules.PullSeconds+duration)v.y=Mathf.Min(v.y,-20);
     characterMotor.velocity=Vector3.ClampMagnitude(v,80);
    }
   }
   // A blocked/invalid destination cancels safely; no timer-triggered explosion.
   if(fixedAge>5){LashDeathSlamRules.Release(Targets);outer.SetNextStateToMain();}
  }
  public override void OnExit(){if(characterMotor)characterMotor.onHitGroundAuthority-=Landed;if(isAuthority&&!advancing)LashDeathSlamRules.Release(Targets);base.OnExit();}
  public override void OnSerialize(NetworkWriter writer){base.OnSerialize(writer);writer.Write(Landing);LashDeathSlamRules.WriteTargets(writer,Targets);}
  public override void OnDeserialize(NetworkReader reader){base.OnDeserialize(reader);Landing=reader.ReadVector3();Targets=LashDeathSlamRules.ReadTargets(reader);}
 }
 public sealed class LashDeathSlamImpactState:LashCastState
 {
  internal GameObject[] Targets=new GameObject[0];internal Vector3 Point;
  public override void OnEnter()
  {
   base.OnEnter();if(isAuthority&&characterMotor)characterMotor.velocity=Vector3.zero;
   // One impact, at the caster's real contact point. The Source2 graph and
   // impact audio are selected by the supplied ultimate's original definition.
   LashEffects.Impact(characterBody,Point,1.5f);
   if(NetworkServer.active)
   {
    var damaged=new HashSet<CharacterBody>();
    int slot=0;foreach(var obj in Targets)
    {
     var target=obj?obj.GetComponent<CharacterBody>():null;if(!target||!target.healthComponent||!target.healthComponent.alive)continue;
     var victim=obj.GetComponent<LashSlamVictim>();if(victim)victim.Land(Point+LashDeathSlamRules.Spread(slot++));
     // Directly include captured targets; do not rely on collider positions
     // catching up to their just-moved motor transforms this physics step.
     damaged.Add(target);
    }
    foreach(var enemy in LashTargeting.Nearby(characterBody,Point,LashDeathSlamRules.ImpactRadius))if(enemy)damaged.Add(enemy);
    foreach(var enemy in damaged)if(enemy.teamComponent&&enemy.teamComponent.teamIndex!=characterBody.teamComponent.teamIndex){LashTargeting.Damage(characterBody,enemy,LashDeathSlamRules.Damage);enemy.AddTimedBuff(RoR2Content.Buffs.Slow50,4);}
    LashDeathSlamRules.Release(Targets);
   }
  }
  public override void FixedUpdate(){base.FixedUpdate();if(fixedAge>=.3f&&isAuthority){controller?.ReleaseLowerBody();outer.SetNextStateToMain();}}
  public override void OnSerialize(NetworkWriter writer){base.OnSerialize(writer);writer.Write(Point);LashDeathSlamRules.WriteTargets(writer,Targets);}
  public override void OnDeserialize(NetworkReader reader){base.OnDeserialize(reader);Point=reader.ReadVector3();Targets=LashDeathSlamRules.ReadTargets(reader);}
 }
 internal static class LashSlamTrajectory
 {
  internal static Vector3 Lift(Vector3 start,Vector3 caster,float age){var top=start;top.y=Mathf.Max(start.y+2,caster.y+2);return Vector3.Lerp(start,top,Mathf.SmoothStep(0,1,Mathf.Clamp01(age/.4f)));}
  internal static Vector3 Sample(Vector3 origin,Vector3 gather,Vector3 destination,float age,float slamDuration)
  {if(age<LashDeathSlamRules.PullSeconds)return Vector3.Lerp(origin,gather,Mathf.SmoothStep(0,1,Mathf.Clamp01(age/LashDeathSlamRules.PullSeconds)));float t=Mathf.Clamp01((age-LashDeathSlamRules.PullSeconds)/slamDuration);return Vector3.Lerp(gather,destination,t*t);}
 }
