//
//  ProductGridView.swift
//  lichunWebsocket
//
//  In-app purchase grid view with diamond animation
//

import SwiftUI
import SDWebImageSwiftUI

// MARK: - Falling Diamond Animation
struct FallingDiamond: View {
    @State private var isAnimating = false
    var offset: CGSize

    var body: some View {
        Text("💎")
            .font(.largeTitle)
            .offset(x: offset.width, y: isAnimating ? UIScreen.main.bounds.height + offset.height : -100)
            .animation(.linear(duration: 3).repeatForever(autoreverses: false), value: isAnimating)
            .onAppear {
                self.isAnimating = true
            }
    }
}

// MARK: - Product Grid View
struct ProductGridView: View {
    @EnvironmentObject var storeManager: StoreManager
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var showAnimation = false
    @State private var diamondCount = 0
    var columns: [GridItem] = Array(repeating: .init(.flexible()), count: 2)

    var body: some View {
        ZStack {
            // Full-bleed cozy background so the sheet is never white-on-white in
            // dark mode (presented inside an enclosing NavigationView).
            AppColors.background.ignoresSafeArea()

            ScrollView {
                VStack(spacing: AppSpacing.lg) {
                    // Cozy header with diamond icon
                    VStack(spacing: AppSpacing.sm) {
                        ZStack {
                            Circle()
                                .fill(
                                    LinearGradient(
                                        colors: [Color(red: 0.4, green: 0.8, blue: 1.0), Color(red: 0.6, green: 0.4, blue: 1.0)],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                )
                                .frame(width: 80, height: 80)
                                .shadow(color: Color(red: 0.5, green: 0.6, blue: 1.0).opacity(0.4), radius: 12, x: 0, y: 6)

                            Image(systemName: "gem.fill")
                                .font(.system(size: 40))
                                .foregroundColor(.white)
                        }

                        Text("Diamonds")
                            .font(.appTitle)
                            .foregroundStyle(AppColors.primaryText)

                        Text("Premium currency for special features")
                            .font(.appBody)
                            .foregroundColor(AppColors.secondaryText)
                            .multilineTextAlignment(.center)
                    }
                    .padding(.top, AppSpacing.md)

                    LazyVGrid(columns: columns, spacing: AppSpacing.md) {
                        ForEach(webSocketService.player.inAppPurchases) { item in
                            VStack(spacing: AppSpacing.md) {
                                // Diamond icon with quantity
                                ZStack {
                                    RoundedRectangle(cornerRadius: 20)
                                        .fill(
                                            LinearGradient(
                                                colors: [AppColors.diamond.opacity(0.18), AppColors.intelligence.opacity(0.18)],
                                                startPoint: .topLeading,
                                                endPoint: .bottomTrailing
                                            )
                                        )
                                        .frame(height: 120)

                                    VStack(spacing: AppSpacing.xs) {
                                        WebImage(url: URL(string: item.image))
                                            .resizable()
                                            .aspectRatio(contentMode: .fill)
                                            .frame(width: 60, height: 60)

                                        Text("\(item.diamonds)")
                                            .font(.system(size: 22, weight: .bold, design: .rounded))
                                            .foregroundColor(AppColors.diamond)
                                    }
                                }

                                VStack(spacing: AppSpacing.xs) {
                                    Text(item.name)
                                        .font(.appHeadline)
                                        .foregroundColor(AppColors.primaryText)

                                    Text(item.description)
                                        .font(.appCaption)
                                        .foregroundColor(AppColors.secondaryText)
                                        .multilineTextAlignment(.center)
                                        .lineLimit(2)
                                }

                                // Price button with premium gradient
                                Button {
                                    webSocketService.sendMessage(message: WebSocketCommands.purchaseInAppItem(productId: item.id))

                                    // Start the diamond animation
                                    self.diamondCount = item.diamonds
                                    self.showAnimation = true

                                    // Stop the animation after 3 seconds
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                                        self.showAnimation = false
                                    }
                                } label: {
                                    Text("$\(item.price, specifier: "%.2f")")
                                        .font(.system(size: 18, weight: .bold, design: .rounded))
                                        .foregroundColor(.white)
                                        .frame(maxWidth: .infinity)
                                        .padding(.vertical, AppSpacing.sm)
                                        .background(
                                            LinearGradient(
                                                colors: [Color(red: 0.4, green: 0.8, blue: 1.0), Color(red: 0.6, green: 0.4, blue: 1.0)],
                                                startPoint: .leading,
                                                endPoint: .trailing
                                            )
                                        )
                                        .cornerRadius(AppSpacing.pillCornerRadius)
                                        .shadow(
                                            color: Color(red: 0.5, green: 0.6, blue: 1.0).opacity(0.4),
                                            radius: 8,
                                            x: 0,
                                            y: 4
                                        )
                                }
                            }
                            .padding(AppSpacing.md)
                            .background(AppColors.surfaceElevated)
                            .cornerRadius(20)
                            .shadow(color: Color.black.opacity(0.08), radius: 10, x: 0, y: 4)
                            .overlay(
                                RoundedRectangle(cornerRadius: 20)
                                    .stroke(
                                        LinearGradient(
                                            colors: [Color(red: 0.7, green: 0.9, blue: 1.0).opacity(0.3), Color(red: 0.8, green: 0.7, blue: 1.0).opacity(0.3)],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ),
                                        lineWidth: 1
                                    )
                            )
                        }
                    }
                    .padding(.horizontal, AppSpacing.md)
                }
            }
            .background(AppColors.primaryBackground)

            if showAnimation {
                VStack {
                    Text("Congratulations!")
                    Text("You have received \(diamondCount) diamonds!")
                    ForEach(0..<20) { _ in
                        FallingDiamond(offset: .init(
                            width: Double.random(in: -150...150),
                            height: Double.random(in: -150...150)
                        ))
                    }
                }
                .font(.largeTitle)
                .foregroundColor(.blue)
            }
        }
    }
}

// MARK: - Preview
// Preview removed - requires backend connection
