//
//  StoreItemCard.swift
//  lichunWebsocket
//
//  Card component for displaying store items with purchase functionality
//

import SwiftUI
import SDWebImageSwiftUI

struct StoreItemCard: View {
    @EnvironmentObject var webSocketService: WebSocketService
    var item: StoreItem

    @State private var animateButton = false

    var isOwned: Bool {
        webSocketService.person.items.contains { $0.id == item.id }
    }

    var canAfford: Bool {
        webSocketService.person.money >= item.price
    }

    var body: some View {
        VStack(spacing: AppSpacing.md) {
            // Item Image with cozy backdrop
            ZStack {
                RoundedRectangle(cornerRadius: 16)
                    .fill(
                        LinearGradient(
                            colors: [AppColors.intelligence.opacity(0.16), AppColors.accent.opacity(0.16)],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(height: 120)

                if let imageUrl = item.image, let url = URL(string: imageUrl) {
                    WebImage(url: url)
                        .onSuccess { image, data, cacheType in
                            print("🛍️ ItemImage: ✅ Loaded '\(item.name)' - size: \(image.size), cache: \(cacheType)")
                        }
                        .onFailure { error in
                            print("🛍️ ItemImage: ❌ Failed '\(item.name)' - URL: \(imageUrl) - Error: \(error.localizedDescription)")
                        }
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(height: 100)
                        .onAppear {
                            print("🛍️ ItemImage: 🔄 Loading '\(item.name)' from: \(imageUrl)")
                        }
                } else {
                    // Log missing image
                    Color.clear
                        .frame(height: 100)
                        .onAppear {
                            print("🛍️ ItemImage: ⚠️ No image URL for item '\(item.name)' (id: \(item.id))")
                        }
                }
            }

            VStack(spacing: AppSpacing.xs) {
                // Item Name
                Text(item.name)
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)
                    .multilineTextAlignment(.center)

                // Item Price with icon
                HStack(spacing: 4) {
                    Image(systemName: "dollarsign.circle.fill")
                        .font(.system(size: 14))
                        .foregroundColor(priceColor)
                    Text("\(item.price)")
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                        .foregroundColor(priceColor)
                }
            }

            // Purchase Button with gradient
            Button(action: purchaseItem) {
                Text(isOwned ? "Owned" : "Get Item")
                    .font(.appBodyBold)
                    .padding(.vertical, AppSpacing.sm)
                    .frame(maxWidth: .infinity)
                    .background(buttonBackground)
                    .foregroundColor(.white)
                    .cornerRadius(AppSpacing.pillCornerRadius)
                    .scaleEffect(animateButton ? 0.95 : 1)
                    .shadow(
                        color: buttonShadowColor,
                        radius: 8,
                        x: 0,
                        y: 4
                    )
            }
            .disabled(isOwned || !canAfford)
            // INTEGRATION: Haptic feedback on purchase
            .hapticOnTap(style: .medium)
        }
        .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.9, green: 0.7, blue: 1.0).opacity(0.3), Color(red: 1.0, green: 0.9, blue: 0.7).opacity(0.3)],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: 1
                )
        )
    }

    // MARK: - Computed Properties
    private var priceColor: Color {
        if isOwned {
            return AppColors.success
        } else if canAfford {
            return Color(red: 0.9, green: 0.7, blue: 0.4) // Warm gold
        } else {
            return AppColors.secondaryText
        }
    }

    private var buttonBackground: LinearGradient {
        if isOwned {
            return LinearGradient(
                colors: [AppColors.success, AppColors.success.opacity(0.8)],
                startPoint: .leading,
                endPoint: .trailing
            )
        } else if canAfford {
            return LinearGradient(
                colors: [Color(red: 0.8, green: 0.6, blue: 0.9), Color(red: 0.9, green: 0.7, blue: 0.4)],
                startPoint: .leading,
                endPoint: .trailing
            )
        } else {
            return LinearGradient(
                colors: [Color.gray, Color.gray],
                startPoint: .leading,
                endPoint: .trailing
            )
        }
    }

    private var buttonShadowColor: Color {
        if isOwned || !canAfford {
            return Color.clear
        }
        return Color(red: 0.8, green: 0.6, blue: 0.9).opacity(0.4)
    }

    // MARK: - Actions
    private func purchaseItem() {
        guard !isOwned && canAfford else { return }

        // INTEGRATION: Play purchase sound
        SoundManager.shared.playSound(.purchase)

        // Track purchase initiation
        AnalyticsManager.shared.track(.purchaseInitiated(
            itemId: item.id,
            itemName: item.name,
            price: item.price
        ))

        // Animate button
        withAnimation(.spring()) {
            animateButton = true
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            withAnimation(.spring()) {
                animateButton = false
            }
        }

        let message = WebSocketCommands.purchaseItem(item.id)
        webSocketService.sendMessage(message: message)
    }
}

// Backward compatibility alias
typealias StoreItemView = StoreItemCard

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