import SwiftUI
import Metal

struct ChatThermalShader: View {
    let isVisible: Bool
    @State private var time: Float = 0.0
    @State private var animationTimer: Timer?

    var body: some View {
        Rectangle()
            .fill(Constants.Colors.Background.primary)
            .visualEffect { content, proxy in
                content
                    .colorEffect(
                        ShaderLibrary.default.chatThermal(
                            .float(time),
                            .float2(proxy.size)
                        )
                    )
            }
            .opacity(isVisible ? 1.0 : 0.0)
            .animation(.easeOut(duration: 0.8), value: isVisible)
            .onAppear {
                startAnimation()
            }
            .onDisappear {
                stopAnimation()
            }
    }

    private func startAnimation() {
        // Stop any existing timer first
        stopAnimation()

        animationTimer = Timer.scheduledTimer(withTimeInterval: 1/60.0, repeats: true) { _ in
            DispatchQueue.main.async {
                time += 0.016 // ~60fps, slower speed for subtle effect
            }
        }
    }

    private func stopAnimation() {
        animationTimer?.invalidate()
        animationTimer = nil
    }
}

#Preview {
    ChatThermalShader(isVisible: true)
        .ignoresSafeArea()
}
