using UnityEngine;
using UnityEngine.Events;
using System;

public class LevelManager : MonoBehaviour, ITask
{
    public static LevelManager Instance;

    [Header("Nastavení levelu")]
    [Tooltip("Kolik itemů musí hráč trefit pro splnění levelu")]
    public int itemsToScore = 3;

    [Header("Event – vyvolá se po trefení všech itemů")]
    public UnityEvent OnAllItemsScored;

    private int scoredCount = 0;

    // ── ITask ────────────────────────────────────────────────────────────────
    public string TaskID { get; set; }
    public TaskType TaskType { get; set; }
    public string TaskName { get; set; }
    public (double, double) TaskLocation { get; set; }
    public bool IsCompleted { get; private set; }

    private Action<ITask> _onCompleted;
    private Action<ITask> _onExit;

    public void Initialize(Action<ITask> onCompleted)
    {
        IsCompleted = false;
        _onCompleted = onCompleted;
        ResetCounter();
        // Wire OnAllItemsScored to Complete() if not already wired
        OnAllItemsScored.AddListener(Complete);
    }

    public void Complete()
    {
        if (IsCompleted) return;
        IsCompleted = true;
        Debug.Log("[LevelManager] Task complete!");
        _onCompleted?.Invoke(this);
        ExitTask(_onExit);
    }

    public void ExitTask(Action<ITask> onExit)
    {
        onExit?.Invoke(this);
    }
    // ─────────────────────────────────────────────────────────────────────────

    void Awake()
    {
        if (Instance == null) Instance = this;
        else Destroy(gameObject);
    }

    public void RegisterItem()
    {
        scoredCount++;
        Debug.Log($"Trefeno: {scoredCount} / {itemsToScore}");

        if (scoredCount >= itemsToScore)
        {
            OnAllItemsScored?.Invoke();
        }
    }

    public void ResetCounter()
    {
        scoredCount = 0;
    }

    public int GetScoredCount() => scoredCount;
    public int GetTotalCount() => itemsToScore;
}

