import SwiftUI

struct HomeTab: View {
    @State private var posts: [Post] = []
    @State private var isLoading = true
    @State private var isRefreshing = false
    
    var onScroll: ((CGPoint) -> Void)?

    var body: some View {
        VStack {
            if isLoading {
                ProgressView("Загрузка ленты...")
            } else {
                RefreshableScrollView(
                    isRefreshing: $isRefreshing,
                    onRefresh: { fetchData() },
                    onScroll: onScroll
                ) {
                    LazyVStack(spacing: 24) {
                        ForEach(posts) { post in
                            PostDetailView(post: post)
                        }
                    }
                }
            }
        }
        .onAppear {
            if posts.isEmpty {
                fetchData(isInitialLoad: true)
            }
        }
    }

    private func fetchData(isInitialLoad: Bool = false) {
        if isInitialLoad {
            isLoading = true
        } else {
            isRefreshing = true
        }
        
        PostService.shared.fetchAllPosts { fetchedPosts in
            self.posts = fetchedPosts
            
            if isInitialLoad {
                print("content updated")
                self.isLoading = false
            }
            self.isRefreshing = false
        }
    }
}
