import Foundation

@MainActor
final class CategoryViewModel: ObservableObject {
    enum SortOption: String, CaseIterable {
        case recentlyAdded = "Recently Added"
        case titleAZ = "Title A-Z"
        case author = "Author"
    }

    let categoryName: String
    @Published var searchText = ""
    @Published var sortOption: SortOption = .recentlyAdded

    init(categoryName: String) {
        self.categoryName = categoryName
    }

    func books(from allBooks: [LibraryBook]) -> [LibraryBook] {
        var filtered = allBooks.filter { $0.categories.contains(categoryName) || (categoryName == "Design" && $0.categories.isEmpty) }

        if !searchText.isEmpty {
            filtered = filtered.filter {
                $0.title.localizedCaseInsensitiveContains(searchText)
                || $0.authorsString.localizedCaseInsensitiveContains(searchText)
            }
        }

        switch sortOption {
        case .recentlyAdded:
            filtered.sort { $0.dateAdded > $1.dateAdded }
        case .titleAZ:
            filtered.sort { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending }
        case .author:
            filtered.sort { $0.authorsString.localizedCaseInsensitiveCompare($1.authorsString) == .orderedAscending }
        }
        return filtered
    }
}
