import SwiftUI
import Bedrock

struct InsightsView: View {
    @Bindable var store: RitualStore
    @State private var refreshToken = UUID()

    private let columns = [
        GridItem(
            .adaptive(minimum: AppMetrics.Size.insightCardMinWidth),
            spacing: Design.Spacing.medium,
            alignment: .top
        )
    ]

    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            VStack(alignment: .leading, spacing: Design.Spacing.large) {
                SectionHeaderView(
                    title: String(localized: "Insights"),
                    subtitle: String(localized: "Momentum at a glance")
                )

                LazyVGrid(columns: columns, spacing: Design.Spacing.medium) {
                    ForEach(store.insightCards()) { card in
                        InsightCardView(card: card, store: store)
                    }
                }
                .id(refreshToken)
            }
            .padding(Design.Spacing.large)
        }
        .background(LinearGradient(
            colors: [AppSurface.primary, AppSurface.secondary],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        ))
        .onAppear {
            Task {
                await Task.yield()
                store.refreshAnalyticsIfNeeded()
                store.refreshInsightCardsIfNeeded()
            }
        }
        .onChange(of: store.rituals) { _, _ in
            store.refreshAnalyticsIfNeeded()
            store.refreshInsightCardsIfNeeded()
            refreshToken = UUID()
        }
    }
}

#Preview {
    InsightsView(store: RitualStore.preview)
}
