using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;

namespace ClaudeDo.Ui.Services;

/// <summary>
/// Clears focus from a TextBox when the user clicks outside of any text box, so input
/// fields behave like the user expects. Registered once for every window in the app.
/// </summary>
public static class FocusClearing
{
    public static void Install()
    {
        InputElement.PointerPressedEvent.AddClassHandler<TopLevel>(
            OnPointerPressed, RoutingStrategies.Tunnel, handledEventsToo: true);
    }

    private static void OnPointerPressed(TopLevel topLevel, PointerPressedEventArgs e)
    {
        if (topLevel.FocusManager is not { } focusManager)
            return;

        if (focusManager.GetFocusedElement() is not TextBox)
            return;

        if (e.Source is Visual v && v.FindAncestorOfType<TextBox>(includeSelf: true) is not null)
            return;

        focusManager.Focus(null);
    }
}
