import SwiftUI

// MARK: - Hero stat card
//
// Full-bleed colored card with one big number + label + optional
// subtitle. The variant determines the background treatment (orange,
// navy, gold, or a photo). Shared by HistoryView, PassportView,
// AircraftStatsView, and YearInReviewView so cards feel consistent
// wherever they appear.

struct HeroStatCard<Footer: View>: View {
    let label: String
    let value: String
    let subtitle: String?
    let variant: Variant
    let onForeground: Color
    @ViewBuilder var footer: () -> Footer

    enum Variant {
        case orange
        case navy
        case gold
        case green
        case photo(URL?)
    }

    init(
        label: String,
        value: String,
        subtitle: String? = nil,
        variant: Variant,
        onForeground: Color = .white,
        @ViewBuilder footer: @escaping () -> Footer = { EmptyView() }
    ) {
        self.label = label
        self.value = value
        self.subtitle = subtitle
        self.variant = variant
        self.onForeground = onForeground
        self.footer = footer
    }

    var body: some View {
        ZStack(alignment: .topLeading) {
            background
            VStack(alignment: .leading, spacing: 8) {
                Text(label)
                    .font(HistoryStyle.label(11))
                    .tracking(1.6)
                    .textCase(.uppercase)
                    .foregroundStyle(onForeground.opacity(0.7))

                Text(value)
                    .font(HistoryStyle.displayNumber(46))
                    .foregroundStyle(onForeground)
                    .lineLimit(1)
                    .minimumScaleFactor(0.55)

                if let subtitle {
                    Text(subtitle)
                        .font(.system(size: 14, weight: .medium))
                        .foregroundStyle(onForeground.opacity(0.82))
                }
                Spacer(minLength: 0)
                footer()
            }
            .padding(20)
        }
        .frame(minHeight: 152)
        .clipShape(RoundedRectangle(cornerRadius: 22))
    }

    @ViewBuilder
    private var background: some View {
        switch variant {
        case .orange:
            HistoryStyle.heroOrangeGradient
        case .navy:
            HistoryStyle.heroNavyGradient
        case .gold:
            HistoryStyle.heroGoldGradient
        case .green:
            HistoryStyle.heroGreenGradient
        case .photo(let url):
            ZStack {
                Color.black
                if let url {
                    AsyncImage(url: url) { phase in
                        switch phase {
                        case .success(let img):
                            img.resizable().aspectRatio(contentMode: .fill)
                        default:
                            Color.black.opacity(0.6)
                        }
                    }
                }
                LinearGradient(
                    colors: [Color.black.opacity(0.0), Color.black.opacity(0.85)],
                    startPoint: .top, endPoint: .bottom
                )
            }
        }
    }
}

// MARK: - Year tab strip
//
// Horizontal scroll of `ALL · 2026 · 2025 · 2024 ...`. Tapping a year
// updates a binding the parent view filters against. Active year is
// pill-highlighted in runway orange.

struct YearTabStrip: View {
    let years: [Int]
    @Binding var selection: Int?
    @Environment(\.colorScheme) private var scheme

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            ScrollViewReader { proxy in
                HStack(spacing: 8) {
                    tab(label: "ALL", id: -1, selected: selection == nil) {
                        selection = nil
                    }
                    .id("ALL")
                    ForEach(years, id: \.self) { y in
                        tab(label: String(y), id: y, selected: selection == y) {
                            selection = y
                        }
                        .id(y)
                    }
                }
                .padding(.horizontal, 16)
                .onAppear {
                    if let sel = selection {
                        withAnimation { proxy.scrollTo(sel, anchor: .center) }
                    }
                }
            }
        }
    }

    private func tab(label: String, id: Int, selected: Bool, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Text(label)
                .font(.system(size: 13, weight: .bold).monospacedDigit())
                .tracking(0.6)
                .foregroundStyle(selected ? .white : HistoryStyle.inkSecondary(scheme))
                .padding(.horizontal, 14)
                .padding(.vertical, 8)
                .background(
                    Capsule()
                        .fill(selected ? HistoryStyle.runwayOrange : HistoryStyle.card(scheme))
                )
        }
        .buttonStyle(.plain)
    }
}

// MARK: - Passport stamp badge
//
// Faux rubber-stamp circular badge used on cards to add flavor (e.g.
// "VERIFIED", date stamps).

struct PassportStamp: View {
    let text: String
    let color: Color

    var body: some View {
        Circle()
            .stroke(color, lineWidth: 1.2)
            .frame(width: 56, height: 56)
            .overlay(
                Text(text)
                    .font(.system(size: 10, weight: .black))
                    .tracking(1.5)
                    .foregroundStyle(color)
                    .multilineTextAlignment(.center)
                    .padding(6)
            )
            .rotationEffect(.degrees(-6))
            .opacity(0.85)
    }
}

// MARK: - OCR-passport flex footer
//
// The deeply unserious passport-bottom OCR text Flighty uses. We
// generate ours from the user's display name + a synthetic issue
// date. Pure flavor, fully optional.

struct OCRPassportFooter: View {
    let owner: String      // "TARTT, GARY"
    let issued: Date

    @Environment(\.colorScheme) private var scheme

    var body: some View {
        VStack(spacing: 2) {
            line(prefix: "P<USA<",  trailing: nameLine)
            line(prefix: "ISSUED<", trailing: tailLine)
        }
        .font(HistoryStyle.ocrFont)
        .foregroundStyle(HistoryStyle.inkSecondary(scheme).opacity(0.9))
        .padding(.vertical, 12)
        .padding(.horizontal, 14)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(
            RoundedRectangle(cornerRadius: 8)
                .stroke(HistoryStyle.inkSecondary(scheme).opacity(0.3), style: .init(lineWidth: 0.5, dash: [3, 3]))
        )
    }

    private func line(prefix: String, trailing: String) -> some View {
        HStack(spacing: 0) {
            Text(prefix + trailing)
                .lineLimit(1)
                .truncationMode(.tail)
            Spacer(minLength: 0)
        }
    }

    private var nameLine: String {
        let upper = owner.uppercased()
        let padded = (upper + String(repeating: "<", count: 40))
        return String(padded.prefix(40)) + "<<<<<<<<"
    }

    private var tailLine: String {
        let f = DateFormatter()
        f.dateFormat = "ddMMMyy"
        f.locale = Locale(identifier: "en_US_POSIX")
        let date = f.string(from: issued).uppercased()
        return date + "<<MEMBER<<@FLIGHTAPP.COM<<<<<<<<<<<<<<<<<<<<<<"
    }
}

// MARK: - Big stat numbers row

struct StatColumn: View {
    let label: String
    let value: String
    var subtitle: String? = nil
    @Environment(\.colorScheme) private var scheme

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(label)
                .font(HistoryStyle.label(10))
                .tracking(1.3)
                .textCase(.uppercase)
                .foregroundStyle(HistoryStyle.inkSecondary(scheme))
            Text(value)
                .font(HistoryStyle.displayNumber(28))
                .foregroundStyle(HistoryStyle.ink(scheme))
            if let subtitle {
                Text(subtitle)
                    .font(.system(size: 11))
                    .foregroundStyle(HistoryStyle.inkTertiary(scheme))
            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}

// MARK: - Section header

struct HistorySectionLabel: View {
    let text: String
    @Environment(\.colorScheme) private var scheme

    init(_ text: String) { self.text = text }

    var body: some View {
        Text(text)
            .font(HistoryStyle.label(11))
            .tracking(1.6)
            .textCase(.uppercase)
            .foregroundStyle(HistoryStyle.inkTertiary(scheme))
    }
}
