import SwiftUI

struct FadingEdgesScrollView<Content: View>: View {
    var content: Content

    @Environment(\.safeAreaInsets) private var safeAreaInsets
    private let topInsetMultiplier: CGFloat = 1.8
    private let compactScreenInsetMultiplier: CGFloat = UIScreen.isCompact ? 2 : 1

    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }

    var body: some View {
        ScrollView {
            Color.clear
                .frame(height: 5) // For spacing at the top of the scroll view
            content
        }
        .mask(
            VStack(spacing: 0) {
                // Top fade (transparent to solid)
                LinearGradient(
                    gradient: Gradient(stops: [
                        .init(color: Color.clear, location: 0),
                        .init(color: Color.black.opacity(0.2), location: 0.7),
                        .init(color: Color.black.opacity(0.3), location: 0.9),
                        .init(color: Color.black, location: 1.0),
                    ]),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .frame(height: safeAreaInsets.top * topInsetMultiplier * compactScreenInsetMultiplier)

                // Middle section (fully visible)
                Rectangle().fill(Color.black)

                LinearGradient(
                    gradient: Gradient(stops: [
                        .init(color: Color.black, location: 0),
                        .init(color: Color.black.opacity(0.6), location: 0.3),
                        .init(color: Color.black.opacity(0.2), location: 0.7),
                        .init(color: Color.clear, location: 1.0),
                    ]),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .frame(height: safeAreaInsets.bottom * compactScreenInsetMultiplier)
            }
            .ignoresSafeArea(.container)
        )
        .contentMargins(.bottom, 100, for: .scrollContent)
        .scrollIndicators(.hidden)
        .scrollClipDisabled(true)
        .scrollDismissesKeyboard(.interactively)
        .scrollBounceBehavior(.basedOnSize)
        .ignoresSafeArea(.container, edges: .bottom)
    }
}
