import SwiftUI

struct SettingsView: View {
    @EnvironmentObject var settings: AppSettings
    @State private var draftURL: String = ""

    var body: some View {
        Form {
            Section("Backend") {
                TextField("URL", text: $draftURL, prompt: Text("http://127.0.0.1:8085"))
                    .textFieldStyle(.roundedBorder)
                    .frame(minWidth: 320)
                HStack {
                    Button("Apply") { settings.backendURL = draftURL.trimmingCharacters(in: .whitespaces) }
                        .keyboardShortcut(.defaultAction)
                    Spacer()
                    Text("Override at launch with CXWEBAPP_URL=…")
                        .font(.caption).foregroundStyle(.secondary)
                }
            }

            Section("Behavior") {
                Toggle("Enable WebKit developer extras (Inspect Element)",
                       isOn: $settings.developerExtras)
                Stepper(value: $settings.autoReloadSeconds, in: 0...3600, step: 5) {
                    Text("Auto-reload every \(settings.autoReloadSeconds)s "
                         + (settings.autoReloadSeconds == 0 ? "(disabled)" : ""))
                }
            }

            Section("Presets") {
                presetRow("Local",       "http://127.0.0.1:8085")
                presetRow("VPS (Caddy)", "https://cxwebapp.76-13-126-127.nip.io")
            }
        }
        .padding(20)
        .frame(width: 480)
        .onAppear { draftURL = settings.backendURL }
    }

    private func presetRow(_ label: String, _ url: String) -> some View {
        HStack {
            Text(label).frame(width: 100, alignment: .leading)
            Text(url).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
            Spacer()
            Button("Use") { draftURL = url; settings.backendURL = url }
                .controlSize(.small)
        }
    }
}
