import SwiftUI

/// News-brief reading layout (its own treatment): per-country sections of rank-ordered topic cards.
/// date-only displayed from the raw string (no Date conversion → no timezone off-by-one).
struct DigestView: View {
    @Environment(AppModel.self) private var model

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                if let digest = model.digest {
                    VStack(alignment: .leading, spacing: 2) {
                        Text("뉴스 다이제스트").font(.title2.weight(.bold)).foregroundStyle(Sage.ink)
                        Text("\(digest.digestDateDisplay) · 기사 \(digest.totalArticles ?? 0)건 · \(digest.totalTopics ?? 0)개 주제")
                            .font(.caption).foregroundStyle(Sage.muted)
                    }

                    ForEach(digest.countries) { country in
                        VStack(alignment: .leading, spacing: 8) {
                            Chip(country.country, Sage.brand)
                            ForEach(country.topics) { topic in
                                VStack(alignment: .leading, spacing: 5) {
                                    Text(topic.topicLabel).font(.headline).foregroundStyle(Sage.ink)
                                    Text(topic.summary).font(.callout).foregroundStyle(Sage.muted)
                                    HStack(spacing: 8) {
                                        Text("기사 \(topic.articleCount ?? topic.articles.count)건")
                                            .font(.caption2).foregroundStyle(Sage.muted)
                                        if topic.llmFallbackUsed == true {
                                            Text("fallback").font(.caption2).foregroundStyle(Sage.amber)
                                        }
                                    }
                                    ForEach(topic.articles) { article in
                                        Text("· \(article.title ?? "기사 \(article.id)")")
                                            .font(.caption).foregroundStyle(Sage.ink)
                                    }
                                }
                                .padding(12)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .background(Sage.card, in: RoundedRectangle(cornerRadius: 10))
                                .overlay(RoundedRectangle(cornerRadius: 10).stroke(Sage.line))
                            }
                        }
                    }
                } else {
                    ProgressView().frame(maxWidth: .infinity, minHeight: 200)
                }
            }
            .padding(20)
        }
        .background(Sage.surface)
    }
}
