//
//  AppIconView.swift
//  CasinoKit
//
//  A reusable app icon design that can be customized for different casino games.
//  Render this view to an image for use as your app icon.
//

import SwiftUI

/// Configuration for the app icon appearance.
public struct AppIconConfig: Sendable {
    public let title: String
    public let subtitle: String?
    public let iconSymbol: String
    public let primaryColor: Color
    public let secondaryColor: Color
    public let accentColor: Color
    
    public init(
        title: String,
        subtitle: String? = nil,
        iconSymbol: String,
        primaryColor: Color = Color(red: 0.1, green: 0.2, blue: 0.35),
        secondaryColor: Color = Color(red: 0.05, green: 0.12, blue: 0.25),
        accentColor: Color = .yellow
    ) {
        self.title = title
        self.subtitle = subtitle
        self.iconSymbol = iconSymbol
        self.primaryColor = primaryColor
        self.secondaryColor = secondaryColor
        self.accentColor = accentColor
    }
    
    // MARK: - Example Configuration (for previews only)
    
    /// Example configuration for CasinoKit previews.
    /// Apps should define their own configs in `BrandingConfig.swift`.
    public static let example = AppIconConfig(
        title: "CASINO",
        iconSymbol: "suit.diamond.fill"
    )
}

/// A customizable app icon view for casino games.
/// Render this view to create your app icon assets.
///
/// **Important**: This view generates a full-bleed square icon. iOS applies its own
/// superellipse mask, so decorative borders are inset to avoid clipping at the edges.
public struct AppIconView: View {
    let config: AppIconConfig
    let size: CGFloat
    
    public init(config: AppIconConfig, size: CGFloat = 1024) {
        self.config = config
        self.size = size
    }
    
    // Size calculations
    private var iconSize: CGFloat { size * 0.35 }
    private var subtitleSize: CGFloat { size * 0.25 }
    
    /// Dynamic title size based on text length.
    /// Shorter titles get larger fonts, longer titles shrink to fit within the border.
    private var titleSize: CGFloat {
        let baseSize = size * 0.12
        let length = config.title.count
        
        // Scale factor: full size for ≤6 chars, progressively smaller for longer
        let scaleFactor: CGFloat = switch length {
        case ...6: 1.0        // "CASINO", "POKER"
        case 7: 0.95          // 
        case 8: 0.85          // "BACCARAT"
        case 9: 0.75          // "BLACKJACK"
        default: 0.65         // Very long titles
        }
        
        return baseSize * scaleFactor
    }
    
    public var body: some View {
        ZStack {
            // Background gradient - full bleed, no rounded corners
            // iOS will apply its own superellipse mask
            Rectangle()
                .fill(
                    LinearGradient(
                        colors: [config.primaryColor, config.secondaryColor],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
            
            // Subtle pattern overlay
            DiamondPatternOverlay(size: size)
                .opacity(0.08)
            
            // Content
            VStack(spacing: size * 0.03) {
                // Icon symbol
                Image(systemName: config.iconSymbol)
                    .font(.system(size: iconSize, weight: .bold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [config.accentColor, config.accentColor.opacity(0.8)],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .shadow(color: .black.opacity(0.3), radius: size * 0.02, y: size * 0.01)
                
                // Subtitle (e.g., "21" for Blackjack)
                if let subtitle = config.subtitle {
                    Text(subtitle)
                        .font(.system(size: subtitleSize, weight: .black, design: .rounded))
                        .foregroundStyle(
                            LinearGradient(
                                colors: [config.accentColor, .orange],
                                startPoint: .top,
                                endPoint: .bottom
                            )
                        )
                        .shadow(color: .black.opacity(0.5), radius: size * 0.01)
                }
                
                // Title
                Text(config.title)
                    .font(.system(size: titleSize, weight: .black, design: .rounded))
                    .tracking(size * 0.005)
                    .foregroundStyle(
                        LinearGradient(
                            colors: [.white, .white.opacity(0.85)],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .shadow(color: .black.opacity(0.5), radius: size * 0.01)
            }
        }
        .frame(width: size, height: size)
    }
}

/// Diamond pattern overlay for the icon background.
private struct DiamondPatternOverlay: View {
    let size: CGFloat
    
    private var spacing: CGFloat { size * 0.08 }
    private var diamondSize: CGFloat { size * 0.03 }
    
    var body: some View {
        Canvas { context, canvasSize in
            let rows = Int(canvasSize.height / spacing) + 1
            let cols = Int(canvasSize.width / spacing) + 1
            
            for row in 0..<rows {
                for col in 0..<cols {
                    let offset: CGFloat = row % 2 == 0 ? 0 : spacing / 2
                    let x = CGFloat(col) * spacing + offset
                    let y = CGFloat(row) * spacing
                    
                    let diamond = Path { path in
                        path.move(to: CGPoint(x: x, y: y - diamondSize))
                        path.addLine(to: CGPoint(x: x + diamondSize, y: y))
                        path.addLine(to: CGPoint(x: x, y: y + diamondSize))
                        path.addLine(to: CGPoint(x: x - diamondSize, y: y))
                        path.closeSubpath()
                    }
                    
                    context.fill(diamond, with: .color(.white))
                }
            }
        }
    }
}

// MARK: - Previews

#Preview("App Icon") {
    AppIconView(config: .example, size: 512)
        .clipShape(.rect(cornerRadius: 512 * 0.22))
        .padding()
        .background(Color.gray)
}

#Preview("Title Scaling") {
    let shortTitle = AppIconConfig(title: "POKER", iconSymbol: "suit.diamond.fill")
    let mediumTitle = AppIconConfig(title: "BACCARAT", iconSymbol: "suit.spade.fill")
    let longTitle = AppIconConfig(
        title: "BLACKJACK",
        subtitle: "21",
        iconSymbol: "suit.club.fill",
        primaryColor: Color(red: 0.05, green: 0.35, blue: 0.15),
        secondaryColor: Color(red: 0.03, green: 0.2, blue: 0.1)
    )
    
    return HStack(spacing: 20) {
        VStack {
            AppIconView(config: shortTitle, size: 180)
                .clipShape(.rect(cornerRadius: 180 * 0.22))
            Text("6 chars").font(.caption)
        }
        VStack {
            AppIconView(config: mediumTitle, size: 180)
                .clipShape(.rect(cornerRadius: 180 * 0.22))
            Text("8 chars").font(.caption)
        }
        VStack {
            AppIconView(config: longTitle, size: 180)
                .clipShape(.rect(cornerRadius: 180 * 0.22))
            Text("9 chars").font(.caption)
        }
    }
    .padding()
    .background(Color.gray)
}

#Preview("All Sizes") {
    LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))], spacing: 20) {
        ForEach([180, 120, 87, 60, 40], id: \.self) { size in
            VStack {
                AppIconView(config: .example, size: CGFloat(size))
                    .clipShape(.rect(cornerRadius: CGFloat(size) * 0.22))
                Text("\(size)px").font(.caption)
            }
        }
    }
    .padding()
    .background(Color.gray)
}

