//
//  MeterChartTabView.swift
//  USB Meter
//

import SwiftUI

struct MeterChartTabView: View {
    @EnvironmentObject private var meter: Meter

    let size: CGSize
    let isLandscape: Bool

    private let pageHorizontalPadding: CGFloat = 12
    private let pageVerticalPadding: CGFloat = 12
    private let portraitContentCardHorizontalPadding: CGFloat = 8
    private let portraitContentCardVerticalPadding: CGFloat = 12

    private var prefersCompactPortraitLayout: Bool {
        size.height < 760 || size.width < 380
    }

    private var prefersCompactLandscapeLayout: Bool {
        size.height < 430
    }

    var body: some View {
        Group {
            if isLandscape {
                landscapeFace {
                    MeasurementChartView(
                        compactLayout: prefersCompactLandscapeLayout,
                        availableSize: size
                    )
                        .environmentObject(meter.measurements)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
                        .padding(10)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
                        .meterCard(tint: meter.color, fillOpacity: 0.12, strokeOpacity: 0.20)
                }
            } else {
                portraitFace {
                    MeasurementChartView(
                        compactLayout: prefersCompactPortraitLayout,
                        availableSize: size
                    )
                        .environmentObject(meter.measurements)
                        .padding(.horizontal, portraitContentCardHorizontalPadding)
                        .padding(.vertical, portraitContentCardVerticalPadding)
                        .meterCard(tint: meter.color, fillOpacity: 0.12, strokeOpacity: 0.20)
                }
            }
        }
    }

    private func portraitFace<Content: View>(@ViewBuilder content: () -> Content) -> some View {
        ScrollView {
            content()
                .frame(maxWidth: .infinity, alignment: .topLeading)
                .padding(.horizontal, pageHorizontalPadding)
                .padding(.vertical, pageVerticalPadding)
        }
    }

    private func landscapeFace<Content: View>(@ViewBuilder content: () -> Content) -> some View {
        content()
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
            .padding(.horizontal, pageHorizontalPadding)
            .padding(.vertical, pageVerticalPadding)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
    }
}
