using Godot;

namespace Theriapolis.GodotHost.Scenes.Widgets;

/// <summary>
/// Draggable ability-score token. Replaces the React prototype's
/// <c>.die</c> + filled <c>.slot</c> in <c>steps.jsx</c> per
/// GODOT_PORTING_GUIDE.md §7.1. Shows the int value as a centered
/// label; <c>_GetDragData</c> returns a Dictionary payload describing
/// where the token came from so the step can mutate CharacterDraft
/// accordingly.
///
/// Tokens are owned by either an AbilityPool (Origin == "pool",
/// OriginPoolIdx set) or an AbilitySlot (Origin == "slot",
/// OriginAbility set). Dropping a token rebuilds the StepStats UI from
/// the new draft state — token instances are short-lived.
/// </summary>
public partial class AbilityToken : PanelContainer
{
    [Export] public int Value { get; set; }
    [Export] public string Origin { get; set; } = "pool";
    [Export] public string OriginAbility { get; set; } = "";
    [Export] public int OriginPoolIdx { get; set; } = -1;

    public override void _Ready()
    {
        CustomMinimumSize = new Vector2(56, 56);
        ThemeTypeVariation = "AbilityToken";
        // PASS so clicks propagate up to the parent AbilitySlot's GuiInput
        // handler (click-to-return). Drag detection still triggers on the
        // deepest non-IGNORE Control under the cursor, so PASS works for
        // _GetDragData too.
        MouseFilter = MouseFilterEnum.Pass;

        var label = new Label
        {
            Text = Value.ToString(),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            MouseFilter = MouseFilterEnum.Ignore,
        };
        label.AddThemeFontSizeOverride("font_size", 22);
        AddChild(label);
    }

    public override Variant _GetDragData(Vector2 atPosition)
    {
        // Drag preview — a dimmed duplicate of the token.
        var preview = new Panel { CustomMinimumSize = new Vector2(56, 56) };
        var lbl = new Label
        {
            Text = Value.ToString(),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
        };
        lbl.AddThemeFontSizeOverride("font_size", 22);
        lbl.AnchorRight = 1f;
        lbl.AnchorBottom = 1f;
        preview.AddChild(lbl);
        preview.Modulate = new Color(1, 1, 1, 0.85f);
        SetDragPreview(preview);

        return new Godot.Collections.Dictionary
        {
            { "kind", "ability_value" },
            { "value", Value },
            { "from", Origin },
            { "ability", OriginAbility },
            { "idx", OriginPoolIdx },
        };
    }
}
