// // SplitListView.swift // Workouts // // Created by rzen on 7/25/25 at 6:24 PM. // // Copyright 2025 Rouslan Zenetl. All Rights Reserved. // import SwiftUI import CoreData struct SplitListView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [ NSSortDescriptor(keyPath: \Split.order, ascending: true), NSSortDescriptor(keyPath: \Split.name, ascending: true) ], animation: .default ) private var fetchedSplits: FetchedResults @State private var splits: [Split] = [] @State private var allowSorting: Bool = true var body: some View { ScrollView { LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 16) { SortableForEach($splits, allowReordering: $allowSorting) { split, dragging in NavigationLink { SplitDetailView(split: split) } label: { SplitItem(split: split) .overlay(dragging ? Color.white.opacity(0.8) : Color.clear) } } } .padding() } .overlay { if fetchedSplits.isEmpty { ContentUnavailableView( "No Splits Yet", systemImage: "dumbbell.fill", description: Text("Create a split to organize your workout routine.") ) } } .onAppear { splits = Array(fetchedSplits) } .onChange(of: fetchedSplits.count) { _, _ in splits = Array(fetchedSplits) } .onChange(of: splits) { _, _ in saveContext() } } private func saveContext() { if viewContext.hasChanges { do { try viewContext.save() } catch { print("Error saving after reorder: \(error)") } } } }