import ComponentLibrary
import FeatureClipDetail
import LyricsClient
import SwiftUI

struct LyricsScrollView: View {
    let lyrics: [LyricsAppearance.TimedLyric]
    let lyricTime: TimeInterval?

    var body: some View {
        ScrollViewReader { proxy in
            ScrollView(showsIndicators: false) {
                LazyVStack(spacing: 0) {
                    // We shouldn't use index for an id but we need a something unique for the lyric lines
                    // and the lines are not going to change while being viewed so in this case it should
                    // be safe.
                    Color.clear.frame(height: 32.0)
                    ForEach(lyrics, id: \.index) { timedLyric in
                        HStack(spacing: 0) {
                            Text(attributedString(
                                for: timedLyric.line,
                                typography: TypographyV1.headline3.neueMontrealMedium(),
                                foregroundColor: .SemanticV1.textOnDark,
                                emphasizedColor: .SemanticV1.textOnDark,
                                emphasizedTypography: TypographyV1.caption3
                            ))
                            .padding(16)
                            Spacer(minLength: 48)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .id(timedLyric.startsAt ?? TimeInterval(timedLyric.index))
                    }
                    Spacer(minLength: 128)
                }
            }
            .onChange(of: lyricTime) { _, newValue in
                guard let newValue else { return }
                withAnimation(.easeInOut(duration: 0.5)) {
                    proxy.scrollTo(newValue, anchor: .top)
                }
            }
        }
    }
}
