import SwiftUI

/// GitHub-style contribution heatmap showing daily activity over the last 90 days.
struct StreakCalendarView: View {
    let dailyLogs: [DailyLog]

    private let columns = Array(repeating: GridItem(.fixed(14), spacing: 2), count: 13)
    private let dayLabels = ["M", "", "W", "", "F", "", ""]

    private var last90Days: [DayData] {
        let calendar = Calendar.current
        let today = calendar.startOfDay(for: Date())
        let logDict = Dictionary(uniqueKeysWithValues: dailyLogs.map { ($0.dateString, $0.reviewCount) })

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"

        return (0..<91).reversed().map { offset in
            let date = calendar.date(byAdding: .day, value: -offset, to: today)!
            let dateStr = formatter.string(from: date)
            let count = logDict[dateStr] ?? 0
            return DayData(date: date, dateString: dateStr, reviewCount: count)
        }
    }

    var body: some View {
        HStack(alignment: .top, spacing: 4) {
            // Day labels
            VStack(spacing: 2) {
                ForEach(Array(dayLabels.enumerated()), id: \.offset) { _, label in
                    Text(label)
                        .font(.system(size: 9))
                        .foregroundStyle(.secondary)
                        .frame(width: 14, height: 14)
                }
            }

            // Calendar grid
            LazyHGrid(rows: Array(repeating: GridItem(.fixed(14), spacing: 2), count: 7), spacing: 2) {
                ForEach(last90Days, id: \.dateString) { day in
                    RoundedRectangle(cornerRadius: 2)
                        .fill(colorForCount(day.reviewCount))
                        .frame(width: 14, height: 14)
                }
            }
        }

        // Legend
        HStack(spacing: 4) {
            Text("Less")
                .font(.system(size: 9))
                .foregroundStyle(.secondary)

            ForEach([0, 5, 15, 30, 50], id: \.self) { count in
                RoundedRectangle(cornerRadius: 2)
                    .fill(colorForCount(count))
                    .frame(width: 12, height: 12)
            }

            Text("More")
                .font(.system(size: 9))
                .foregroundStyle(.secondary)
        }
    }

    private func colorForCount(_ count: Int) -> Color {
        switch count {
        case 0: return .gray.opacity(0.15)
        case 1...5: return .green.opacity(0.3)
        case 6...15: return .green.opacity(0.5)
        case 16...30: return .green.opacity(0.7)
        default: return .green
        }
    }
}

private struct DayData {
    let date: Date
    let dateString: String
    let reviewCount: Int
}
