import SwiftUI

struct MultiSelectContent: View {
    let formId: String
    let widget: WidgetState
    @Environment(ConnectionManager.self) private var manager

    var body: some View {
        if !widget.label.isEmpty {
            Text(widget.label)
                .font(.headline)
        }
        ForEach(widget.items.indices, id: \.self) { index in
            Button {
                toggleItem(index)
            } label: {
                HStack {
                    Image(systemName: widget.selectedIndices.contains(index) ? "checkmark.square.fill" : "square")
                    Text(widget.items[index])
                        .foregroundStyle(.primary)
                }
                .padding(.vertical, 4)
            }
            .disabled(!widget.enabled)
        }
    }

    private func toggleItem(_ index: Int) {
        if widget.selectedIndices.contains(index) {
            widget.selectedIndices.remove(index)
        } else {
            widget.selectedIndices.insert(index)
        }
        let sorted = widget.selectedIndices.sorted().map { UInt64($0) }
        manager.sendFormEvent(
            formId: formId, widgetId: widget.id,
            eventType: .multiSelectListSelectionChanged,
            value: .uintArray(sorted)
        )
    }
}
