using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// GAME 1303 Tier 5 — Point B. The recipient's door. Walk in with cargo and the delivery
/// is complete. Last Delivery.
///
/// SETUP
///  1. Sprite (a house, a hungry customer) + Collider2D (Is Trigger) + this script.
///  2. Required Cargo: how many items must arrive. 1 for a single package.
///  3. On success it calls GameManager.LevelComplete() (tick Complete Level) and/or fires
///     OnDelivered so you can show a thank-you line and load the next street.
///  4. Arriving with nothing fires OnArrivedEmpty — wire it to a "you lost my food!" line
///     and, if you like, GameManager.GameOver.
/// </summary>
[RequireComponent(typeof(Collider2D))]
public class DeliveryPoint : MonoBehaviour
{
    public int requiredCargo = 1;
    public bool completeLevel = true;
    [Tooltip("Set this flag on success (Tier 4 ChoiceFlagManager).")]
    public string setFlagOnDelivery = "";

    [Header("Events")]
    public UnityEvent<int> OnDelivered;    // how many arrived
    public UnityEvent OnArrivedEmpty;
    public UnityEvent OnPartialDelivery;   // arrived with some, but fewer than required

    private bool used;

    void Reset() { GetComponent<Collider2D>().isTrigger = true; }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (used || !other.CompareTag("Player")) return;

        var cargo = other.GetComponentInParent<DeliveryObjective>();
        if (cargo == null) return;

        if (!cargo.HasCargo) { OnArrivedEmpty?.Invoke(); return; }
        if (cargo.Cargo < requiredCargo) { OnPartialDelivery?.Invoke(); return; }

        used = true;
        int delivered = cargo.DeliverAll();

        if (!string.IsNullOrEmpty(setFlagOnDelivery)) ChoiceFlagManager.Instance?.SetFlag(setFlagOnDelivery);
        OnDelivered?.Invoke(delivered);
        if (completeLevel) GameManager.Instance?.LevelComplete();
    }
}