import SwiftUI

struct TreeNodeView: View {
    let node: RemoteTreeNode
    let formId: String
    let widgetId: String
    let depth: Int
    @Environment(ConnectionManager.self) private var manager

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Button {
                manager.sendFormEvent(
                    formId: formId, widgetId: widgetId,
                    eventType: .treeNodeClicked,
                    value: .string(node.id)
                )
            } label: {
                HStack {
                    if !node.children.isEmpty {
                        Image(systemName: node.isExpanded ? "chevron.down" : "chevron.right")
                            .font(.caption)
                    }
                    Text(node.text)
                }
                .padding(.leading, CGFloat(depth) * 16)
            }

            if node.isExpanded {
                ForEach(node.children) { child in
                    TreeNodeView(
                        node: child, formId: formId,
                        widgetId: widgetId, depth: depth + 1
                    )
                }
            }
        }
    }
}
