import SwiftUI

enum Deeplink {
    case topic(name: String)
    case post(id: Int, commentId: Int?)
    
    init?(url: URL) {
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
            return nil
        }
        
        guard !url.lastPathComponent.isEmpty else {
            return nil
        }
        
        if components.path.contains("category") {
            self = .topic(name: url.lastPathComponent)
            return
        }
        
        guard let postId = Int(url.lastPathComponent) else {
            return nil
        }
        
        let commentId: Int?
        if let fragment = components.fragment,
            fragment.contains("comment-"),
           let id = Int(fragment.replacingOccurrences(of: "comment-", with: "")) {
            commentId = id
        } else {
            commentId = nil
        }
        
        self = .post(id: postId, commentId: commentId)
    }
}

struct DeeplinkWrapper: View {
    @EnvironmentObject var contentService: ContentService
    
    var deeplink: Deeplink?
    @State var activeTopic: Topic?
    @State var activePost: Post?
    @State var activeCommentId: Int?
    
    var body: some View {
        ZStack {
            if let deeplink = deeplink {
                switch deeplink {
                case .topic:
                    if let topic = activeTopic {
                        TopicPostsView(topic: topic)
                    }
                case .post:
                    if let post = activePost {
                        PostDetailView(post: post, viewState: activeCommentId == nil ? .article : .conversation)
                    }
                }
            }
        }
        .onAppear {
            Task {
                guard let deeplink = deeplink else {
                    return
                }

                switch deeplink {
                case .topic(let name):
                    let topic = contentService.flatTopics.first(where: { $0.slug == name })
                    activeTopic = topic
                case .post(let id, let commentId):
                    do {
                        let post = try await contentService.hydratePost(id)
                        activeCommentId = commentId
                        activePost = post
                    } catch {
                        activePost = nil
                        activeCommentId = nil
                    }
                }
            }
        }
    }
}
