
import SwiftUI

struct BottomSheetView<Content: View>: View {
    @Binding var isShowing: Bool
    var opacified: Bool
    var dismissable: Bool
    let content: Content
    
    init(isShowing: Binding<Bool>, opacified: Bool = false, dismissable: Bool, @ViewBuilder content: () -> Content) {
        self._isShowing = isShowing
        self.opacified = opacified
        self.dismissable = dismissable
        self.content = content()
    }
    
    var body: some View {
        ZStack(alignment: .bottom) {
            if isShowing {
                Color.black.opacity(opacified ? 0.3 : 0)
                    .ignoresSafeArea()
                    .onTapGesture {
                        if dismissable {
                            withAnimation { isShowing = false }
                        }
                    }
                
                content
                    .padding()
                    .background(Color.white)
                    .cornerRadius(16, corners: [.topLeft, .topRight])
                    .frame(maxWidth: .infinity)
                    .transition(.move(edge: .bottom).combined(with: .opacity))
                    .ignoresSafeArea()
            }
        }
        .animation(.easeInOut, value: isShowing)
    }
}

struct BottomSheetModifier<SheetContent: View>: ViewModifier {
    @Binding var isShowing: Bool
    var opacified: Bool
    var dismissable: Bool
    let sheetContent: () -> SheetContent
    
    func body(content: Content) -> some View {
        ZStack {
            content
            
            if isShowing {
                BottomSheetView(isShowing: $isShowing, opacified: opacified, dismissable: dismissable, content: sheetContent)
                    .ignoresSafeArea()
            }
        }
    }
}

extension View {
    func bottomSheet<SheetContent: View>(isShowing: Binding<Bool>, opacified: Bool = true, dismissable: Bool = true, @ViewBuilder content: @escaping () -> SheetContent) -> some View {
        self.modifier(BottomSheetModifier(isShowing: isShowing, opacified: opacified, dismissable: dismissable, sheetContent: content))
    }
}

#Preview {
    BoosterSubscriptionManagementScreen()
}
