using UnityEngine;
using UnityEngine.Playables;

[DisallowMultipleComponent]
public class KillSwitch : MonoBehaviour
{
    [Header("Animator State")]
    [SerializeField] private string animatorStateName = "DeathBack1hMelee";

    [Header("Capsule Collider (Death)")]
    [SerializeField] private float colliderBlendDuration = 2f;
    [SerializeField] private float addY = -0.74f;
    [SerializeField] private float addZ = -0.8f;

    [Header("Script")]
    [SerializeField] private KillerController kc;

    private PlayableDirector playableDirector;
    private Animator animator;
    private CapsuleCollider capsule;

    private Vector3 startCenter;
    private Vector3 targetCenter;

    private bool hasSwitched;
    private bool blending;
    private float blendT;

    private void Awake()
    {
        playableDirector = GetComponent<PlayableDirector>() ??
                           GetComponentInParent<PlayableDirector>();

        animator = GetComponent<Animator>() ??
                   GetComponentInChildren<Animator>(true);

        capsule = GetComponent<CapsuleCollider>() ??
                  GetComponentInChildren<CapsuleCollider>();

        if (capsule != null)
        {
            startCenter = capsule.center;

            // ✅ RELATIVE offset (this is the important part)
            targetCenter = new Vector3(
                startCenter.x,
                startCenter.y + addY,
                startCenter.z + addZ
            );
        }
    }

    private void Update()
    {
        if (!blending || capsule == null) return;

        blendT += Time.deltaTime / colliderBlendDuration;
        float t = Mathf.Clamp01(blendT);

        capsule.center = Vector3.Lerp(startCenter, targetCenter, t);

        if (t >= 1f)
            blending = false;
    }

    public void SwitchFromTimelineToAnimator()
    {
        if (hasSwitched) return;
        hasSwitched = true;

        if (playableDirector != null)
            playableDirector.Stop();

        if (animator == null) return;

        animator.enabled = true;
        animator.Rebind();
        animator.Update(0f);
        animator.Play(animatorStateName, 0, 0f);
        kc.enabled = false;
        GameManager.Instance.RemoveFromList(gameObject);

        if (capsule != null)
        {
            capsule.direction = 2; // Z axis
            blendT = 0f;
            blending = true;
        }
    }
}
