import SwiftUI

struct StatusBar: View {
    let state: AppState

    var body: some View {
        HStack(spacing: 8) {
            connectionIndicator
            Text(state.status)
                .font(.subheadline)
                .lineLimit(1)

            Spacer()

            refButtons

            Text(String(format: "%.1f\u{00B0}C", state.tempC))
                .font(.subheadline.monospacedDigit())
                .foregroundStyle(.secondary)
        }
        .padding(.horizontal)
        .padding(.vertical, 6)
        .background(.ultraThinMaterial)
    }

    private var connectionIndicator: some View {
        Circle()
            .fill(state.connected ? Color.green : Color.red)
            .frame(width: 8, height: 8)
    }

    @ViewBuilder
    private var refButtons: some View {
        HStack(spacing: 4) {
            if !state.collectingRefs {
                Button("Collect Refs") { state.collectRefs() }
                    .buttonStyle(.bordered)
                    .tint(.green)
                    .controlSize(.small)
            } else {
                Button("Collecting...") {}
                    .buttonStyle(.bordered)
                    .controlSize(.small)
                    .disabled(true)
            }

            if state.hasDeviceRefs {
                Button("Clear Refs") { state.clearRefs() }
                    .buttonStyle(.bordered)
                    .tint(.red)
                    .controlSize(.small)
            }

            if state.hasCurrentData {
                Button("Set Ref") { state.setReference() }
                    .buttonStyle(.bordered)
                    .controlSize(.small)
            }

            if state.hasCurrentRef {
                Button("Clear Ref") { state.clearReference() }
                    .buttonStyle(.bordered)
                    .tint(.red)
                    .controlSize(.small)

                Text("REF")
                    .font(.caption2.bold())
                    .foregroundStyle(.orange)
            }
        }
    }
}
