import Foundation import SwiftUI @MainActor class ProfileListViewModel: ObservableObject { @Published var profiles: [Profile] = [] @Published var isLoading = false @Published var errorMessage: String? @Published var searchText = "" var filteredProfiles: [Profile] { if searchText.isEmpty { return profiles } return profiles.filter { $0.name.localizedCaseInsensitiveContains(searchText) || ($0.gruppename?.localizedCaseInsensitiveContains(searchText) ?? false) } } var groupedProfiles: [String: [Profile]] { Dictionary(grouping: filteredProfiles) { $0.gruppename ?? "Keine Gruppe" } } var groupNames: [String] { groupedProfiles.keys.sorted() } func loadProfiles() async { isLoading = true errorMessage = nil do { profiles = try await APIService.shared.getProfiles() } catch { errorMessage = "Fehler beim Laden: \(error.localizedDescription)" } isLoading = false } func deleteProfile(at offsets: IndexSet, from group: String? = nil) async { let profilesToDelete: [Profile] if let group = group { profilesToDelete = groupedProfiles[group] ?? [] } else { profilesToDelete = filteredProfiles } for index in offsets { let profile = profilesToDelete[index] do { let success = try await APIService.shared.deleteProfile(id: profile.profilID) if success { profiles.removeAll { $0.id == profile.id } } } catch { errorMessage = "Fehler beim Löschen: \(error.localizedDescription)" } } } func getProfilesForGroup(_ groupName: String) -> [Profile] { return groupedProfiles[groupName] ?? [] } }