using Godot;

namespace Theriapolis.GodotHost.Scenes.Widgets;

/// <summary>
/// Card-style PanelContainer helpers. The codex Theme defines three
/// styleboxes for type-variation "Card":
///   - "panel"           → unselected look (Bg2 fill, Rule border)
///   - "panel_hover"     → gild border, slightly heavier weight
///   - "panel_selected"  → seal-red border + soft red shadow
///
/// State is held in Godot meta on the card so hover and selected can be
/// driven independently by different call sites (Make wires the hover
/// signals; SetSelected is called by step Refresh handlers). The active
/// stylebox is picked by Apply: selected beats hover beats default.
/// </summary>
public static class CodexCard
{
    private const string SelectedMeta = "codex_card_selected";
    private const string HoverMeta    = "codex_card_hover";

    /// <summary>
    /// Creates a PanelContainer with ThemeTypeVariation = "Card" plus
    /// hover signal wiring. The MouseEntered/MouseExited handlers update
    /// the hover meta and re-apply the right stylebox.
    /// </summary>
    public static PanelContainer Make()
    {
        var card = new PanelContainer
        {
            ThemeTypeVariation = "Card",
            MouseFilter = Control.MouseFilterEnum.Stop,
        };
        card.MouseEntered += () => SetHover(card, true);
        card.MouseExited  += () => SetHover(card, false);
        return card;
    }

    public static void SetSelected(PanelContainer card, bool selected)
    {
        card.SetMeta(SelectedMeta, selected);
        Apply(card);
    }

    private static void SetHover(PanelContainer card, bool hover)
    {
        card.SetMeta(HoverMeta, hover);
        Apply(card);
    }

    private static void Apply(PanelContainer card)
    {
        bool selected = card.HasMeta(SelectedMeta) && (bool)card.GetMeta(SelectedMeta);
        bool hover    = card.HasMeta(HoverMeta)    && (bool)card.GetMeta(HoverMeta);

        // Priority: selected > hover > default. The default branch removes
        // the override so the type variation's "panel" stylebox applies.
        StringName picked = selected ? "panel_selected"
                          : hover    ? "panel_hover"
                                     : "panel";

        if (picked == "panel" || !card.HasThemeStylebox(picked, "Card"))
            card.RemoveThemeStyleboxOverride("panel");
        else
            card.AddThemeStyleboxOverride("panel", card.GetThemeStylebox(picked, "Card"));
    }
}
