import SwiftUI
import SaplingStorage

public struct SettingsView: View {
    @Binding private var configuration: SaplingConfiguration
    private let onSave: (SaplingConfiguration) -> Void

    public init(
        configuration: Binding<SaplingConfiguration>,
        onSave: @escaping (SaplingConfiguration) -> Void
    ) {
        self._configuration = configuration
        self.onSave = onSave
    }

    public var body: some View {
        Form {
            Section("General") {
                TextField("Default branch", text: binding(\.defaultBranchName))
                Toggle("Autosave drafts", isOn: binding(\.autosavesDrafts))
                Toggle("Show hidden files", isOn: binding(\.showsHiddenFiles))
            }

            Section("Editor") {
                HStack {
                    Slider(value: binding(\.preferredEditorFontSize), in: 11...24, step: 1)
                    Text("\(Int(configuration.preferredEditorFontSize)) pt")
                        .foregroundStyle(.secondary)
                        .monospacedDigit()
                }
            }
        }
        .formStyle(.grouped)
        .frame(minWidth: 420, minHeight: 260)
        .padding()
    }

    private func binding<Value>(_ keyPath: WritableKeyPath<SaplingConfiguration, Value>) -> Binding<Value> {
        Binding(
            get: { configuration[keyPath: keyPath] },
            set: { newValue in
                configuration[keyPath: keyPath] = newValue
                onSave(configuration)
            }
        )
    }
}
