import SwiftUI

struct PlayerDeckView: View {
    @ObservedObject var model: AppModel

    var progress: Double {
        guard model.trackDuration > 0 else { return 0 }
        return min(1, max(0, Double(model.playerPositionMs) / (model.trackDuration * 1000)))
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 14) {
            HStack(alignment: .top) {
                VStack(alignment: .leading, spacing: 4) {
                    Text(model.sourceMode.rawValue)
                        .font(Theme.mono(12, weight: .bold))
                        .foregroundStyle(Theme.accent)
                    Text(model.channelName)
                        .font(Theme.headlineFont)
                        .foregroundStyle(Theme.text)
                    Text(model.trackTitle)
                        .font(Theme.pixel(22, weight: .bold))
                        .foregroundStyle(Theme.text)
                        .lineLimit(2)
                }

                Spacer()

                VStack(alignment: .trailing, spacing: 4) {
                    Text(model.playbackMode.uppercased())
                        .font(Theme.mono(12))
                        .foregroundStyle(Theme.amber)
                    Text(model.playbackState.uppercased())
                        .font(Theme.mono(12))
                        .foregroundStyle(model.isPlaying ? Theme.ready : Theme.muted)
                }
            }

            VStack(alignment: .leading, spacing: 8) {
                ProgressView(value: progress)
                    .tint(Theme.ready)
                    .background(Theme.panel2)
                    .clipShape(RoundedRectangle(cornerRadius: Theme.smallCorner))

                HStack {
                    Text(formatTime(model.playerPositionMs))
                    Spacer()
                    Text(formatDuration(model.trackDuration))
                }
                .font(Theme.mono(12))
                .foregroundStyle(Theme.muted)
            }

            HStack(spacing: 8) {
                iconButton("backward.end.fill") { model.previous() }
                iconButton("gobackward.15") { model.seekBy(seconds: -15) }
                Button {
                    model.togglePlay()
                } label: {
                    Image(systemName: model.isPlaying ? "pause.fill" : "play.fill")
                        .font(Theme.pixel(24, weight: .bold))
                        .frame(width: 58, height: 48)
                }
                .buttonStyle(.borderedProminent)
                .tint(Theme.accent)
                iconButton("goforward.15") { model.seekBy(seconds: 15) }
                iconButton("forward.end.fill") { model.next() }
            }

            HStack(spacing: 8) {
                actionButton("Mode", icon: "repeat") {
                    Task { await model.cyclePlaybackMode() }
                }
                actionButton("Queue", icon: "text.badge.plus") {
                    Task { await model.queueCurrent(playNext: false) }
                }
                actionButton("Next", icon: "text.line.first.and.arrowtriangle.forward") {
                    Task { await model.queueCurrent(playNext: true) }
                }
                actionButton("Stop", icon: "power") {
                    model.stopAndExit()
                }
            }

            HStack(spacing: 12) {
                meter("DRIFT", "\(model.driftMs)ms", model.sourceMode == .radio && abs(model.driftMs) > 1800 ? Theme.amber : Theme.ready)
                meter("ROOMS", "\(model.channels.count)", Theme.text)
                meter("QUEUE", "\(model.queue.count)", Theme.text)
            }
        }
        .panel()
    }

    private func iconButton(_ systemName: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Image(systemName: systemName)
                .frame(maxWidth: .infinity, minHeight: 44)
        }
        .buttonStyle(.bordered)
    }

    private func actionButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Label(title, systemImage: icon)
                .labelStyle(.iconOnly)
                .frame(maxWidth: .infinity, minHeight: 38)
        }
        .buttonStyle(.bordered)
        .accessibilityLabel(title)
    }

    private func meter(_ label: String, _ value: String, _ color: Color) -> some View {
        VStack(alignment: .leading, spacing: 2) {
            Text(label)
                .font(Theme.microFont)
                .foregroundStyle(Theme.muted)
            Text(value)
                .font(Theme.mono(13, weight: .bold))
                .foregroundStyle(color)
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(8)
        .background(Theme.panel2)
        .clipShape(RoundedRectangle(cornerRadius: Theme.corner))
    }
}
