import APIClient
import SwiftUI
import ComponentLibrary

struct CustomChatView: View {
    @Binding var text: String
    @Binding var isEditingLyrics: Bool
    @Binding var isInExtendMode: Bool
    let currentlySelectedSong: Song?
    let currentLyrics: String? // Add currentLyrics parameter
    let billingInfo: SubscriptionInfoResponse? // Add billingInfo for credits display
    let audioManager: AudioManager
    let onSendTap: () -> Void
    let onDismiss: () -> Void
    
    @State private var lyricsText: String = ""
    @State private var styleText: String = ""
    @State private var extensionTime: String = "0:30s"
    @State private var modelVersion: String = "v4.5"
    @State private var isKeyboardVisible: Bool = false

    // Advanced options state
    @State private var weirdnessValue: Double = 0.5
    @State private var styleInfluenceValue: Double = 0.5
    @State private var audioInfluenceValue: Double = 0.5
    @State private var vocalGender: String = "Female"

    var body: some View {
        GeometryReader { geometry in
            ZStack {
                VStack(spacing: 0) {
                    ScrollViewWithSheetSupport {
                        VStack(spacing: 16) {
                            // Audio Player (when there's a selected song)
                            if let selectedSong = currentlySelectedSong {
                                CreateAudioPlayer(
                                    songTitle: selectedSong.title,
                                    artworkGradient: createGradientForSong(selectedSong),
                                    isPlaying: audioManager.currentlyPlayingSongId == selectedSong.id,
                                    onPlayPause: {
                                        audioManager.togglePlayback(songId: selectedSong.id, audioURL: selectedSong.audioURL)
                                    },
                                    audioManager: audioManager
                                )
                            }

                            // Lyrics Description Component
                            LyricsDescription(
                                lyricsText: $lyricsText,
                                startExpanded: true,
                                placeholderText: isInExtendMode ? 
                                    "Continue the song — what lyrics come after \(extensionTime)" :
                                    (isEditingLyrics ? "Write your song lyrics here..." : "Write lyrics or prompt"),
                                onSaveLyrics: { currentLyricsText in
                                    print("Save lyrics: \(currentLyricsText)")
                                },
                                showOnlyUndo: false,
                                hideFooterControls: false,
                                customHeight: isEditingLyrics ? 340 : nil
                            )

                            // Style Description Component (collapsed in lyrics focus mode)
                            StyleDescription(
                                styleText: $styleText,
                                modelVersion: modelVersion,
                                startExpanded: !isEditingLyrics
                            ) { currentStyleText in
                                print("Save style: \(currentStyleText)")
                            }

                            // Advanced Options Component
                            AdvancedOptions(
                                weirdnessValue: $weirdnessValue,
                                styleInfluenceValue: $styleInfluenceValue,
                                audioInfluenceValue: $audioInfluenceValue,
                                vocalGender: $vocalGender
                            )

                            // Extra padding at bottom for floating elements in both modes
                            Spacer()
                                .frame(height: 120)

                            // Extra padding at bottom for floating elements
                            Spacer()
                                .frame(height: 40)
                        }
                        .padding(16)
                    }
                }
            }
        }
        .background(ChatConstants.Colors.Background.primary)
        .onAppear {
            setupKeyboardObservers()
            populateFromSelectedSong()
        }
        .onChange(of: currentlySelectedSong?.id) { _, _ in
            populateFromSelectedSong()
        }
        .onChange(of: currentLyrics) { _, _ in
            populateFromSelectedSong()
        }
    }
    
    private func setupKeyboardObservers() {
        NotificationCenter.default.addObserver(
            forName: UIResponder.keyboardWillShowNotification,
            object: nil,
            queue: .main
        ) { _ in
            withAnimation(.easeInOut(duration: 0.3)) {
                isKeyboardVisible = true
            }
        }
        
        NotificationCenter.default.addObserver(
            forName: UIResponder.keyboardWillHideNotification,
            object: nil,
            queue: .main
        ) { _ in
            withAnimation(.easeInOut(duration: 0.3)) {
                isKeyboardVisible = false
            }
        }
    }
    
    private func populateFromSelectedSong() {
        // Populate lyrics from currentLyrics if available
        if let lyrics = currentLyrics, lyricsText.isEmpty {
//            lyricsText = lyrics.sections.map { section in
//                "[\(section.type)]\n\(section.content)"
//            }.joined(separator: "\n\n")
            lyricsText = lyrics
        }
        
        // Populate style from selected song's genres if available
        if let song = currentlySelectedSong, styleText.isEmpty {
            styleText = song.genres.joined(separator: ", ")
        }
    }
}

struct CustomHeader: View {
    let title: String
    let onModelVersionChanged: (String) -> Void
    let billingInfo: SubscriptionInfoResponse? // Add billingInfo parameter
    
    @State private var selectedModel = "v4.5"
    private let modelOptions = ["v3.5", "v4.0", "v4.5"]
    
    init(title: String, billingInfo: SubscriptionInfoResponse?, onModelVersionChanged: @escaping (String) -> Void) {
        self.title = title
        self.billingInfo = billingInfo
        self.onModelVersionChanged = onModelVersionChanged
    }
    
    var body: some View {
        HStack {
            // Left Section - Title and Credits (matching reference)
            VStack(alignment: .leading, spacing: 2) {
                // Custom Title
                Text(title)
                    .figmaMCPTypography(TypographyV1.FigmaMCP.mediumRegular)
                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                    .tracking(0.36)
                
                // Credits Display - using billingInfo from shared state
                if let billingInfo = billingInfo {
                    Text("\(billingInfo.totalCreditsLeft) credits")
                        .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallTitle)
                        .foregroundColor(ChatConstants.Colors.Foreground.tertiary)
                        .tracking(0.2)
                }
            }
            
            Spacer()
            
            // Right Section - Model Version Picker (matching reference)
            Menu {
                Button {
                    selectedModel = "v4.5"
                    onModelVersionChanged("v4.5")
                } label: {
                    HStack {
                        Text("v4.5")
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        Spacer()
                        if selectedModel == "v4.5" {
                            Image(systemName: "checkmark")
                                .foregroundColor(ChatConstants.Colors.Accent.brand)
                                .font(.system(size: 14, weight: .medium))
                        }
                    }
                }
                
                Button {
                    selectedModel = "v4.0"
                    onModelVersionChanged("v4.0")
                } label: {
                    HStack {
                        Text("v4.0")
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        Spacer()
                        if selectedModel == "v4.0" {
                            Image(systemName: "checkmark")
                                .foregroundColor(ChatConstants.Colors.Accent.brand)
                                .font(.system(size: 14, weight: .medium))
                        }
                    }
                }
                
                Button {
                    selectedModel = "v3.5"
                    onModelVersionChanged("v3.5")
                } label: {
                    HStack {
                        Text("v3.5")
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        Spacer()
                        if selectedModel == "v3.5" {
                            Image(systemName: "checkmark")
                                .foregroundColor(ChatConstants.Colors.Accent.brand)
                                .font(.system(size: 14, weight: .medium))
                        }
                    }
                }
            } label: {
                HStack(spacing: 4) {
                    Text(selectedModel)
                        .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallTitle)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        .tracking(0.24)
                    
                    Image.FigmaMCP.triangleDown
                        .resizable()
                        .renderingMode(.template)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 16, height: 16)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                }
                .frame(height: 40)
                .padding(.horizontal, 16)
                .background(
                    RoundedRectangle(cornerRadius: 100)
                        .stroke(Color.white.opacity(0.1), lineWidth: 1)
                )
            }
            .buttonStyle(PlainButtonStyle())
            .preferredColorScheme(.dark)
        }
        .padding(.leading, 24)
        .padding(.trailing, 16)
        .padding(.top, 24)
    }
}

struct ActionsComponent: View {
    var body: some View {
        HStack(spacing: 1) { // gap-px = 1px between buttons
            // Audio Button with Menu
            ActionButtonWithMenu(
                title: "Audio",
                iconName: "Icon/plus",
                menuItems: [
                    ("Upload", "Icon/upload", { print("Upload selected") }),
                    ("Record", "Icon/microphone", { print("Record selected") }),
                    ("Library", "Icon/library", { print("Library selected") })
                ]
            )
            
            // Voice Button
            ActionButton(
                title: "Voice",
                action: { print("Voice selected") }
            )
        }
        .clipShape(RoundedRectangle(cornerRadius: 16)) // rounded-2xl = 16px
    }
}

struct ActionButton: View {
    let title: String
    let badgeText: String?
    let iconName: String
    let action: () -> Void
    
    init(title: String, badgeText: String? = nil, iconName: String = "Icon/plus", action: @escaping () -> Void) {
        self.title = title
        self.badgeText = badgeText
        self.iconName = iconName
        self.action = action
    }
    
    var body: some View {
        Button(action: action) {
            HStack(spacing: 8) { // gap-2 = 8px
                // Icon - using FigmaMCP icons
                Image.FigmaMCP.plus
                    .resizable()
                    .renderingMode(.template)
                    .frame(width: 16, height: 16)
                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                
                // Button Text - using FigmaMCP typography
                Text(title)
                    .figmaMCPTypography(TypographyV1.FigmaMCP.small)
                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                    .lineLimit(1)
            }
            .frame(maxWidth: .infinity)
            .frame(height: 48)
            .background(
                Color.white.opacity(0.04) // Background/Fog/Thin: #ffffff0a
            )
        }
        .buttonStyle(ActionButtonStyle())
    }
}

struct ActionButtonWithMenu: View {
    let title: String
    let iconName: String
    let menuItems: [(String, String, () -> Void)] // (title, iconName, action)
    
    init(title: String, iconName: String = "Icon/plus", menuItems: [(String, String, () -> Void)]) {
        self.title = title
        self.iconName = iconName
        self.menuItems = menuItems
    }
    
    var body: some View {
        Menu {
            ForEach(0..<menuItems.count, id: \.self) { index in
                let item = menuItems[index]
                Button {
                    item.2() // action
                } label: {
                    HStack(spacing: 8) {
                        // Map icon names to FigmaMCP icons
                        let icon = iconForName(item.1)
                        icon
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 16, height: 16)
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        
                        Text(item.0) // title
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        
                        Spacer()
                    }
                }
            }
        } label: {
            HStack(spacing: 8) {
                // Icon - using FigmaMCP icons
                Image.FigmaMCP.plus
                    .resizable()
                    .renderingMode(.template)
                    .frame(width: 16, height: 16)
                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                
                // Button Text - using FigmaMCP typography
                Text(title)
                    .figmaMCPTypography(TypographyV1.FigmaMCP.small)
                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                    .lineLimit(1)
            }
            .frame(maxWidth: .infinity)
            .frame(height: 48)
            .background(
                Color.white.opacity(0.04) // Background/Fog/Thin: #ffffff0a
            )
        }
        .preferredColorScheme(.dark)
        .buttonStyle(ActionButtonStyle())
    }
    
    // Helper to map icon names to FigmaMCP icons
    private func iconForName(_ name: String) -> Image {
        switch name {
        case "Icon/upload":
            return Image.FigmaMCP.upload
        case "Icon/microphone":
            return Image.FigmaMCP.microphone
        case "Icon/library":
            return Image.FigmaMCP.library
        default:
            return Image.FigmaMCP.plus
        }
    }
}

// Custom button style for press effects
struct ActionButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.98 : 1.0)
            .opacity(configuration.isPressed ? 0.8 : 1.0)
            .animation(.easeInOut(duration: 0.1), value: configuration.isPressed)
    }
}

struct ExtendPlayerView: View {
    let song: Song
    let audioManager: AudioManager
    @Binding var extensionTime: String
    
    private let extensionOptions = ["0:15s", "0:30s", "1:00s", "1:30s"]
    
    var body: some View {
        VStack(spacing: 16) {
            // Song artwork and info
            HStack(spacing: 16) {
                RoundedRectangle(cornerRadius: 12)
                    .fill(createGradientForSong(song))
                    .frame(width: 60, height: 60)
                    .overlay {
                        Button {
                            audioManager.togglePlayback(songId: song.id, audioURL: song.audioURL)
                        } label: {
                            if audioManager.currentlyPlayingSongId == song.id && audioManager.isCurrentlyPlaying {
                                Image.FigmaMCP.pause
                                    .resizable()
                                    .renderingMode(.template)
                                    .frame(width: 24, height: 24)
                                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                            } else {
                                Image.FigmaMCP.play
                                    .resizable()
                                    .renderingMode(.template)
                                    .frame(width: 24, height: 24)
                                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                            }
                        }
                    }
                
                VStack(alignment: .leading) {
                    Text(song.title)
                        .figmaMCPTypography(TypographyV1.FigmaMCP.headingH4)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                    Text(song.genres.joined(separator: " • "))
                        .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                        .foregroundColor(ChatConstants.Colors.Foreground.secondary.opacity(0.7))
                }
                
                Spacer()
            }
            
            // Extension time picker
            HStack {
                Text("Extend by:")
                    .figmaMCPTypography(TypographyV1.FigmaMCP.small)
                    .foregroundColor(ChatConstants.Colors.Foreground.primary)
                
                Menu(extensionTime) {
                    ForEach(extensionOptions, id: \.self) { option in
                        Button(option) {
                            extensionTime = option
                        }
                    }
                }
                .foregroundColor(ChatConstants.Colors.Accent.brand)

                Spacer()
            }
        }
        .padding(16)
        .background(ChatConstants.Palette.Dumbo._200.opacity(0.3))
        .cornerRadius(16)
        .padding(.horizontal, 16)
    }
}

struct LyricsDescription: View {
    @Binding var lyricsText: String
    @FocusState private var isTextFieldFocused: Bool
    let startExpanded: Bool
    let placeholderText: String
    let onSaveLyrics: ((String) -> Void)?
    let showOnlyUndo: Bool
    let hideFooterControls: Bool
    let customHeight: CGFloat?
    
    @State private var isExpanded: Bool
    
    // Character limit
    private let characterLimit: Int = 5000
    
    // Show warning threshold (90% of limit)
    private var warningThreshold: Int {
        Int(Double(characterLimit) * 0.9)
    }
    
    // Computed property to determine if we're in typing mode
    private var isTypingMode: Bool {
        !lyricsText.isEmpty
    }
    
    init(
        lyricsText: Binding<String>,
        startExpanded: Bool,
        placeholderText: String,
        onSaveLyrics: ((String) -> Void)? = nil,
        showOnlyUndo: Bool = false,
        hideFooterControls: Bool = false,
        customHeight: CGFloat? = nil
    ) {
        self._lyricsText = lyricsText
        self.startExpanded = startExpanded
        self.placeholderText = placeholderText
        self.onSaveLyrics = onSaveLyrics
        self.showOnlyUndo = showOnlyUndo
        self.hideFooterControls = hideFooterControls
        self.customHeight = customHeight
        self._isExpanded = State(initialValue: startExpanded)
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Header
            HStack(spacing: 8) {
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        isExpanded.toggle()
                    }
                }) {
                    Image.FigmaMCP.chevronDown
                        .resizable()
                        .renderingMode(.template)
                        .frame(width: 12, height: 12)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        .rotationEffect(.degrees(isExpanded ? 0 : -90))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .buttonStyle(PlainButtonStyle())
                
                VStack(alignment: .leading, spacing: 4) {
                    HStack(alignment: .bottom, spacing: 8) {
                        Text("Lyrics")
                            .figmaMCPTypography(TypographyV1.FigmaMCP.small)
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                            .lineLimit(1)
                        
                        // Show character count when approaching limit
                        if lyricsText.count >= warningThreshold {
                            Text("\(lyricsText.count)")
                                .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                                .foregroundColor(ChatConstants.Colors.Accent.error)
                        }
                    }
                    
                    // Show typed text preview when collapsed and text exists
                    if !isExpanded && !lyricsText.isEmpty {
                        Text(lyricsText.replacingOccurrences(of: "\n", with: " "))
                            .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                            .foregroundColor(ChatConstants.Colors.Foreground.tertiary)
                            .lineLimit(1)
                            .multilineTextAlignment(.leading)
                    }
                }
                
                Spacer()
                
                // Show action buttons when in typing mode
                if isTypingMode && isExpanded {
                    HStack(spacing: 8) {
                        Button {
                            withAnimation(.easeInOut(duration: 0.2)) {
                                lyricsText = ""
                                isTextFieldFocused = false
                            }
                        } label: {
                            Image.FigmaMCP.editUndo
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        }
                        .frame(width: 32, height: 32)
                        .background(ChatConstants.Colors.Background.Glass.thin)
                        .clipShape(RoundedRectangle(cornerRadius: 8))
                        
                        Button {
                            withAnimation(.easeInOut(duration: 0.2)) {
                                lyricsText = ""
                                isTextFieldFocused = false
                            }
                        } label: {
                            Image.FigmaMCP.clear
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        }
                        .frame(width: 32, height: 32)
                        .background(ChatConstants.Colors.Background.Glass.thin)
                        .clipShape(RoundedRectangle(cornerRadius: 8))
                        
                        Button {
                            print("Save lyrics")
                        } label: {
                            Image.FigmaMCP.bookmarkOutline
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        }
                        .frame(width: 32, height: 32)
                        .background(ChatConstants.Colors.Background.Glass.thin)
                        .clipShape(RoundedRectangle(cornerRadius: 8))
                        
                        // Generate/Apply button (aura style)
                        Button {
                            print("Generate lyrics")
                        } label: {
                            Image.FigmaMCP.wand
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        }
                        .frame(width: 32, height: 32)
                        .background(ChatConstants.Colors.Accent.brand)
                        .clipShape(RoundedRectangle(cornerRadius: 8))
                    }
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 64)
            
            if isExpanded {
                // Text input section
                VStack(alignment: .leading, spacing: 0) {
                    ZStack(alignment: .topLeading) {
                        if lyricsText.isEmpty {
                            VStack(alignment: .leading, spacing: 4) {
                                Text(placeholderText)
                            }
                            .figmaMCPTypography(TypographyV1.FigmaMCP.paragraphMedium)
                            .foregroundColor(ChatConstants.Colors.Foreground.tertiary.opacity(0.6))
                            .allowsHitTesting(false)
                            .frame(maxHeight: .infinity, alignment: .top)
                        }
                        
                        TextField("", text: $lyricsText, axis: .vertical)
                            .tint(ChatConstants.Colors.Accent.brand)
                            .figmaMCPTypography(TypographyV1.FigmaMCP.paragraphMedium)
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                            .lineLimit(1...10)
                            .textFieldStyle(PlainTextFieldStyle())
                            .focused($isTextFieldFocused)
                            .keyboardType(.default)
                            .colorScheme(.dark)
                            .frame(maxHeight: .infinity, alignment: .top)
                            .onChange(of: lyricsText) { _, newValue in
                                // Enforce character limit
                                if newValue.count > characterLimit {
                                    lyricsText = String(newValue.prefix(characterLimit))
                                }
                            }
                    }
                    .frame(
                        minHeight: 60,
                        maxHeight: .infinity,
                        alignment: .top
                    )
                }
                .padding(.horizontal, 16)
                .padding(.bottom, 16)
                
                // Footer section - lyrics specific controls
                HStack(spacing: 8) {
                    // Left side controls
                    HStack(spacing: 8) {
                        // Library button
                        Button {
                            print("Library tapped")
                        } label: {
                            Image.FigmaMCP.library
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        }
                        .frame(width: 40, height: 32)
                        .background(ChatConstants.Colors.Background.Glass.thin)
                        .clipShape(RoundedRectangle(cornerRadius: 8))
                        
                        // Instrumental toggle
                        Button {
                            print("Instrumental toggle")
                        } label: {
                            Text("Instrumental")
                                .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallTitle)
                                .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        }
                        .padding(.horizontal, 12)
                        .frame(height: 32)
                        .background(ChatConstants.Colors.Background.Glass.thin)
                        .clipShape(RoundedRectangle(cornerRadius: 16))
                    }
                    
                    Spacer()
                    
                    // Right side - expand button
                    Button {
                        print("Expand editor")
                    } label: {
                        Image.FigmaMCP.expandContent
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 16, height: 16)
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                    }
                    .frame(width: 40, height: 32)
                    .background(ChatConstants.Colors.Background.Glass.thin)
                    .clipShape(RoundedRectangle(cornerRadius: 8))
                }
                .padding(.horizontal, 16)
                .padding(.bottom, 16)
            }
        }
        .background(Color.white.opacity(0.04)) // Background/Fog/Thin: #ffffff0a
        .clipShape(RoundedRectangle(cornerRadius: 16))
    }
}

struct StyleDescription: View {
    @Binding var styleText: String
    @FocusState private var isTextFieldFocused: Bool
    let modelVersion: String
    let startExpanded: Bool
    let onSaveStyle: ((String) -> Void)?
    
    @State private var isExpanded: Bool
    
    init(styleText: Binding<String>, modelVersion: String, startExpanded: Bool, onSaveStyle: ((String) -> Void)? = nil) {
        self._styleText = styleText
        self.modelVersion = modelVersion
        self.startExpanded = startExpanded
        self.onSaveStyle = onSaveStyle
        self._isExpanded = State(initialValue: startExpanded)
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Header
            HStack(spacing: 8) {
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        isExpanded.toggle()
                    }
                }) {
                    Image.FigmaMCP.chevronDown
                        .resizable()
                        .renderingMode(.template)
                        .frame(width: 12, height: 12)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        .rotationEffect(.degrees(isExpanded ? 0 : -90))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .buttonStyle(PlainButtonStyle())
                
                VStack(alignment: .leading, spacing: 4) {
                    Text("Style of Music")
                        .figmaMCPTypography(TypographyV1.FigmaMCP.small)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        .lineLimit(1)
                    
                    // Show typed text preview when collapsed and text exists
                    if !isExpanded && !styleText.isEmpty {
                        Text(styleText.replacingOccurrences(of: "\n", with: " "))
                            .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                            .foregroundColor(ChatConstants.Colors.Foreground.tertiary)
                            .lineLimit(1)
                            .multilineTextAlignment(.leading)
                    }
                }
                
                Spacer()
            }
            .padding(.horizontal, 16)
            .frame(height: 64)
            
            if isExpanded {
                // Text input section
                VStack(alignment: .leading, spacing: 0) {
                    ZStack(alignment: .topLeading) {
                        if styleText.isEmpty {
                            VStack(alignment: .leading, spacing: 4) {
                                Text("Describe the style, genre, mood, instruments...")
                            }
                            .figmaMCPTypography(TypographyV1.FigmaMCP.paragraphMedium)
                            .foregroundColor(ChatConstants.Colors.Foreground.tertiary.opacity(0.6))
                            .allowsHitTesting(false)
                            .frame(maxHeight: .infinity, alignment: .top)
                        }
                        
                        TextField("", text: $styleText, axis: .vertical)
                            .figmaMCPTypography(TypographyV1.FigmaMCP.paragraphMedium)
                            .foregroundColor(ChatConstants.Colors.Foreground.primary)
                            .lineLimit(3...6)
                            .textFieldStyle(PlainTextFieldStyle())
                            .focused($isTextFieldFocused)
                            .keyboardType(.default)
                            .colorScheme(.dark)
                            .frame(maxHeight: .infinity, alignment: .top)
                    }
                    .frame(
                        minHeight: 60,
                        maxHeight: .infinity,
                        alignment: .top
                    )
                }
                .padding(.horizontal, 16)
                .padding(.bottom, 16)
            }
        }
        .background(Color.white.opacity(0.04)) // Background/Fog/Thin: #ffffff0a
        .clipShape(RoundedRectangle(cornerRadius: 16))
    }
}

struct AdvancedOptions: View {
    @State private var isExpanded: Bool = false
    @Binding var weirdnessValue: Double
    @Binding var styleInfluenceValue: Double
    @Binding var audioInfluenceValue: Double
    @Binding var vocalGender: String
    
    private let vocalGenderOptions = ["Male", "Female"]
    
    init(
        weirdnessValue: Binding<Double> = .constant(0.5),
        styleInfluenceValue: Binding<Double> = .constant(0.5),
        audioInfluenceValue: Binding<Double> = .constant(0.5),
        vocalGender: Binding<String> = .constant("Female")
    ) {
        self._weirdnessValue = weirdnessValue
        self._styleInfluenceValue = styleInfluenceValue
        self._audioInfluenceValue = audioInfluenceValue
        self._vocalGender = vocalGender
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Header
            HStack(spacing: 8) {
                Button(action: {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        isExpanded.toggle()
                    }
                }) {
                    Image.FigmaMCP.chevronDown
                        .resizable()
                        .renderingMode(.template)
                        .frame(width: 12, height: 12)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        .rotationEffect(.degrees(isExpanded ? 0 : -90))
                        .animation(.easeInOut(duration: 0.3), value: isExpanded)
                }
                .buttonStyle(PlainButtonStyle())
                
                VStack(alignment: .leading, spacing: 4) {
                    Text("Advanced Options")
                        .figmaMCPTypography(TypographyV1.FigmaMCP.small)
                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                        .lineLimit(1)
                }
                
                Spacer()
            }
            .padding(.horizontal, 16)
            .frame(height: 64)
            
            if isExpanded {
                // Advanced options content
                VStack(spacing: 8) {
                    // Placeholder for advanced options - full implementation would include:
                    // - ExcludeStylesInput
                    // - SliderComponent for weirdnessValue
                    // - SliderComponent for styleInfluenceValue
                    // - SliderComponent for audioInfluenceValue
                    // - Vocal Gender selector
                    Text("Advanced options (sliders and controls)")
                        .font(.caption)
                        .foregroundColor(ChatConstants.Colors.Foreground.tertiary)
                        .padding(12)
                        .background(ChatConstants.Colors.Background.Glass.thin)
                        .cornerRadius(8)
                }
                .padding(.horizontal, 12)
                .padding(.bottom, 12)
            }
        }
        .background(Color.white.opacity(0.04)) // Background/Fog/Thin: #ffffff0a
        .clipShape(RoundedRectangle(cornerRadius: 16))
    }
}

struct CreateFooter: View {
    let isVisible: Bool
    let showTrashButton: Bool
    let isKeyboardVisible: Bool
    let createButtonTitle: String
    let onTrash: () -> Void
    let onCreate: () -> Void
    
    var body: some View {
        if isVisible {
            VStack {
                Spacer()
                
                VStack(spacing: 0) {
                    // Gradient overlay that fades content above (from Figma)
                    LinearGradient(
                        colors: [
                            ChatConstants.Colors.Background.primary.opacity(0.0),   // Fully transparent
                            ChatConstants.Colors.Background.primary.opacity(0.8)   // Semi-transparent
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                    .frame(height: 80)
                }
                .overlay(
                    // Buttons positioned over the gradient
                    VStack {
                        Spacer()
                        
                        HStack(spacing: 12) {
                            // Trash button (conditionally shown) - icon-only, 56x56 circle
                            if showTrashButton {
                                Button(action: onTrash) {
                                    Image.FigmaMCP.trash
                                        .resizable()
                                        .renderingMode(.template)
                                        .frame(width: 24, height: 24)
                                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                                }
                                .frame(width: 56, height: 56)
                                .background(
                                    RoundedRectangle(cornerRadius: 100)
                                        .fill(ChatConstants.Colors.Background.tertiary)
                                )
                                .buttonStyle(ActionButtonStyle())
                            }
                            
                            // Create button - aura style with icon and text
                            Button {
                                onCreate()
                            } label: {
                                HStack(spacing: 4) {
                                    Image.FigmaMCP.create
                                        .resizable()
                                        .renderingMode(.template)
                                        .frame(width: 16, height: 16)
                                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                                    
                                    Text(createButtonTitle)
                                        .figmaMCPTypography(TypographyV1.FigmaMCP.largeTitle)
                                        .foregroundColor(ChatConstants.Colors.Foreground.primary)
                                        .tracking(0.36)
                                        .lineLimit(1)
                                }
                                .frame(maxWidth: .infinity)
                                .frame(height: 56)
                                .padding(.horizontal, 24)
                                .background {
                                    // Aura background - using animated shader if available, otherwise gradient
#if targetEnvironment(simulator)
                                    LinearGradient(
                                        colors: [
                                            ChatConstants.Colors.Accent.purple,
                                            ChatConstants.Colors.Accent.pink
                                        ],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
#else
                                    AuraShaderView(
                                        id: "create-button-aura",
                                        appPreset: .pinkYellowOrange,
                                        morphSpeed: 0.05,
                                        scale: 0.2,
                                        seed: 0
                                    )
#endif
                                }
                                .clipShape(Capsule())
                            }
                            .buttonStyle(ActionButtonStyle())
                        }
                        .padding(.horizontal, 16)
                        .padding(.bottom, isKeyboardVisible ? 16 : 50)
                    }
                )
            }
        }
    }
}

private func createGradientForSong(_ song: Song) -> LinearGradient {
    guard let artwork = song.artwork else {
        return LinearGradient(
            colors: [
                ChatConstants.Colors.Accent.purple,
                ChatConstants.Colors.Accent.pink
            ],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
    }

    let hash = artwork.hashValue
    let seed1 = abs(hash % 1000)
    let seed2 = abs((hash / 1000) % 1000)

    return LinearGradient(
        colors: [
            Color(
                red: 0.3 + (Double(seed1 % 600) / 1000.0),
                green: 0.3 + (Double((seed1 + 200) % 600) / 1000.0),
                blue: 0.3 + (Double((seed1 + 400) % 600) / 1000.0)
            ),
            Color(
                red: 0.3 + (Double(seed2 % 600) / 1000.0),
                green: 0.3 + (Double((seed2 + 200) % 600) / 1000.0),
                blue: 0.3 + (Double((seed2 + 400) % 600) / 1000.0)
            )
        ],
        startPoint: .topLeading,
        endPoint: .bottomTrailing
    )
}

#Preview {
    let sampleSong = Song(
        id: "1",
        title: "Sample Song",
        genres: ["pop", "electronic"],
        artwork: nil
    )
    
    CustomChatView(
        text: .constant(""),
        isEditingLyrics: .constant(false),
        isInExtendMode: .constant(false),
        currentlySelectedSong: sampleSong,
        currentLyrics: nil,
        billingInfo: nil,
        audioManager: AudioManager.shared,
        onSendTap: { print("Send tapped") },
        onDismiss: { print("Dismiss tapped") }
    )
}
