import UIKit
import SwiftUI
import UniformTypeIdentifiers

/// Einstiegspunkt der Share Extension.
/// Extrahiert den geteilten Text und präsentiert ShareExtensionView.
@objc(ShareViewController)
class ShareViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        Task {
            let text = await extractSharedText()
            await MainActor.run { presentShareView(text: text) }
        }
    }

    private func presentShareView(text: String) {
        let shareView = ShareExtensionView(sharedText: text) { [weak self] in
            self?.extensionContext?.completeRequest(returningItems: nil)
        }
        let host = UIHostingController(rootView: shareView)
        addChild(host)
        host.view.frame = view.bounds
        host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(host.view)
        host.didMove(toParent: self)
    }

    private func extractSharedText() async -> String {
        guard let items = extensionContext?.inputItems as? [NSExtensionItem] else { return "" }
        for item in items {
            for provider in item.attachments ?? [] {
                if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
                    if let result = try? await provider.loadItem(forTypeIdentifier: UTType.plainText.identifier),
                       let text = result as? String {
                        return text
                    }
                }
            }
        }
        return ""
    }
}
