import SwiftUI

struct DiagnosticsView: View {
    @ObservedObject var controller: RecordingController
    @State private var mode: CaptureMode = .fusedOnly
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                Text("Sensor diagnostics").font(.title2)
                Text("Rigid torso mount. Remain still for 30 seconds, then perform each slow or rapid lean and return. Instructions mark protocol timing; they do not prove movement onset.")
                if controller.synthetic { Text("SYNTHETIC • UI TEST MOTION").foregroundStyle(.orange) }
                Text(controller.status).accessibilityIdentifier("diagnosticStatus")
                Text("\(controller.elapsed, specifier: "%.1f") seconds · fused \(controller.counts[.motion, default: 0]) samples")
                if controller.state == .recording && controller.diagnosticsActive {
                    Text(controller.diagnosticInstruction).font(.title).bold().accessibilityIdentifier("diagnosticInstruction")
                    if controller.diagnosticMovementReady {
                        Button("Movement complete / next") { controller.nextDiagnosticDrill() }.buttonStyle(.borderedProminent).frame(minHeight: 52).accessibilityIdentifier("nextDiagnosticDrill")
                    }
                    Button("Stop and save diagnostics") { controller.stopRecording() }.buttonStyle(.borderedProminent).tint(.red).frame(minHeight: 52).accessibilityIdentifier("stopDiagnostics")
                } else if controller.state == .saved, let url = controller.savedURL {
                    SessionReviewView(url: url)
                    Button("Another diagnostic") { controller.acknowledgeSaved() }.accessibilityIdentifier("anotherDiagnostic")
                } else if controller.state == .finalizing { ProgressView("Saving diagnostics…") }
                else if controller.state == .saveError { Button("Retry save") { controller.retrySave() } }
                else {
                    Picker("Diagnostic streams", selection: $mode) {
                        Text("Fused").tag(CaptureMode.fusedOnly)
                        Text("Fused + raw").tag(CaptureMode.combined)
                        Text("Raw only").tag(CaptureMode.rawOnly)
                    }.pickerStyle(.segmented).accessibilityIdentifier("diagnosticMode")
                    Text("Calibration is optional for noise and device-frame drift. Rider angles and transition analysis remain unavailable until calibrated. Changing streams restarts capture and requires recalibration.").font(.caption)
                    Button("Start 30-second stationary phase") { controller.startDiagnostics(mode: mode) }.buttonStyle(.borderedProminent).frame(minHeight: 52).disabled(![.uncalibrated,.ready].contains(controller.state)).accessibilityIdentifier("startDiagnostics")
                }
            }.padding()
        }.navigationTitle("Diagnostics")
    }
}
