using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// GAME 1303 Tier 2 — Consecutive hits raise your damage. Stardust's core mechanic.
///
/// SETUP
///  1. Add to the PLAYER root (same object as Health / PlayerController2D).
///  2. On every melee Hitbox the player owns, wire OnHit -> ComboCounter.RegisterHit.
///     (Hitbox finds the ComboCounter on its parent to read DamageMultiplier, but you
///     wire RegisterHit yourself so the counter goes up.) Projectiles fired by a
///     ProjectileShooter on the same object register hits automatically — don't
///     wire those too or they'll count double.
///  3. Wire player Health.OnDamaged -> ComboCounter.ResetCombo so getting hit breaks the combo.
///  4. HUD: OnComboChanged(count, multiplier) -> a text like "12 HITS  x1.6".
///
/// Multiplier = 1 + (combo * Damage Per Hit), capped at Max Multiplier.
/// Combo drops to 0 if no hit lands within Combo Window seconds.
/// </summary>
public class ComboCounter : MonoBehaviour
{
    [Tooltip("Seconds allowed between hits before the combo resets.")]
    public float comboWindow = 2f;
    [Tooltip("Each hit in the combo adds this much to the multiplier (0.1 = +10%).")]
    public float damagePerHit = 0.1f;
    public float maxMultiplier = 3f;

    [Header("Events")]
    public UnityEvent<int, float> OnComboChanged;   // (count, multiplier)
    public UnityEvent OnComboBroken;

    public int Combo { get; private set; }
    public float DamageMultiplier => Mathf.Min(maxMultiplier, 1f + Combo * damagePerHit);

    private float timer;

    void Update()
    {
        if (Combo == 0) return;
        timer -= Time.deltaTime;
        if (timer <= 0f) ResetCombo();
    }

    /// <summary>Wire Hitbox.OnHit / Projectile.OnHit here. The Hurtbox argument is ignored.</summary>
    public void RegisterHit(Hurtbox target) => RegisterHit();

    public void RegisterHit()
    {
        Combo++;
        timer = comboWindow;
        OnComboChanged?.Invoke(Combo, DamageMultiplier);
    }

    public void ResetCombo()
    {
        if (Combo == 0) return;
        Combo = 0;
        timer = 0f;
        OnComboChanged?.Invoke(0, 1f);
        OnComboBroken?.Invoke();
    }
}