using Avalonia.Controls;
using Avalonia.Input;
using ClaudeDo.Ui.ViewModels.Modals;

namespace ClaudeDo.Ui.Views.Modals;

public partial class DiffViewerView : Window
{
    public DiffViewerView()
    {
        InitializeComponent();
    }

    protected override void OnDataContextChanged(EventArgs e)
    {
        base.OnDataContextChanged(e);
        if (DataContext is DiffViewerViewModel vm)
            vm.CloseAction = Close;

        // SelectedItem TwoWay binding can miss on Avalonia 12 TreeView — back it
        // up with SelectionChanged.
        var tree = this.FindControl<TreeView>("FileTree");
        if (tree is not null)
            tree.SelectionChanged += OnFileTreeSelectionChanged;
    }

    private void OnFileTreeSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (DataContext is DiffViewerViewModel vm && sender is TreeView tree)
            vm.SelectedNode = tree.SelectedItem as DiffTreeNodeViewModel;
    }

    private void OnNodeTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not Control c) return;
        if (c.DataContext is not DiffTreeNodeViewModel node) return;
        if (!node.IsDirectory) return;
        node.IsExpanded = !node.IsExpanded;
        e.Handled = true;
    }
}
