using Godot;
using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.interfaces;

namespace Mr.BrickAdventures.scripts.components;

[GlobalClass]
public partial class ExitDoorComponent : Area2D, IUnlockable
{
    [Export] public bool Locked { get; set; } = true;
    [Export] public Sprite2D DoorSprite { get; set; }
    [Export] public AudioStreamPlayer2D OpenDoorSfx { get; set; }
    [Export] public int OpenedDoorFrame { get; set; } = 0;
    [Export] public string AchievementId = "level_complete_1";

    [Signal] public delegate void ExitTriggeredEventHandler();

    public override void _Ready()
    {
        BodyEntered += OnExitAreaBodyEntered;

    }

    private void OnExitAreaBodyEntered(Node2D body)
    {
        if (Locked) return;

        EmitSignalExitTriggered();
        AchievementManager.Instance?.UnlockAchievement(AchievementId);
        CallDeferred(nameof(GoToNextLevel));
    }

    public void Unlock()
    {
        Locked = false;
        if (DoorSprite != null)
        {
            DoorSprite.Frame = OpenedDoorFrame;
        }

        OpenDoorSfx?.Play();
    }

    private void GoToNextLevel()
    {
        GameManager.Instance?.OnLevelComplete();
    }
}