//
//  OneSongMainViewB.swift
//  vibes
//
//  Main interface for One Song - iterative music creation
//

import SwiftUI

struct OneSongMainViewB: View {
    // MARK: - Light Mode Color Overrides
    // These colors are specific to the versions exploration in light mode
    private struct LightColors {
        static let backgroundPrimary = Color.white
        static let backgroundSecondary = Color(hex: "#f7f4ef")  // Light beige
        static let foregroundPrimary = Color(hex: "#101012")    // Dark/black
        static let foregroundSecondary = Color(hex: "#5b5b62")  // Medium gray
        static let foregroundTertiary = Color(hex: "#a3a3a3")   // Light gray
        static let borderPrimary = Color.black.opacity(0.10)
        static let accentOrange = Color(hex: "#ff6a00")         // Keep same
    }

    var onDismiss: (() -> Void)? = nil
    var onAddToLibrary: ((String, String, String) -> Void)? = nil // (albumArt, songName, description)

    @Environment(\.dismiss) var dismiss
    @StateObject private var sessionManager = OneSongSessionManagerB.shared
    @StateObject private var audioManager = AudioManager.shared
    @State private var currentPrompt = ""
    @State private var isGenerating = false
    @State private var animationProgress: Double = 0
    @State private var isWaveformAnimating = false
    @State private var waveAmplitude: Double = 0.08
    @FocusState private var isInputFocused: Bool
    @State private var dragOffset: CGFloat = 0
    @State private var isDragging = false
    @State private var baseOffset: CGFloat = 0
    @State private var carouselWidth: CGFloat = 0
    @State private var isVersionDropdownShown = false
    @State private var isScrubbing = false
    @State private var isInSaveMode = false
    @State private var editedSongName: String = ""
    @State private var isEditingSongName = false
    @State private var showArtworkAnimated = false
    @State private var showEditButtonsAnimated = false
    @State private var showSaveButtonAnimated = false
    @State private var artworkGradientColors: [Color] = [
        Color(red: 0.8, green: 0.4, blue: 0.9),
        Color(red: 0.4, green: 0.6, blue: 1.0)
    ]
    @State private var isCollapsed = false
    @State private var currentAlbumArtIndex = 0
    @State private var currentSongNameIndex = 0
    @State private var showMinimizeDialog = false

    // Album art filenames from Resources/album-art
    private let albumArtFiles = [
        "cry cried crying.png",
        "crystal healing.png",
        "daylight.png",
        "ECLIPSE.png",
        "feel good.png",
        "fernery.png",
        "flower in the wind.png",
        "Found.png",
        "FREEEEEEEEE.png",
        "gameboy colors.png",
        "going somewhere.png",
        "Heal your Soul.png",
        "her.png",
        "highs and lows.png",
        "church wast of time.png",
        "coachella wave.png",
        "car mirror light.png",
        "CYE BLUE.png",
        "CYE FIRE .png",
        "DIGITAL CD.png",
        "DO IT.png",
        "DREAM GIRL.png",
        "Dreamin DAY.png",
        "ECLIPSE FM.png",
        "EYE.png",
        "face to face.png",
        "faded 2.png",
        "FAREWELL.png",
        "FLOATING.png",
        "FLower window.png",
        "FRAME.png",
        "FRIENDS TO LOVERS.png",
        "Garden door.png",
        "GHOSTS.png",
        "God breathed on this.png",
        "Green Tile.png",
        "GROW.png",
        "HEAD TO THE SKY.png",
        "HELP ME GOD.png"
    ]

    // Song name options
    private let songNames = [
        "Midnight Dreams",
        "Crystal Heart",
        "Fading Light",
        "Electric Soul",
        "Ocean Eyes",
        "Golden Hour",
        "Velvet Sky",
        "Neon Nights",
        "Summer Rain",
        "Lost in Paradise",
        "Echoes of You",
        "Starlight",
        "Wild Heart",
        "Dancing Shadows",
        "Aurora",
        "Butterfly Effect",
        "Cosmic Love",
        "Daydream",
        "Euphoria",
        "Falling Stars",
        "Garden of Eden",
        "Heartbeat",
        "Infinity",
        "Luna",
        "Moonlight",
        "Paradise",
        "Sacred",
        "Timeless",
        "Waves",
        "Wonderland"
    ]

    private let allSuggestions = [
        "Slower",
        "Faster",
        "More Upbeat",
        "Add Guitar",
        "More Chill",
        "Add Drums",
        "Make it Epic",
        "Add Piano",
        "More Energy",
        "Softer Vocals",
        "Add Bass",
        "More Reverb",
        "80s Synth",
        "Acoustic Version",
        "Add Strings",
        "Double Tempo",
        "Half Tempo",
        "More Harmony",
        "Add Claps",
        "Lo-fi Style"
    ]

    var body: some View {
        Group {
            if isCollapsed {
                collapsedView
            } else {
                expandedView
            }
        }
        .preferredColorScheme(.light)  // Force light mode for versions exploration only
        .navigationBarBackButtonHidden(true)
        .interactiveDismissDisabled()
    }

    // MARK: - Collapsed View
    private var collapsedView: some View {
        ZStack {
            LightColors.backgroundPrimary
                .ignoresSafeArea()

            VStack {
                Spacer()

                Button(action: {
                    withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                        isCollapsed = false
                    }
                }) {
                    Image(systemName: "chevron.up")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(LightColors.foregroundPrimary)
                        .frame(width: 48, height: 48)
                        .background(Circle().fill(LightColors.backgroundSecondary))
                        .overlay(
                            Circle()
                                .stroke(LightColors.borderPrimary, lineWidth: 1)
                        )
                }
                .padding(.bottom, 32)
            }
        }
    }

    // MARK: - Expanded View
    private var expandedView: some View {
        ZStack {
            LightColors.backgroundPrimary
                .ignoresSafeArea()
                .onTapGesture {
                    // Close dropdown when tapping background
                    if isVersionDropdownShown {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            isVersionDropdownShown = false
                        }
                    }
                }

            VStack(spacing: 0) {
                // Center: Waveform display area or empty state (fixed space)
                ZStack {
                    // Empty State
                    emptyStateView
                        .opacity(sessionManager.iterations.isEmpty && !isGenerating ? 1 : 0)

                    // Waveform carousel (always present to maintain layout)
                    GeometryReader { geometry in
                        HStack(spacing: 0) {
                            ForEach(sessionManager.iterations) { iteration in
                                let index = sessionManager.iterations.firstIndex(where: { $0.id == iteration.id }) ?? 0
                                waveformView(for: iteration, isActive: index == sessionManager.currentIndex)
                                    .frame(width: geometry.size.width)
                            }
                        }
                        .offset(x: baseOffset + dragOffset)
                        .onAppear {
                            carouselWidth = geometry.size.width
                            baseOffset = -CGFloat(sessionManager.currentIndex) * carouselWidth
                        }
                        .onChange(of: geometry.size.width) { _, newWidth in
                            carouselWidth = newWidth
                            baseOffset = -CGFloat(sessionManager.currentIndex) * carouselWidth
                        }
                    }
                    .clipped()
                    .opacity(sessionManager.iterations.isEmpty ? 0 : 1)
                    .opacity(isInSaveMode ? 0 : 1)

                    // Save mode interface
                    if isInSaveMode {
                        saveInterfaceView
                            .transition(.opacity.combined(with: .scale(scale: 0.95)))
                    }
                }
                .frame(maxHeight: .infinity)
                .contentShape(Rectangle())
                .onTapGesture {
                    // Disable tap gesture when in save mode
                    guard !isInSaveMode else { return }
                    // Tap anywhere to play/pause the current iteration
                    guard !isGenerating, !sessionManager.iterations.isEmpty, let iteration = currentIteration else { return }
                    togglePlayback(for: iteration)
                }
                .gesture(
                    DragGesture()
                        .onChanged { value in
                            // Don't allow gestures in save mode
                            guard !isInSaveMode else { return }
                            // Don't allow carousel dragging when scrubbing
                            guard !isScrubbing else { return }
                            // Only allow dragging when we have iterations and not generating
                            guard !sessionManager.iterations.isEmpty && !isGenerating else { return }

                            isDragging = true
                            dragOffset = value.translation.width
                        }
                        .onEnded { value in
                            // Don't allow gestures in save mode
                            guard !isInSaveMode else { return }
                            // Don't allow carousel dragging when scrubbing
                            guard !isScrubbing else { return }
                            guard !sessionManager.iterations.isEmpty && !isGenerating else { return }

                            let threshold: CGFloat = 100

                            if value.translation.width > threshold && sessionManager.currentIndex > 0 {
                                // Swipe right - go to previous iteration
                                navigateToPrevious()
                            } else if value.translation.width < -threshold && sessionManager.currentIndex < sessionManager.iterations.count - 1 {
                                // Swipe left - go to next iteration
                                navigateToNext()
                            } else {
                                // Didn't pass threshold - animate back to original position
                                withAnimation(.spring(response: 0.4, dampingFraction: 0.75, blendDuration: 0)) {
                                    dragOffset = 0
                                    isDragging = false
                                }
                            }
                        }
                )

                // Pagination dots (only show when not in save mode and have multiple iterations)
                if !isInSaveMode && sessionManager.iterations.count > 1 {
                    paginationDots
                        .padding(.bottom, 8)
                        .transition(.opacity)
                }

                // Bottom: Input area (only show when not in save mode)
                if !isInSaveMode {
                    inputAreaView
                }
            }

            // Top: Song title header, iteration indicator, and save button (overlaid, doesn't affect layout)
            VStack(spacing: 8) {
                ZStack {
                    if let _ = currentIteration {
                        // Title with optional caret icon
                        Button(action: {
                            // Only show dropdown if there are 2+ iterations
                            if sessionManager.iterations.count >= 2 {
                                withAnimation(.easeInOut(duration: 0.2)) {
                                    isVersionDropdownShown.toggle()
                                }
                            }
                        }) {
                            HStack(spacing: 4) {
                                Text("Audio \(sessionManager.currentIndex + 1)")
                                    .font(Constants.Typography.mediumTitle)
                                    .foregroundColor(LightColors.foregroundPrimary)

                                // Show caret only when there are 2+ iterations
                                if sessionManager.iterations.count >= 2 {
                                    Image(systemName: "chevron.down")
                                        .font(.system(size: 12, weight: .medium))
                                        .foregroundColor(LightColors.foregroundSecondary)
                                        .rotationEffect(.degrees(isVersionDropdownShown ? 180 : 0))
                                        .animation(.easeInOut(duration: 0.2), value: isVersionDropdownShown)
                                }
                            }
                        }
                        .buttonStyle(PlainButtonStyle())
                        .frame(maxWidth: .infinity, minHeight: 40)
                        .padding(.top, 16)
                        .background(LightColors.backgroundPrimary)
                        .transition(.opacity)
                        .id("title-\(sessionManager.currentIndex)")
                        .opacity(isInSaveMode ? 0 : 1)
                    }

                    // Dismiss/Back button in top left
                    HStack {
                        Button(action: {
                            if isInSaveMode {
                                // Exit save mode
                                withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                                    isInSaveMode = false
                                }
                                // Reset animation states for next time
                                showArtworkAnimated = false
                                showSaveButtonAnimated = false
                            } else {
                                // Dismiss keyboard
                                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)

                                // Pause any playing audio
                                if audioManager.isCurrentlyPlaying {
                                    audioManager.pauseAudio()
                                }

                                // Dismiss back to library
                                if let onDismiss = onDismiss {
                                    withAnimation(.spring(response: 0.5, dampingFraction: 0.85)) {
                                        onDismiss()
                                    }
                                } else {
                                    // Fallback: show minimize dialog
                                    withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
                                        showMinimizeDialog = true
                                    }
                                }
                            }
                        }) {
                            Image(systemName: isInSaveMode ? "arrow.left" : "chevron.down")
                                .font(.system(size: 16, weight: .semibold))
                                .foregroundColor(LightColors.foregroundPrimary)
                                .frame(width: 40, height: 40)
                                .background(Circle().fill(LightColors.backgroundSecondary))
                                .overlay(
                                    Circle()
                                        .stroke(LightColors.borderPrimary, lineWidth: 1)
                                )
                                .contentTransition(.symbolEffect(.replace))
                        }
                        .padding(.top, 16)
                        .padding(.leading, 16)

                        Spacer()
                    }

                    // Checkmark button in top right (hidden in save mode)
                    if !isInSaveMode {
                        HStack {
                            Spacer()
                            Button(action: {
                                // Dismiss keyboard with animation using UIKit
                                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)

                                // Wait for keyboard animation to complete, then transition
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                                    isInputFocused = false  // Update state after animation
                                    audioManager.pauseAudio()  // Pause music when entering save mode
                                    withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                                        isInSaveMode = true
                                    }
                                }
                            }) {
                                Image(systemName: "checkmark")
                                    .font(.system(size: 16, weight: .semibold))
                                    .foregroundColor(.white)
                                    .frame(width: 40, height: 40)
                                    .background(Circle().fill(.black))
                            }
                            .opacity(sessionManager.iterations.isEmpty || isGenerating ? 0 : 1)
                            .animation(.easeInOut(duration: 0.25), value: isGenerating)
                            .disabled(sessionManager.iterations.isEmpty || isGenerating)
                            .allowsHitTesting(!sessionManager.iterations.isEmpty && !isGenerating)
                            .padding(.top, 16)
                            .padding(.trailing, 16)
                            .transition(.opacity.combined(with: .scale(scale: 0.8)))
                        }
                    }
                }
                .frame(minHeight: 56)

                // Version dropdown menu
                if isVersionDropdownShown && sessionManager.iterations.count >= 2 {
                    versionDropdownMenu
                        .padding(.top, 8)
                        .padding(.horizontal, 16)
                        .transition(.asymmetric(
                            insertion: .opacity.combined(with: .move(edge: .top)),
                            removal: .opacity
                        ))
                }

                Spacer()
            }

            // Minimize dialog with scrim
            if showMinimizeDialog {
                ZStack {
                    // Scrim (semi-transparent background)
                    Color.black.opacity(0.4)
                        .ignoresSafeArea()
                        .onTapGesture {
                            withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
                                showMinimizeDialog = false
                            }
                        }

                    // Dialog
                    VStack(spacing: 16) {
                        // Empty dialog content for now
                    }
                    .frame(width: 300, height: 200)
                    .background(
                        RoundedRectangle(cornerRadius: 16)
                            .fill(LightColors.backgroundPrimary)
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 16)
                            .stroke(LightColors.borderPrimary, lineWidth: 1)
                    )
                    .shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 10)
                }
                .transition(.opacity)
            }
        }
        .onAppear {
            // Initialize animation state for completed iterations
            if !sessionManager.iterations.isEmpty {
                animationProgress = 1.0
                isWaveformAnimating = false
                loadChipsForCurrentIteration()
            }
        }
    }

    // MARK: - Pagination Dots
    private var paginationDots: some View {
        HStack(spacing: 6) {
            ForEach(0..<sessionManager.iterations.count, id: \.self) { index in
                Circle()
                    .fill(index == sessionManager.currentIndex ? LightColors.foregroundPrimary : LightColors.foregroundTertiary)
                    .frame(width: 6, height: 6)
                    .animation(.easeInOut(duration: 0.2), value: sessionManager.currentIndex)
            }
        }
        .padding(.vertical, 8)
    }

    // MARK: - Save Interface
    private var saveInterfaceView: some View {
        VStack(spacing: 0) {
            Spacer()

            // Album artwork - centered, with regenerate button overlaid to the right
            ZStack(alignment: .trailing) {
                if let uiImage = UIImage(named: albumArtFiles[currentAlbumArtIndex]) {
                    Image(uiImage: uiImage)
                        .resizable()
                        .scaledToFill()
                        .frame(width: 200, height: 316)
                        .clipShape(RoundedRectangle(cornerRadius: 24))
                        .blur(radius: showArtworkAnimated ? 0 : 20)
                        .opacity(showArtworkAnimated ? 1 : 0)
                } else {
                    RoundedRectangle(cornerRadius: 24)
                        .fill(
                            LinearGradient(
                                colors: artworkGradientColors,
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 200, height: 316)
                        .blur(radius: showArtworkAnimated ? 0 : 20)
                        .opacity(showArtworkAnimated ? 1 : 0)
                }

                // Regenerate button for artwork - positioned to the right
                Button(action: {
                    currentAlbumArtIndex = (currentAlbumArtIndex + 1) % albumArtFiles.count
                }) {
                    Circle()
                        .fill(LightColors.backgroundSecondary)
                        .frame(width: 32, height: 32)
                        .overlay(
                            Circle()
                                .stroke(LightColors.borderPrimary, lineWidth: 1)
                        )
                        .overlay(
                            Image(systemName: "arrow.clockwise")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(LightColors.foregroundPrimary)
                        )
                }
                .blur(radius: showArtworkAnimated ? 0 : 20)
                .opacity(showArtworkAnimated ? 1 : 0)
                .offset(x: 44)
            }
            .frame(maxWidth: .infinity)

            // Title - centered, with regenerate button overlaid to the right
            ZStack(alignment: .trailing) {
                Text(songNames[currentSongNameIndex])
                    .font(.system(size: 20, weight: .semibold))
                    .foregroundColor(LightColors.foregroundPrimary)
                    .multilineTextAlignment(.center)
                    .blur(radius: showArtworkAnimated ? 0 : 20)
                    .opacity(showArtworkAnimated ? 1 : 0)

                // Regenerate button for title - positioned to the right
                Button(action: {
                    currentSongNameIndex = (currentSongNameIndex + 1) % songNames.count
                }) {
                    Circle()
                        .fill(LightColors.backgroundSecondary)
                        .frame(width: 24, height: 24)
                        .overlay(
                            Circle()
                                .stroke(LightColors.borderPrimary, lineWidth: 1)
                        )
                        .overlay(
                            Image(systemName: "arrow.clockwise")
                                .font(.system(size: 12, weight: .semibold))
                                .foregroundColor(LightColors.foregroundPrimary)
                        )
                }
                .blur(radius: showArtworkAnimated ? 0 : 20)
                .opacity(showArtworkAnimated ? 1 : 0)
                .offset(x: 32)
            }
            .frame(maxWidth: .infinity)
            .padding(.top, 16)

            Spacer()

            // Action buttons at the bottom
            VStack(spacing: 10) {
                // Add to Library button (filled black)
                Button(action: {
                    // Get the current album art and song name
                    let albumArt = albumArtFiles[currentAlbumArtIndex]
                    let songName = songNames[currentSongNameIndex]

                    // Generate a simple description
                    let description = "Original creation"

                    // Call the callback to add to library
                    onAddToLibrary?(albumArt, songName, description)
                }) {
                    Text("Add to Library")
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(.black)
                        )
                }

                // Post button (light gray)
                Button(action: {
                    // TODO: Implement post action
                    print("Post tapped")
                }) {
                    Text("Post")
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundColor(LightColors.foregroundPrimary)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(LightColors.backgroundSecondary)
                                .overlay(
                                    RoundedRectangle(cornerRadius: 12)
                                        .stroke(LightColors.borderPrimary, lineWidth: 1)
                                )
                        )
                }

                // Share button (light gray)
                Button(action: {
                    // TODO: Implement share action
                    print("Share tapped")
                }) {
                    Text("Share")
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundColor(LightColors.foregroundPrimary)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(LightColors.backgroundSecondary)
                                .overlay(
                                    RoundedRectangle(cornerRadius: 12)
                                        .stroke(LightColors.borderPrimary, lineWidth: 1)
                                )
                        )
                }

                // Keep in Drafts button (text only, no background)
                Button(action: {
                    // TODO: Implement keep in drafts action
                    print("Keep in Drafts tapped")
                }) {
                    Text("Keep in Drafts")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundColor(LightColors.foregroundSecondary)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                }
            }
            .padding(.horizontal, 32)
            .padding(.bottom, 16)
            .opacity(showSaveButtonAnimated ? 1 : 0)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onAppear {
            // Reset animation states
            showArtworkAnimated = false
            showSaveButtonAnimated = false

            // Randomize album art and song name on each appearance
            currentAlbumArtIndex = Int.random(in: 0..<albumArtFiles.count)
            currentSongNameIndex = Int.random(in: 0..<songNames.count)

            // 2-stage animation sequence
            withAnimation(.easeOut(duration: 2.0)) {
                showArtworkAnimated = true
            }

            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {
                    showSaveButtonAnimated = true
                }
            }
        }
    }

    // MARK: - Helper Functions
    private func generateRandomSongName() -> String {
        let adjectives = ["Electric", "Midnight", "Golden", "Crystal", "Neon", "Velvet", "Cosmic", "Ocean", "Forest", "Summer"]
        let nouns = ["Dreams", "Memories", "Vibes", "Echoes", "Waves", "Sky", "Soul", "Heart", "Lights", "Journey"]

        let adjective = adjectives.randomElement() ?? "Beautiful"
        let noun = nouns.randomElement() ?? "Song"

        return "\(adjective) \(noun)"
    }

    private func generateRandomGradient() -> [Color] {
        // Generate two random colors with good saturation for nice gradients
        let hue1 = Double.random(in: 0...1)
        let hue2 = Double.random(in: 0...1)

        let color1 = Color(hue: hue1, saturation: 0.7, brightness: 0.8)
        let color2 = Color(hue: hue2, saturation: 0.6, brightness: 0.9)

        return [color1, color2]
    }

    // MARK: - Empty State
    private var emptyStateView: some View {
        VStack(spacing: 16) {
            Spacer()

            VStack(spacing: 12) {
                // SUNO logo (dark version for light mode)
                Image("sunologo-dark")
                    .resizable()
                    .scaledToFit()
                    .frame(height: 24)

                // Tagline
                Text("Make any song you can imagine")
                    .font(Constants.Typography.mediumRegular)
                    .foregroundColor(LightColors.foregroundSecondary)
            }

            Spacer()
        }
    }

    // MARK: - Waveform Display
    private func waveformView(for iteration: SongIteration, isActive: Bool) -> some View {
        let computedPlaybackProgress = isActive && audioManager.currentlyPlayingSongId == iteration.id.uuidString ? audioManager.currentProgress : 0.0

        return VStack(spacing: 16) {
            Spacer()

            // Waveform visualization - always use iteration's own seed
            // Show full progress unless actively generating
            BarStyleWaveformView(
                isAnimating: isActive && isWaveformAnimating,
                progress: (isActive && isGenerating) ? animationProgress : 1.0,
                waveformSeed: Double(iteration.waveformSeed),
                playbackProgress: computedPlaybackProgress,
                waveAmplitude: waveAmplitude
            )
            .frame(height: 300)
            .padding(.horizontal, 40)
            .coordinateSpace(name: "waveform")
            .contentShape(Rectangle())
            .onTapGesture {
                // Tap anywhere to play/pause
                if !isGenerating {
                    togglePlayback(for: iteration)
                }
            }
            .overlay(
                // Waveform scrubbing area - only center 87pt
                Color.clear
                    .frame(height: 87)
                    .contentShape(Rectangle())
                    .highPriorityGesture(
                        DragGesture(minimumDistance: 0, coordinateSpace: .named("waveform"))
                            .onChanged { value in
                                guard !isGenerating else { return }
                                guard audioManager.currentlyPlayingSongId == iteration.id.uuidString else { return }

                                // Start scrubbing
                                if !isScrubbing {
                                    isScrubbing = true
                                    audioManager.startScrubbing()
                                }

                                // Calculate scrub position - subtract left padding
                                let touchX = value.location.x - 40
                                let waveformWidth = UIScreen.main.bounds.width - 80
                                let scrubProgress = max(0, min(1, touchX / waveformWidth))

                                audioManager.seekToProgress(scrubProgress)
                            }
                            .onEnded { _ in
                                if isScrubbing {
                                    audioManager.endScrubbing()
                                    isScrubbing = false
                                }
                            }
                    )
            )

            Spacer()
        }
    }

    // MARK: - Version Dropdown Menu
    private var versionDropdownMenu: some View {
        VStack(spacing: 8) {
            ForEach(Array(sessionManager.iterations.enumerated()), id: \.element.id) { index, iteration in
                Button(action: {
                    // Switch to this version
                    withAnimation(.spring(response: 0.4, dampingFraction: 0.75, blendDuration: 0)) {
                        sessionManager.setCurrentIndex(index)
                        baseOffset = -CGFloat(index) * carouselWidth
                        dragOffset = 0
                        isVersionDropdownShown = false
                    }

                    // Set waveform to fully formed state
                    animationProgress = 1.0
                    isWaveformAnimating = false

                    // Load chips for this iteration
                    loadChipsForCurrentIteration()

                    // Play the song for the new iteration if audio was playing
                    if audioManager.isCurrentlyPlaying {
                        togglePlayback(for: iteration)
                    }
                }) {
                    HStack(spacing: 12) {
                        // Version label
                        Text("Audio \(index + 1)")
                            .font(Constants.Typography.mediumTitle)
                            .foregroundColor(
                                index == sessionManager.currentIndex
                                    ? LightColors.foregroundPrimary
                                    : LightColors.foregroundSecondary
                            )
                            .frame(maxWidth: .infinity, alignment: .leading)

                        // Checkmark for current version
                        if index == sessionManager.currentIndex {
                            Image(systemName: "checkmark")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(LightColors.accentOrange)
                        }
                    }
                    .padding(.horizontal, 12)
                    .padding(.vertical, 10)
                    .background(
                        RoundedRectangle(cornerRadius: 8)
                            .fill(
                                index == sessionManager.currentIndex
                                    ? LightColors.backgroundSecondary
                                    : Color.clear
                            )
                    )
                    .contentShape(Rectangle())
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
        .padding(8)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(LightColors.backgroundSecondary)
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(LightColors.borderPrimary, lineWidth: 1)
                )
        )
        .shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 10)
    }

    // MARK: - Input Area
    private var inputAreaView: some View {
        VStack(spacing: 4) {
            // Container 1: Chips ScrollView
            // Chips can scroll past the 16px margins but stay within overall container
            ScrollViewReader { proxy in
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 8) {
                        // Permanent chips - always visible on the left
                        // Plus button
                        Button(action: {
                            // TODO: Implement plus action
                            print("Plus tapped")
                        }) {
                            Image(systemName: "plus")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(LightColors.foregroundPrimary)
                                .frame(width: 32, height: 32)
                                .background(
                                    RoundedRectangle(cornerRadius: 16)
                                        .fill(LightColors.backgroundPrimary)
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 16)
                                                .stroke(LightColors.borderPrimary, lineWidth: 1)
                                        )
                                )
                        }
                        .disabled(isGenerating)
                        .id("plusButton")

                    // Settings button
                    Button(action: {
                        // TODO: Implement settings action
                        print("Settings tapped")
                    }) {
                        Image(systemName: "slider.horizontal.3")
                            .font(.system(size: 14, weight: .semibold))
                            .foregroundColor(LightColors.foregroundPrimary)
                            .frame(width: 32, height: 32)
                            .background(
                                RoundedRectangle(cornerRadius: 16)
                                    .fill(LightColors.backgroundPrimary)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 16)
                                            .stroke(LightColors.borderPrimary, lineWidth: 1)
                                    )
                            )
                    }
                    .disabled(isGenerating)

                    // Suggestion chips - fade in after first song
                    if !sessionManager.suggestionChips.isEmpty {
                        ForEach(Array(sessionManager.suggestionChips.enumerated()), id: \.offset) { index, suggestion in
                            Button(action: {
                                currentPrompt = suggestion
                            }) {
                                Text(suggestion)
                                    .font(Constants.Typography.small)
                                    .foregroundColor(LightColors.foregroundPrimary)
                                    .padding(.horizontal, 12)
                                    .padding(.vertical, 8)
                                    .background(
                                        RoundedRectangle(cornerRadius: 16)
                                            .fill(LightColors.backgroundPrimary)
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 16)
                                                    .stroke(LightColors.borderPrimary, lineWidth: 1)
                                            )
                                    )
                            }
                            .opacity(!sessionManager.iterations.isEmpty && !isGenerating ? 1 : 0)
                            .animation(.easeInOut(duration: 0.25), value: isGenerating)
                            .disabled(isGenerating)
                            .id(index)
                        }
                    }
                }
                .onChange(of: sessionManager.currentIndex) { _, _ in
                    // Reset scroll position when navigating between versions
                    withAnimation {
                        proxy.scrollTo("plusButton", anchor: .leading)
                    }
                }
            }
            .contentMargins(.horizontal, 16, for: .scrollContent)
            .frame(height: 40)
            }

            // Container 2: Text input and submit button
            // Fixed 16px margin, content doesn't scroll
            HStack(spacing: 8) {
                LightTextField(
                    text: $currentPrompt,
                    placeholder: "Song about that feeling...",
                    font: UIFont(name: "PP Neue Montreal", size: 16) ?? UIFont.systemFont(ofSize: 16, weight: .medium),
                    textColor: UIColor(LightColors.foregroundPrimary),
                    onSubmit: {
                        submitPrompt()
                    }
                )
                .frame(height: 48)
                .focused($isInputFocused)

                Button(action: {
                    submitPrompt()
                }) {
                    Image(systemName: currentPrompt.isEmpty && !sessionManager.iterations.isEmpty && !isGenerating ? "arrow.clockwise.circle.fill" : "arrow.up.circle.fill")
                        .font(.system(size: 24))
                        .foregroundColor(
                            (sessionManager.iterations.isEmpty && currentPrompt.isEmpty)
                                ? LightColors.foregroundTertiary
                                : LightColors.accentOrange
                        )
                        .contentTransition(.symbolEffect(.replace))
                }
                .opacity(isGenerating ? 0.25 : 1.0)
                .disabled((currentPrompt.isEmpty && sessionManager.iterations.isEmpty) || isGenerating)
                .animation(.easeInOut(duration: 0.3), value: currentPrompt.isEmpty && !isGenerating)
            }
            .padding(.leading, 16)
            .padding(.trailing, 12)
            .frame(height: 48)
        }
        .padding(.top, 10)
        .padding(.bottom, 8)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(LightColors.backgroundSecondary)
                .overlay(
                    RoundedRectangle(cornerRadius: 16)
                        .stroke(LightColors.borderPrimary, lineWidth: 1)
                )
        )
        .clipShape(RoundedRectangle(cornerRadius: 16))  // Clip chips to rounded corners
        .padding(.horizontal, 16)  // Distance from screen edges
        .padding(.bottom, 16)
        .onAppear {
            isInputFocused = true
        }
    }

    // MARK: - Computed Properties
    private var currentIteration: SongIteration? {
        guard sessionManager.currentIndex < sessionManager.iterations.count else { return nil }
        return sessionManager.iterations[sessionManager.currentIndex]
    }

    // MARK: - Navigation
    private func navigateToPrevious() {
        guard sessionManager.currentIndex > 0 else { return }

        withAnimation(.spring(response: 0.4, dampingFraction: 0.75, blendDuration: 0)) {
            sessionManager.setCurrentIndex(sessionManager.currentIndex - 1)
            baseOffset = -CGFloat(sessionManager.currentIndex) * carouselWidth
            dragOffset = 0  // Animate dragOffset to 0 together with baseOffset
            isDragging = false
        }
        // Set waveform to fully formed state, not animating
        animationProgress = 1.0
        isWaveformAnimating = false

        // Load chips for this iteration
        loadChipsForCurrentIteration()

        // Play the song for the new iteration if audio was playing
        if audioManager.isCurrentlyPlaying, let iteration = currentIteration {
            togglePlayback(for: iteration)
        }
    }

    private func navigateToNext() {
        guard sessionManager.currentIndex < sessionManager.iterations.count - 1 else { return }

        withAnimation(.spring(response: 0.4, dampingFraction: 0.75, blendDuration: 0)) {
            sessionManager.setCurrentIndex(sessionManager.currentIndex + 1)
            baseOffset = -CGFloat(sessionManager.currentIndex) * carouselWidth
            dragOffset = 0  // Animate dragOffset to 0 together with baseOffset
            isDragging = false
        }
        // Set waveform to fully formed state, not animating
        animationProgress = 1.0
        isWaveformAnimating = false

        // Load chips for this iteration
        loadChipsForCurrentIteration()

        // Play the song for the new iteration if audio was playing
        if audioManager.isCurrentlyPlaying, let iteration = currentIteration {
            togglePlayback(for: iteration)
        }
    }

    private func loadChipsForCurrentIteration() {
        guard let iteration = currentIteration else { return }
        sessionManager.updateSuggestionChips(iteration.suggestionChips)
    }

    // MARK: - Actions
    private func submitPrompt() {
        // Pause any currently playing audio before starting generation
        if audioManager.isCurrentlyPlaying {
            audioManager.pauseAudio()
        }

        let submittedPrompt = currentPrompt
        currentPrompt = ""  // Clear immediately

        // Check if this is the first generation
        let isFirstGeneration = sessionManager.iterations.isEmpty

        if isFirstGeneration {
            // First generation - create TWO versions
            // Generate Audio 1
            let version1Title = generateEvolvingTitle(from: submittedPrompt, previousTitle: nil)
            let version1Chips = Array(allSuggestions.shuffled().prefix(7))
            let version1Song = sessionManager.getUnusedSongName()

            let version1 = SongIteration(
                prompt: submittedPrompt,
                title: version1Title,
                waveformData: generateMockWaveformData(),
                audioAssetName: version1Song,
                suggestionChips: version1Chips
            )

            sessionManager.addIteration(version1)

            // Generate Audio 2
            let version2Title = generateEvolvingTitle(from: submittedPrompt, previousTitle: version1Title)
            let version2Chips = Array(allSuggestions.shuffled().prefix(7))
            let version2Song = sessionManager.getUnusedSongName()

            let version2 = SongIteration(
                prompt: submittedPrompt,
                title: version2Title,
                waveformData: generateMockWaveformData(),
                audioAssetName: version2Song,
                suggestionChips: version2Chips
            )

            sessionManager.addIteration(version2)

            // Set to Audio 1 (index 0) for animation
            sessionManager.setCurrentIndex(0)
            baseOffset = 0

            isGenerating = true
            animationProgress = 0
            isWaveformAnimating = true  // Start wave motion
            waveAmplitude = 0.08  // Full wave amplitude

            // Load Audio 1's chips after fade out completes
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                sessionManager.updateSuggestionChips(version1Chips)
            }

            // Animate waveform formation over 5 seconds with smooth easing
            withAnimation(.easeInOut(duration: 5.0)) {
                animationProgress = 1.0
            }

            // Step down wave amplitude gradually for ultra smooth finish
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.4) {
                waveAmplitude = 0.06
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.6) {
                waveAmplitude = 0.04
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.75) {
                waveAmplitude = 0.03
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.85) {
                waveAmplitude = 0.02
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.92) {
                waveAmplitude = 0.01
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.97) {
                waveAmplitude = 0.005
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.99) {
                waveAmplitude = 0.0
            }

            // Complete formation after 5 seconds and auto-play Audio 1
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                isGenerating = false
                isWaveformAnimating = false

                // Auto-play Audio 1
                self.togglePlayback(for: version1)
            }
        } else {
            // Subsequent generations - create TWO new versions
            // Determine title based on whether we have a new prompt
            let baseTitle: String
            if submittedPrompt.isEmpty {
                // No new prompt - reuse current title for variation
                baseTitle = currentIteration?.title ?? "New Song"
            } else {
                // New prompt - evolve the title
                baseTitle = generateEvolvingTitle(from: submittedPrompt, previousTitle: currentIteration?.title)
            }

            // Generate Audio 1
            let version1Title = baseTitle
            let version1Chips = Array(allSuggestions.shuffled().prefix(7))
            let version1Song = sessionManager.getUnusedSongName()

            let version1 = SongIteration(
                prompt: submittedPrompt,
                title: version1Title,
                waveformData: generateMockWaveformData(),
                audioAssetName: version1Song,
                suggestionChips: version1Chips
            )

            sessionManager.addIteration(version1)

            // Generate Audio 2
            let version2Title = generateEvolvingTitle(from: submittedPrompt, previousTitle: version1Title)
            let version2Chips = Array(allSuggestions.shuffled().prefix(7))
            let version2Song = sessionManager.getUnusedSongName()

            let version2 = SongIteration(
                prompt: submittedPrompt,
                title: version2Title,
                waveformData: generateMockWaveformData(),
                audioAssetName: version2Song,
                suggestionChips: version2Chips
            )

            sessionManager.addIteration(version2)

            // Navigate to the first new version (second-to-last in the list)
            let firstNewIndex = sessionManager.iterations.count - 2
            sessionManager.setCurrentIndex(firstNewIndex)
            baseOffset = -CGFloat(firstNewIndex) * carouselWidth

            isGenerating = true
            animationProgress = 0
            isWaveformAnimating = true  // Start wave motion
            waveAmplitude = 0.08  // Full wave amplitude

            // Load Audio 1's chips after fade out completes
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                sessionManager.updateSuggestionChips(version1Chips)
            }

            // Animate waveform formation over 5 seconds with smooth easing
            withAnimation(.easeInOut(duration: 5.0)) {
                animationProgress = 1.0
            }

            // Step down wave amplitude gradually for ultra smooth finish
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.4) {
                waveAmplitude = 0.06
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.6) {
                waveAmplitude = 0.04
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.75) {
                waveAmplitude = 0.03
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.85) {
                waveAmplitude = 0.02
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.92) {
                waveAmplitude = 0.01
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.97) {
                waveAmplitude = 0.005
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.99) {
                waveAmplitude = 0.0
            }

            // Complete formation after 5 seconds and auto-play Audio 1
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                isGenerating = false
                isWaveformAnimating = false

                // Auto-play the first new version
                self.togglePlayback(for: version1)
            }
        }
    }

    private func generateEvolvingTitle(from prompt: String, previousTitle: String?) -> String {
        let words = prompt.split(separator: " ")

        if let prevTitle = previousTitle {
            // Evolve the title by combining previous with new prompt
            if words.count > 0 {
                // Take a key word from the new prompt
                let keyWord = words.first(where: { $0.count > 3 }) ?? words.first ?? "More"
                return "\(prevTitle) + \(keyWord.capitalized)"
            }
            return "\(prevTitle) (v\(sessionManager.iterations.count + 1))"
        } else {
            // First iteration - generate from prompt
            if words.count > 2 {
                return "\(words[1].capitalized) \(words[2].capitalized)"
            } else if words.count > 0 {
                return "\(words[0].capitalized) Song"
            }
            return "New Song"
        }
    }

    private func generateMockWaveformData() -> [Float] {
        // Generate random waveform data for mocking
        return (0..<100).map { _ in Float.random(in: 0...1) }
    }

    // MARK: - Audio Playback
    private func togglePlayback(for iteration: SongIteration) {
        let songId = iteration.id.uuidString
        // Versions exploration only loads from Resources/Songs/ folder (skip Assets.xcassets)
        audioManager.togglePlayback(songId: songId, audioURL: iteration.audioAssetName, skipDataAssets: true)
    }
}

#Preview {
    OneSongMainViewB()
}
