//
//  InteractiveCardView.swift
//  Baccarat
//
//  A wrapper around card views that adds interaction logic for Tap and Squeeze reveal styles.
//

import SwiftUI
import CasinoKit

struct InteractiveCardView: View {
    let card: Card
    let isFaceUp: Bool
    let cardWidth: CGFloat
    let revealStyle: RevealStyle
    let isWaiting: Bool
    let progress: Double
    /// Whether this card is in the bottom (Home) hand - used for glow effect
    let isBottomHand: Bool
    let onReveal: () -> Void
    let onUpdateProgress: (Double) -> Void
    
    /// Whether user is currently interacting with the card (peeling)
    @State private var isInteracting = false
    
    /// Whether to show the glowing animation around this card
    /// Only show when waiting, face down, bottom hand, not auto mode, AND not currently being touched
    private var showGlow: Bool {
        isWaiting && !isFaceUp && isBottomHand && revealStyle != .auto && !isInteracting
    }
    
    /// Tracks if we just completed a squeeze reveal (to skip flip animation)
    @State private var squeezeJustCompleted = false
    
    private var cardHeight: CGFloat {
        cardWidth * CasinoDesign.Size.cardAspectRatio
    }
    
    var body: some View {
        ZStack {
            // Glow layer - completely separate from the card, sits underneath
            GlowBackgroundView(
                isActive: showGlow,
                shouldPulse: showGlow,
                cardWidth: cardWidth
            )
            // Force recreation on size change to avoid stale dimensions during rotation
            .id("glow-\(Int(cardWidth))")
            
            // Card layer - completely independent, no glow modifiers
            cardContent
        }
        // Explicit frame ensures card and glow stay synced during size changes
        .frame(width: cardWidth, height: cardHeight)
        .animation(.easeOut(duration: 0.3), value: cardWidth)
        .onChange(of: isWaiting) { _, newValue in
            // Reset interaction state when this card is no longer waiting
            if !newValue {
                isInteracting = false
            }
        }
    }
    
    /// The card content - completely isolated from glow state
    @ViewBuilder
    private var cardContent: some View {
        if revealStyle == .squeeze && !isFaceUp && isWaiting {
            PageCurlView(
                card: card,
                width: cardWidth,
                onReveal: {
                    // Mark that squeeze just completed to skip flip animation
                    squeezeJustCompleted = true
                    onReveal()
                    // Reset after a short delay
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                        squeezeJustCompleted = false
                    }
                }
            )
            // Detect touch to hide glow without interfering with page curl gesture
            .simultaneousGesture(
                DragGesture(minimumDistance: 0)
                    .onChanged { _ in
                        if !isInteracting {
                            isInteracting = true
                        }
                    }
            )
        } else if squeezeJustCompleted && isFaceUp {
            // After squeeze reveal: animate vertical flip to continue upward motion
            VerticalFlipCardView(card: card, cardWidth: cardWidth)
        } else {
            // Standard CardView with flip animation
            CardView(card: card, isFaceUp: isFaceUp, cardWidth: cardWidth)
                .onTapGesture {
                    if !isFaceUp && isWaiting && revealStyle == .tap {
                        // Hide glow immediately before flip starts
                        isInteracting = true
                        onReveal()
                    }
                }
        }
    }
}

// MARK: - Vertical Flip Card View

/// A card view that animates a vertical flip (X-axis rotation) to reveal the card face.
/// Used after the page curl peel completes to smoothly continue the upward flip motion.
private struct VerticalFlipCardView: View {
    let card: Card
    let cardWidth: CGFloat
    
    /// Rotation angle - starts slightly tilted and settles to flat
    /// The page curl ends with the card nearly revealed, so we just do a small settling animation
    @State private var rotationAngle: Double = -15
    
    /// Opacity for smooth fade-in
    @State private var opacity: Double = 0.8
    
    private var cardHeight: CGFloat {
        cardWidth * CasinoDesign.Size.cardAspectRatio
    }
    
    var body: some View {
        CardFrontView(card: card, width: cardWidth, height: cardHeight)
            .rotation3DEffect(
                .degrees(rotationAngle),
                axis: (x: 1, y: 0, z: 0),
                anchor: .bottom,
                perspective: 0.4
            )
            .opacity(opacity)
            .onAppear {
                // Smooth settling animation
                withAnimation(.easeOut(duration: 0.2)) {
                    rotationAngle = 0
                    opacity = 1.0
                }
            }
    }
}

// MARK: - Glow Background View

/// A standalone glow view that sits underneath the card.
/// Completely separate from the card view to avoid any state changes affecting the card.
private struct GlowBackgroundView: View {
    let isActive: Bool
    let shouldPulse: Bool
    let cardWidth: CGFloat
    
    /// Internal animation state - starts false so animation triggers on appear
    @State private var animatingPulse = false
    
    /// Corner radius matching CasinoKit's CardView
    private var cornerRadius: CGFloat {
        cardWidth * 0.08
    }
    
    private var cardHeight: CGFloat {
        cardWidth * CasinoDesign.Size.cardAspectRatio
    }
    
    var body: some View {
        ZStack {
            // Outer glow strokes (largest to smallest for layered glow)
            RoundedRectangle(cornerRadius: cornerRadius)
                .stroke(Color.orange.opacity(animatingPulse ? 0.6 : 0.2), lineWidth: animatingPulse ? 20 : 10)
                .blur(radius: 10)
            
            RoundedRectangle(cornerRadius: cornerRadius)
                .stroke(Color.yellow.opacity(animatingPulse ? 0.8 : 0.3), lineWidth: animatingPulse ? 12 : 6)
                .blur(radius: 6)
            
            RoundedRectangle(cornerRadius: cornerRadius)
                .stroke(Color.yellow.opacity(animatingPulse ? 1.0 : 0.5), lineWidth: animatingPulse ? 6 : 3)
                .blur(radius: 3)
            
            // Bright animated border (sharp, on top)
            RoundedRectangle(cornerRadius: cornerRadius)
                .strokeBorder(
                    LinearGradient(
                        colors: [.yellow, .white, .yellow],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: animatingPulse ? 4 : 3
                )
        }
        .frame(width: cardWidth, height: cardHeight)
        .scaleEffect(isActive && animatingPulse ? 1.02 : 1.0)
        .opacity(isActive ? 1.0 : 0.0)
        .animation(.easeOut(duration: 0.15), value: isActive)
        .animation(
            isActive ? .easeInOut(duration: 0.7).repeatForever(autoreverses: true) : .easeOut(duration: 0.15),
            value: animatingPulse
        )
        .onAppear {
            // Start animation after view appears - this ensures the repeating animation triggers
            if shouldPulse {
                animatingPulse = true
            }
        }
        .onChange(of: shouldPulse) { _, newValue in
            animatingPulse = newValue
        }
    }
}
