import SwiftUI
import SDWebImageSwiftUI

public struct PopupPromotion: View {
    var imageUrl: String
    var onIconClose: (() -> Void)?
    var onAction: (() -> Void)?


    public init(
        imageUrl: String,
        onIconClose: (() -> Void)? = nil,
        onAction: (() -> Void)? = nil
    ) {
        self.imageUrl = imageUrl
        self.onIconClose = onIconClose
        self.onAction = onAction
    }

    public var body: some View {
        VStack(spacing: 8) {
            if(imageUrl.isEmpty) {
                Icon(source: "media_fail", size: UIScreen.main.bounds.width - Spacing.XL * 2)
            }
            else {
                WebImage(url: URL(string: imageUrl)!)
                    .resizable()
                    .placeholder {
                        Color.gray
                            .aspectRatio(0.72, contentMode: .fit)
                            .frame(maxWidth: UIScreen.main.bounds.width - Spacing.XL * 2)
                            .clipped()
                    }
                    .aspectRatio(0.72, contentMode: .fit)
                    .frame(maxWidth: UIScreen.main.bounds.width - Spacing.XL * 2, alignment: .center)
                    .clipped()
                    .onTapGesture {
                        onAction?()
                    }
            }
            buildCloseIcon()
                .accessibility(identifier: "ic_popup_close")
        }
        .accessibilityElement(children: .ignore)
        .accessibility(identifier: "popup_promotion")
    }

    @ViewBuilder
    private func buildCloseIcon() -> some View {
        HStack(alignment: .center, spacing: 0) {
            SwiftUI.Button(action: {
                onIconClose?()
            }) {
                ZStack {
                    Circle()
                        .strokeBorder(Colors.black01, lineWidth: 2)
                        .background(Circle().fill(Colors.black17))
                        .frame(width: 22, height: 22)

                    Icon(source: "navigation_close", size: 16,  color: Colors.black01)
                }
                .frame(width: 40, height: 40)
                .padding(8)
                .zIndex(1)
            }
        }
    }

}



