import Foundation

@Observable
final class TemplatesViewModel {
    private let repo = FitnessRepository.shared

    var templates: [MealTemplate] = []
    var isLoading = false
    var error: String?

    func load() async {
        isLoading = true
        await repo.loadTemplates()
        templates = repo.templates
        isLoading = false
    }

    func logTemplate(_ template: MealTemplate, mealType: String, entryDate: String) async throws -> TemplateLogResponse {
        try await repo.logTemplate(id: template.id, mealType: mealType, entryDate: entryDate)
    }

    var groupedByMealType: [(String, [MealTemplate])] {
        let grouped = Dictionary(grouping: templates) { t in
            t.mealType ?? "other"
        }
        let order = ["breakfast", "lunch", "dinner", "snack", "other"]
        return order.compactMap { key in
            guard let items = grouped[key], !items.isEmpty else { return nil }
            return (key.capitalized, items)
        }
    }
}
