using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// GAME 1303 Tier 6 — Starts a conversation when the player walks into an area, no button
/// press needed. Opening narration, a ghost appearing, a warning as you enter a room.
///
/// SETUP
///  - Empty GameObject + Collider2D (Is Trigger) + this script. Drag in the DialogueData
///    and the scene's DialogueRunner.
///  - One Shot is on by default so it doesn't fire every time you walk back through.
///  - Require Flags gates it on story state ("only after you've found the body").
///  - Trigger On Start instead of on enter, for an opening narration when the scene loads.
///
/// For a conversation the player chooses to have, use an Interactable instead and wire its
/// OnInteract -> DialogueRunner.StartDialogue. This one is for moments the game imposes.
/// </summary>
public class DialogueTrigger : MonoBehaviour
{
    public DialogueData dialogue;
    public DialogueRunner runner;
    public bool oneShot = true;
    public bool triggerOnStart = false;
    public float startDelay = 0f;
    [Tooltip("Flags required (comma separated; ! to negate).")]
    public string requireFlags = "";

    public UnityEvent OnTriggered;

    private bool used;

    void Reset()
    {
        var col = GetComponent<Collider2D>();
        if (col != null) col.isTrigger = true;
    }

    void Start()
    {
        if (runner == null) runner = FindFirstObjectByType<DialogueRunner>();
        if (triggerOnStart) Invoke(nameof(Fire), startDelay);
    }

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

    public void Fire()
    {
        if (used && oneShot) return;
        if (dialogue == null || runner == null) return;
        if (!string.IsNullOrWhiteSpace(requireFlags) &&
            ChoiceFlagManager.Instance != null && !ChoiceFlagManager.Instance.HasAll(requireFlags)) return;

        used = true;
        runner.StartDialogue(dialogue);
        OnTriggered?.Invoke();
    }
}