//
// SeriesRow.swift
// IceGlass-iOS
//
// Copyright 2026 Rouslan Zenetl. All Rights Reserved.
//

import SwiftUI

struct SeriesRow: View {
    let item: MainService.RoundSeriesItem

    var body: some View {
        Button(action: open) {
            HStack(alignment: .center, spacing: 12) {
                VStack(alignment: .leading, spacing: 2) {
                    Text(matchupText)
                        .font(.body)
                        .fontWeight(.medium)
                        .foregroundStyle(.primary)
                    Text(scoreText)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
                Spacer()
                VStack(alignment: .trailing, spacing: 2) {
                    Text(statusText)
                        .font(.caption)
                        .fontWeight(.medium)
                        .foregroundStyle(.secondary)
                    if let trailing = trailingText {
                        Text(trailing)
                            .font(.caption2)
                            .foregroundStyle(.tertiary)
                    }
                }
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 10)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
    }

    private var matchupText: String {
        let top = item.series.topSeedTeam?.abbrev ?? "TBD"
        let bottom = item.series.bottomSeedTeam?.abbrev ?? "TBD"
        return "\(bottom) @ \(top)"
    }

    private var scoreText: String {
        "\(item.series.bottomSeedWins) – \(item.series.topSeedWins)"
    }

    private var statusText: String {
        if let winner = item.series.winner {
            return "Final · \(winner) wins"
        }
        if let n = item.series.nextGameNumber {
            return "Game \(n)"
        }
        return ""
    }

    private var trailingText: String? {
        guard item.series.winner == nil else { return nil }
        return item.nextGame?.nextGameLabel
    }

    private func open() {
        guard let urlString = item.series.fullSeriesUrl,
              let url = URL(string: urlString) else { return }
        UIApplication.shared.open(url)
    }
}
