//
//  Omniplayer.swift
//  vibes
//
//  Created by Kaveh Anvaripour on 11/5/25.
//

import SwiftUI
import UIKit
import NukeUI

struct MusicTrack: Identifiable, Codable {
    let id: String // Use String for UUID/backend IDs
    let title: String
    let artist: String
    let artworkURL: String // URL for remote artwork
    let createdAt: Date
    let audioURL: String // URL for mp3/audio file
    let duration: Double // Duration in seconds
    let likeCount: Int
    let commentCount: Int

    // Optional local artwork name for fallback/local assets
    var localArtworkName: String? = nil

    // Remix information - data from the original song this is a remix of
    var rootRemixSongId: String? = nil

    let isCreatedByCurrentUser: Bool

    // Computed property to get artwork identifier (URL or local name)
    var artworkIdentifier: String {
        return localArtworkName ?? artworkURL
    }
    
    // Computed properties for remix functionality
    var isRemix: Bool {
        return rootRemixSongId != nil
    }
}


enum AnimationDirection {
    case forward, backward
}

struct Omniplayer: View {
    @EnvironmentObject var artistManager: ArtistManager
    @EnvironmentObject var uploadedSongManager: UploadedSongManager
    @EnvironmentObject var librarySongManager: LibrarySongManager

    // MARK: - Public Properties
    let songs: [MusicTrack]
    let initialSongIndex: Int
    
    // Optional callbacks for parent view to handle audio playback
    var onPlayPause: ((Bool) -> Void)? = nil
    var onSeek: ((Double) -> Void)? = nil
    var onSongChange: ((MusicTrack, Int) -> Void)? = nil
    var onDismiss: (() -> Void)? = nil
    
    // MARK: - State
    @State private var currentTime: Double = AudioManager.shared.progress.currentTime
    @State private var isDraggingProgress: Bool = false
    @State private var isPressed: Bool = false
    @State private var playbackTimer: Timer?
    @Environment(AudioManager.self) private var audioManager
    @State private var playbackProgress = AudioManager.shared.progress
    @State private var topColor: Color = Color.gray
    @State private var bottomColor: Color = Color.gray
    @State private var currentSongIndex: Int
    @State private var slideOffset: CGFloat = 0
    @State private var dragOffset: CGFloat = 0
    @State private var isAnimating: Bool = false
    @State private var isDraggingArtwork: Bool = false
    // Stable artwork cache - these never change during drag/animation
    @State private var stableCurrentArtwork: String = ""
    @State private var stablePreviousArtwork: String = ""
    @State private var stableNextArtwork: String = ""

    // Preloaded artwork cache for smooth transitions
    @State private var artworkCache: [Int: String] = [:]
    @State private var useHorizontalLayout: Bool = true // Toggle between layouts
    @State private var titleOffset: CGFloat = 0
    @State private var titleWidth: CGFloat = 0
    @State private var containerWidth: CGFloat = 0

    @State private var showRemixSheet = false

    @State private var scrollPosition: MusicTrack.ID?

    // MARK: - Initializer
    init(songs: [MusicTrack], initialSongIndex: Int = 0, onPlayPause: ((Bool) -> Void)? = nil, onSeek: ((Double) -> Void)? = nil, onSongChange: ((MusicTrack, Int) -> Void)? = nil, onDismiss: (() -> Void)? = nil) {
        self.songs = songs
        self.initialSongIndex = initialSongIndex
        self.onPlayPause = onPlayPause
        self.onSeek = onSeek
        self.onSongChange = onSongChange
        self.onDismiss = onDismiss
        self._currentSongIndex = State(initialValue: initialSongIndex)

        let initialID = songs[initialSongIndex].id
        self._scrollPosition = State(initialValue: initialID)
    }
    
    private var currentSong: MusicTrack {
        songs[currentSongIndex]
    }
    
    private var currentSongAsUploadedSong: UploadedSong {
        let song = currentSong
        return UploadedSong(
            id: song.id,
            name: song.title,
            artistName: song.artist,
            artistId: song.artist, // Use artist name as fallback for artistId
            createdAt: song.createdAt,
            imageURL: song.artworkURL.hasPrefix("http") ? song.artworkURL : nil,
            audioURL: song.audioURL,
            originalPrompt: nil,
            rewrittenPrompt: nil,
            rootRemixSongId: song.rootRemixSongId
        )
    }
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // Background Image with Gradient Overlay
                backgroundView
                
                // Main Content
                VStack {
                    Spacer()

                    ScrollView(.horizontal) {
                        LazyHStack(spacing: 0) {
                            ForEach(songs) { song in
                                ArtworkImageView(artworkIdentifier: song.artworkIdentifier)
                                    .clipShape(RoundedRectangle(cornerRadius: 16))
                                    .padding(20)
                                    .shadow(color: .black.opacity(0.2), radius: 20, x: 0, y: 8)
                                    .frame(width: geometry.size.width, height: geometry.size.width)
                            }
                        }
                        .scrollTargetLayout()
                    }
                    .scrollPosition(id: $scrollPosition, anchor: .leading)
                    .scrollClipDisabled()
                    .scrollTargetBehavior(.paging)
                    .scrollIndicators(.hidden)
                    .frame(width: geometry.size.width, height: geometry.size.width)
                    .onAppear {
                        print(geometry.size.width)
                    }
                    .onChange(of: scrollPosition) { oldValue, newValue in
                        currentSongIndex = songs.firstIndex(where: { $0.id == newValue })!
                        currentTime = 0
                        onSongChange?(currentSong, currentSongIndex)
                    }
                    .sensoryFeedback(.selection, trigger: scrollPosition)

                    Spacer()

                    // Bottom Content
                    bottomContent
                        .padding(.horizontal, 20)

                    Spacer()
                }
                .padding(.bottom, 21) // For home indicator
                
                // Side Actions - positioned above progress bar (only show if using vertical layout)
                if !useHorizontalLayout {
                    VStack {
                        Spacer()
                        
                        HStack {
                            Spacer()
                            sideActions
                        }
                        .padding(.trailing, 12)
                        .padding(.bottom, 204) // Position above progress bar, moved up 4px
                    }
                }
            }
        }
        .ignoresSafeArea()
        .onAppear {
            preloadArtworkCache()
            sampleArtworkColors()
        }
        .onChange(of: audioManager.currentPlaylistIndex) { oldValue, newValue in
            currentSongIndex = audioManager.currentPlaylistIndex
            withAnimation {
                scrollPosition = currentSong.id
            }
        }
        .sheet(isPresented: $showRemixSheet) {
            RemixSelectionView(song: currentSongAsUploadedSong)
                .presentationDetents([.large])
                .presentationDragIndicator(.hidden)
                .presentationBackground(.ultraThinMaterial)
                .presentationContentInteraction(.scrolls)
        }
    }
    
    // MARK: - Background View
    private var backgroundView: some View {
        GeometryReader { geometry in
            ZStack {
                CrossFadingLazyImage(url: URL(string: currentSong.artworkIdentifier))
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .blur(radius: 140)

                // Overlay gradient for depth
                Rectangle()
                    .fill(
                        LinearGradient(
                            gradient: Gradient(colors: [
                                Color.clear,
                                Color.black.opacity(0.5)
                            ]),
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
            }
        }
    }
    
    // MARK: - Top Section
    private var topSection: some View {
        HStack {
            Button(action: {
                onDismiss?()
            }) {
                Image("Icon/chevron-down")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .frame(width: 44, height: 44)
                    .glassEffect(VibesGlassStyle.blur, in: RoundedRectangle(cornerRadius: 56))
            }
            
            Spacer()
            
            Button(action: {
                // More menu action
            }) {
                Image("Icon/more-horizontal")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .frame(width: 44, height: 44)
                    .glassEffect(VibesGlassStyle.blur, in: RoundedRectangle(cornerRadius: 56))
            }
        }
.padding(.top, 16) // 16px padding from top of sheet
        .padding(.horizontal, -20) // Break out of parent container padding
        .padding(.leading, 16) // 16px from actual screen edge
        .padding(.trailing, 16) // 16px from actual screen edge
    }
    
    // MARK: - Bottom Content
    private var bottomContent: some View {
        VStack(spacing: 12) {
            // Song Info
            songInfo
            
            // Progress Bar
            progressSection

            // Player Controls
            HStack {
                Spacer()
                playerControls
                Spacer()
            }
        }
    }

    // MARK: - Song Info
    private var songInfo: some View {
        VStack(alignment: .leading, spacing: 8) {
            // Song Title with Marquee
            HStack {
                Text(currentSong.title)
                    .font(Constants.Typography.xLargeTitle)
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .shadow(color: .black.opacity(0.35), radius: 2, x: 0, y: 0)
                    .lineLimit(1)
                
                Spacer()
            }
            
            // Artist Name with Avatar
            HStack(spacing: 8) {
                Circle()
                    .fill(Constants.Colors.Foreground.secondary)
                    .frame(width: 16, height: 16)
                
                Text(currentSong.artist)
                    .font(Constants.Typography.smallTitle)
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .shadow(color: .black.opacity(0.35), radius: 2, x: 0, y: 0)
                
                Spacer()
            }
            
            // Horizontal Action Pills (only show if using horizontal layout)
            if useHorizontalLayout {
                horizontalActionPills
                    .padding(.top, 8) // Space from artist name
                    .padding(.bottom, 8) // Space between pills and scrubber
                    .padding(.horizontal, -20) // Break out of parent container padding
            }
        }
    }
    
    // MARK: - Progress Section
    private var progressSection: some View {
        VStack(spacing: 12) {
            let currentTimeForDisplay = isDraggingProgress ? currentTime : playbackProgress.currentTime

            // Interactive Progress Bar
            GeometryReader { geometry in
                let trackWidth = geometry.size.width
                let progress = currentTimeForDisplay / playbackProgress.totalDuration
                let thumbPosition = CGFloat(progress) * trackWidth

                ZStack {
                    // Background track
                    RoundedRectangle(cornerRadius: isDraggingProgress ? 6 : 5)
                        .fill(Color.white.opacity(0.1))
                        .frame(width: trackWidth, height: isDraggingProgress ? 12 : 10)
                    
                    // Unified progress track (single rounded rectangle)
                    HStack {
                        RoundedRectangle(cornerRadius: isDraggingProgress ? 6 : 5)
                            .fill(Color.white)
                            .frame(width: max(isDraggingProgress ? 12 : 10, thumbPosition), height: isDraggingProgress ? 12 : 10)
                            .shadow(color: .black.opacity(0.25), radius: 1, x: 0, y: 0)
                        
                        Spacer()
                    }
                }
                .animation(.spring(response: 0.3, dampingFraction: 0.8, blendDuration: 0), value: isDraggingProgress)
                .contentShape(Rectangle())
                .gesture(
                    DragGesture()
                        .onChanged { value in
                            isDraggingProgress = true
                            let newProgress = max(0, min(1, value.location.x / trackWidth))
                            currentTime = newProgress * playbackProgress.totalDuration
                        }
                        .onEnded { _ in
                            isDraggingProgress = false
                            onSeek?(currentTime) // Notify parent of seek
                        }
                )
                .onTapGesture { location in
                    let newProgress = max(0, min(1, location.x / trackWidth))
                    currentTime = newProgress * playbackProgress.totalDuration
                    onSeek?(currentTime) // Notify parent of seek
                }
            }
            .frame(height: 10)

            // Time indicators
            HStack {
                Text(formatTime(currentTimeForDisplay))
                    .font(Constants.Typography.timecode)
                    .foregroundColor(Color.white.opacity(0.5))
                    .shadow(color: .black.opacity(0.35), radius: 2, x: 0, y: 0)

                Spacer()

                Text(formatTime(playbackProgress.totalDuration))
                    .font(Constants.Typography.timecode)
                    .foregroundColor(Color.white.opacity(0.5))
                    .shadow(color: .black.opacity(0.35), radius: 2, x: 0, y: 0)
            }
        }
        .frame(height: 35)
    }
    
    // MARK: - Player Controls
    private var playerControls: some View {
        HStack(spacing: 24) {
            Circle()
                .overlay {
                    Image(systemName: "backward.fill")
                        .font(.system(size: 16, weight: .medium))
                }
                .frame(width: 60, height: 60)
                .glassEffect(.clear.interactive())
                .background(Circle().foregroundStyle(.black.opacity(0.3)))
                .onTapGesture {
                    previousSong()
                }
            
            Circle()
                .overlay {
                    Image(systemName: audioManager.isCurrentlyPlaying ? "pause.fill" : "play.fill")
                        .font(.system(size: 28, weight: .medium))
                }
                .frame(width: 80, height: 80)
                .glassEffect(.clear.interactive())
                .background(Circle().foregroundStyle(.black.opacity(0.3)))
                .onTapGesture {
                    togglePlayback()
                }
            
            Circle()
                .overlay {
                    Image(systemName: "forward.fill")
                        .font(.system(size: 16, weight: .medium))
                }
                .frame(width: 60, height: 60)
                .glassEffect(.clear.interactive())
                .background(Circle().foregroundStyle(.black.opacity(0.3)))
                .onTapGesture {
                    nextSong()
                }
        }
    }
    
    // MARK: - Side Actions
    private var sideActions: some View {
        VStack(spacing: 10) {
            // Remix
            actionButton(icon: "Icon/remix", text: "REMIX") {
                showRemixSheet = true
            }
            
            // Like
            if currentSong.isCreatedByCurrentUser {
                if let isLikedByCreator = librarySongManager.songs.first(where: { $0.id == currentSong.id })?.isLikedByCreator,
                   isLikedByCreator {
                    actionButtonWithCount(icon: "Icon/thumbs-up", count: 1) {
                        LibrarySongManager.shared.setIsLikedByCreator(false, forSongWithId: currentSong.id) { error in
                            print("Unliked song \(currentSong.id) (error=\(String(describing: error)))")
                        }
                    }
                } else {
                    actionButtonWithCount(icon: "Icon/thumbs-up", count: 0) {
                        LibrarySongManager.shared.setIsLikedByCreator(true, forSongWithId: currentSong.id) { error in
                            print("Liked song \(currentSong.id) (error=\(String(describing: error)))")
                        }
                    }
                }
            }

            // Comment
            actionButtonWithCount(icon: "Icon/comment", count: currentSong.commentCount) {}
            
            // Share
            actionButton(icon: "Icon/share-arrow", text: "SHARE") {}
            
            // More
            Button(action: {}) {
                Image("Icon/more-horizontal")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .frame(width: 44, height: 44)
                    .glassEffect(VibesGlassStyle.blur, in: RoundedRectangle(cornerRadius: 56))
            }
        }
    }
    
    
    
    // MARK: - See More Section
    private var seeMoreSection: some View {
        VStack(spacing: 6) {
            Button(action: {}) {
                Image(systemName: "chevron.up")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Color.white.opacity(0.6))
                    .frame(width: 24, height: 24)
            }
            
            Text("See More")
                .font(Constants.Typography.timecode)
                .foregroundColor(Color.white.opacity(0.6))
        }
    }
    
    // MARK: - Helper Views
    private func actionButton(icon: String, text: String, action: @escaping () -> Void) -> some View {
        VStack(spacing: 4) {
            Button(action: action) {
                Image(icon)
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .frame(width: 44, height: 44)
                    .glassEffect(VibesGlassStyle.blur, in: RoundedRectangle(cornerRadius: 56))
            }
            
            Text(text)
                .font(Constants.Typography.timecode)
                .foregroundColor(.white)
                .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 0)
                .multilineTextAlignment(.center)
        }
    }
    
    private func actionButtonWithCount(icon: String, count: Int, action: @escaping () -> Void) -> some View {
        VStack(spacing: 4) {
            Button(action: action) {
                Image(icon)
                    .renderingMode(.template)
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(count > 0 ? Constants.Colors.Background.primary : Constants.Colors.Foreground.primary)
                    .frame(width: 44, height: 44)
                    .background(
                        RoundedRectangle(cornerRadius: 56)
                            .fill(count > 0 ? Constants.Colors.Foreground.primary : Color.clear)
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 56)
                            .stroke(Color.white.opacity(0.1), lineWidth: 1)
                    )
            }
            
            Text("\(count)")
                .font(Constants.Typography.timecode)
                .foregroundColor(.white)
                .shadow(color: .black.opacity(0.3), radius: 2, x: 0, y: 0)
        }
    }
    
    // MARK: - Helper Functions
    private func formatTime(_ time: Double) -> String {
        let minutes = Int(time) / 60
        let seconds = Int(time) % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
    
    private func togglePlayback() {
        onPlayPause?(audioManager.isCurrentlyPlaying) // Notify parent of play/pause
    }

    // MARK: - Button Navigation (Instant)
    private func nextSong() {
        guard currentSongIndex < songs.count - 1 else { return }
        
        // Instant transition - no animation
        currentSongIndex += 1
        withAnimation {
            scrollPosition = currentSong.id
        }
        currentTime = 0
        preloadArtworkCache() // This calls updateStableArtworkCache() internally
        sampleArtworkColors()
        onSongChange?(currentSong, currentSongIndex)
    }
    
    private func previousSong() {
        guard currentSongIndex > 0 else { return }
        
        // Instant transition - no animation
        currentSongIndex -= 1
        withAnimation {
            scrollPosition = currentSong.id
        }
        currentTime = 0
        preloadArtworkCache() // This calls updateStableArtworkCache() internally
        sampleArtworkColors()
        onSongChange?(currentSong, currentSongIndex)
    }
    
    // MARK: - Artwork Cache Management
    private func preloadArtworkCache() {
        // Cache current and surrounding artwork identifiers (3 on each side)
        let range = max(0, currentSongIndex - 3)...min(songs.count - 1, currentSongIndex + 3)
        
        for index in range {
            artworkCache[index] = songs[index].artworkIdentifier
        }
        
        print("🎨 Preloaded artwork cache for range \\(range.lowerBound)-\\(range.upperBound)")
        
        // Update stable cache only when not dragging/animating
        updateStableArtworkCache()
    }
    
    private func updateStableArtworkCache() {
        // Only update stable cache when not dragging (allow updates during animation completion)
        guard !isDraggingArtwork else { 
            print("🎨 Skipping stable cache update - dragging artwork")
            return 
        }
        
        let oldCurrentArtwork = stableCurrentArtwork
        stableCurrentArtwork = currentSong.artworkIdentifier
        stablePreviousArtwork = currentSongIndex > 0 ? songs[currentSongIndex - 1].artworkIdentifier : ""
        stableNextArtwork = currentSongIndex < songs.count - 1 ? songs[currentSongIndex + 1].artworkIdentifier : ""
        
        print("🎨 Updated stable artwork cache: current=\(stableCurrentArtwork) (was: \(oldCurrentArtwork)), prev=\(stablePreviousArtwork), next=\(stableNextArtwork)")
    }
    
    private func getArtworkForIndex(_ index: Int) -> String {
        return artworkCache[index] ?? (index >= 0 && index < songs.count ? songs[index].artworkIdentifier : "")
    }
    
    private func sampleArtworkColors() {
        // Simple color mapping based on artwork
        switch currentSong.artworkIdentifier {
        case "Artwork/1":
            topColor = Color(red: 0.85, green: 0.45, blue: 0.92)
            bottomColor = Color(red: 0.45, green: 0.15, blue: 0.85)
        case "Artwork/2":
            topColor = Color(red: 0.95, green: 0.75, blue: 0.35)
            bottomColor = Color(red: 0.85, green: 0.35, blue: 0.25)
        case "Artwork/3":
            topColor = Color(red: 0.75, green: 0.25, blue: 0.85)
            bottomColor = Color(red: 0.15, green: 0.05, blue: 0.35)
        case "Artwork/5":
            topColor = Color(red: 0.65, green: 0.80, blue: 0.95)
            bottomColor = Color(red: 0.20, green: 0.35, blue: 0.65)
        case "Artwork/7":
            topColor = Color(red: 0.70, green: 0.75, blue: 0.85)
            bottomColor = Color(red: 0.25, green: 0.30, blue: 0.45)
        case "Artwork/9":
            topColor = Color(red: 0.95, green: 0.65, blue: 0.35)
            bottomColor = Color(red: 0.35, green: 0.55, blue: 0.75)
        default:
            // Use warmer colors for unknown artwork
            topColor = Color(red: 0.85, green: 0.65, blue: 0.75)
            bottomColor = Color(red: 0.55, green: 0.35, blue: 0.65)
        }
    }
    
    
    // MARK: - Horizontal Action Pills
    var horizontalActionPills: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 8) {

                // Remix of pill (only show if current song is a remix)
                if let rootRemixSongId = currentSong.rootRemixSongId,
                   let originalSong = uploadedSongManager.songForID(rootRemixSongId),
                   let originalArtist = artistManager.artistForID(originalSong.artistId),
                   let avatarURL = originalArtist.avatarURL {
                    remixOfPill(originalArtworkIdentifier: avatarURL, originalArtist: originalArtist.displayName) {
                        playOriginalSong(originalSong, originalArtist)
                    }
                }

                // Remix pill
                actionPill(icon: "Icon/remix", text: "Remix") {
                    showRemixSheet = true
                }

                // Like pill - show count if liked, otherwise show label
                if currentSong.isCreatedByCurrentUser {
                    if let isLikedByCreator = librarySongManager.songs.first(where: { $0.id == currentSong.id })?.isLikedByCreator,
                       isLikedByCreator {
                        actionPillWithCount(icon: "Icon/thumbs-up", count: 1) {
                            LibrarySongManager.shared.setIsLikedByCreator(false, forSongWithId: currentSong.id) { error in
                                print("Unliked song \(currentSong.id) (error=\(String(describing: error)))")
                            }
                        }
                    } else {
                        actionPill(icon: "Icon/thumbs-up", text: "Like") {
                            LibrarySongManager.shared.setIsLikedByCreator(true, forSongWithId: currentSong.id) { error in
                                print("Liked song \(currentSong.id) (error=\(String(describing: error)))")
                            }
                        }
                    }
                } else {
                    // Grayed out Like button for songs not created by current user
                    actionPill(icon: "Icon/thumbs-up", text: "Like", isGrayedOut: true) {
                        // No action for non-user songs
                    }
                }

                // Comment pill - always show just label by default
                actionPill(icon: "Icon/comment", text: "Comment") {}
                
                // Share pill
                actionPill(icon: "Icon/share-arrow", text: "Share") {}
                
            }
            .padding(.leading, 20) // Add back leading padding since we broke out of container
            .padding(.trailing, 20) // Trailing space for overflow scrolling
        }
    }
    
    // MARK: - Action Pills Components
    private func remixOfPill(originalArtworkIdentifier: String, originalArtist: String, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            HStack(spacing: 4) {
                // Original song artwork (small circular)
                ArtworkImageView(artworkIdentifier: originalArtworkIdentifier)
                    .frame(width: 20, height: 20)
                    .clipShape(Circle())
                
                Text("Remix of \(originalArtist)")
                    .font(.custom("PP Neue Montreal", size: 14).weight(.medium))
                    .foregroundColor(.white)
                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                    .tracking(0.28)
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(
                RoundedRectangle(cornerRadius: 70)
                    .stroke(Color.white.opacity(0.1), lineWidth: 1)
                    .background(Color.clear)
            )
        }
        .buttonStyle(PlainButtonStyle())
    }

    private func actionPill(icon: String, text: String, isGrayedOut: Bool = false, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            HStack(spacing: 4) {
                Image(icon)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 20, height: 20)
                    .foregroundColor(isGrayedOut ? Constants.Colors.Foreground.primary.opacity(0.5) : Constants.Colors.Foreground.primary)
                
                Text(text)
                    .font(.custom("PP Neue Montreal", size: 14).weight(.medium))
                    .foregroundColor(isGrayedOut ? .white.opacity(0.5) : .white)
                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                    .tracking(0.28)
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(
                RoundedRectangle(cornerRadius: 70)
                    .stroke(Color.white.opacity(isGrayedOut ? 0.05 : 0.1), lineWidth: 1)
                    .background(Color.clear)
            )
        }
        .opacity(isGrayedOut ? 0.5 : 1.0)
    }
    
    private func actionPillWithCount(icon: String, count: Int, action: @escaping () -> Void) -> some View {
        Button(action: action) {
            HStack(spacing: 4) {
                Image(icon)
                    .renderingMode(.template)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 20, height: 20)
                    .foregroundColor(count > 0 ? Constants.Colors.Background.primary : Constants.Colors.Foreground.primary)
                
                // Show only the count number
                Text("\(count)")
                    .font(.custom("PP Neue Montreal", size: 14).weight(.medium))
                    .foregroundColor(count > 0 ? Constants.Colors.Background.primary : .white)
                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                    .tracking(0.28)
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(
                RoundedRectangle(cornerRadius: 70)
                    .fill(count > 0 ? Constants.Colors.Foreground.primary : Color.clear)
                    .stroke(Color.white.opacity(0.1), lineWidth: 1)
            )
        }
    }
    
    // MARK: - Play Original Song Function
    private func playOriginalSong(_ originalSong: UploadedSong, _ originalArtist: Artist) {
        // Convert the original song to MusicTrack format
        // Use the original song's actual artwork, not the artist avatar
        let artworkURL = originalSong.imageURL?.isEmpty == false ? originalSong.imageURL! : "Artwork/2"
        
        let originalMusicTrack = MusicTrack(
            id: originalSong.id,
            title: originalSong.name,
            artist: originalArtist.displayName,
            artworkURL: artworkURL,
            createdAt: originalSong.createdAt,
            audioURL: originalSong.audioURL ?? "",
            duration: 180, // Default duration
            likeCount: 0,
            commentCount: 0,
            localArtworkName: (artworkURL.hasPrefix("http") != true && artworkURL.isEmpty == false) ? artworkURL : nil,
            rootRemixSongId: originalSong.rootRemixSongId,
            isCreatedByCurrentUser: originalSong.isCreatedByCurrentUser
        )
        
        // Notify parent of song change to update audio playback and playlist
        // The parent needs to create a new Omniplayer instance with the original song
        onSongChange?(originalMusicTrack, 0)
    }
}
// MARK: - Artwork Image View
struct ArtworkImageView: View {
    let artworkIdentifier: String
    
    var body: some View {
        if artworkIdentifier.hasPrefix("http") {
            // Remote URL - use LazyImage
            LazyImage(url: URL(string: artworkIdentifier)) { state in
                if let image = state.image {
                    image
                        .resizable()
                        .aspectRatio(1, contentMode: .fill)
                } else {
                    Rectangle()
                        .fill(Color.gray.opacity(0.3))
                        .overlay(
                            Image(systemName: "music.note")
                                .foregroundColor(.gray)
                                .font(.largeTitle)
                        )
                }
            }
        } else {
            // Local asset
            Image(artworkIdentifier)
                .resizable()
                .aspectRatio(contentMode: .fill)
        }
    }
}

#Preview {
    // Sample data for preview
    let sampleSongs = [
        MusicTrack(id: "1", title: "Viva La Vida (My Remix)", artist: "You", artworkURL: "https://example.com/artwork1.jpg", createdAt: .now, audioURL: "https://example.com/song1.mp3", duration: 242, likeCount: 1250, commentCount: 387, localArtworkName: "Artwork/1", rootRemixSongId: "original-123", isCreatedByCurrentUser: false),
        MusicTrack(id: "2", title: "Yellow", artist: "Coldplay", artworkURL: "https://example.com/artwork2.jpg", createdAt: .now, audioURL: "https://example.com/song2.mp3", duration: 192, likeCount: 890, commentCount: 293, localArtworkName: "Artwork/5", isCreatedByCurrentUser: false),
        MusicTrack(id: "3", title: "Fix You", artist: "Coldplay", artworkURL: "https://example.com/artwork3.jpg", createdAt: .now, audioURL: "https://example.com/song3.mp3", duration: 295, likeCount: 2100, commentCount: 567, localArtworkName: "Artwork/3", isCreatedByCurrentUser: false),
        MusicTrack(id: "4", title: "The Scientist", artist: "Coldplay", artworkURL: "https://example.com/artwork4.jpg", createdAt: .now, audioURL: "https://example.com/song4.mp3", duration: 236, likeCount: 1560, commentCount: 428, localArtworkName: "Artwork/7", isCreatedByCurrentUser: false),
        MusicTrack(id: "5", title: "Clocks", artist: "Coldplay", artworkURL: "https://example.com/artwork5.jpg", createdAt: .now, audioURL: "https://example.com/song5.mp3", duration: 308, likeCount: 1830, commentCount: 612, localArtworkName: "Artwork/9", isCreatedByCurrentUser: false)
    ]
    
    Omniplayer(
        songs: sampleSongs,
        initialSongIndex: 0,
        onPlayPause: { isPlaying in
            print("Play/Pause: \(isPlaying)")
        },
        onSeek: { time in
            print("Seek to: \(time)")
        },
        onSongChange: { song, index in
            print("Song changed to: \(song.title) at index \(index)")
        }
    )
    .environmentObject(UploadedSongManager.shared)
}

