// generated by bun run generate from the SwiftUI SDK and codegen/catalog.ts.
// edit the generator or catalog, then regenerate.
import SwiftUI
import UIKit
import QuickLook
import Foundation

private final class QuickLookModel: ObservableObject {
  @Published var controlled = OneNativeControlled<Bool>(false)
  @Published var url: String = ""
  @Published var accessibility = OneNativeAccessibility()
  @Published var swiftStyle = OneNativeStyle()
  var active = false
  var onSDKEvent: ((String, String) -> Void)?
  func emitSDKEvent(_ name: String, _ value: String) { if active { onSDKEvent?(name, value) } }

  var onChange: ((Bool, Int, Int) -> Void)?
  func change(_ value: Bool) {
    guard active, controlled.value != value else { return }
    controlled.change(value)
    onChange?(value, controlled.eventCount, controlled.revision)
  }
}
@objcMembers public final class OneNativeQuickLookView: UIView, OneNativeComposable {
  public var onSDKEvent: ((String, String) -> Void)?

  public var onChange: ((Bool, Int, Int) -> Void)?
  private var model = QuickLookModel()
  private var controller: OneNativeHostingController<OneNativeStandalone<QuickLookContent>>?
  public override init(frame: CGRect) { super.init(frame: frame) }
  required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
  public func configureAccessibility(_ label: String, hint: String, value: String, identifier: String) {
    let next = OneNativeAccessibility(label: label, hint: hint, value: value, identifier: identifier)
    if model.accessibility != next { model.accessibility = next }
  }
  public func configureStyle(_ style: [String: Any]) {
    let next = OneNativeStyle(dictionary: style)
    if model.swiftStyle != next {
      let previousRows = model.swiftStyle.sdkModifiers.filter { $0.first?.hasPrefix("listRow") == true }
      let nextRows = next.sdkModifiers.filter { $0.first?.hasPrefix("listRow") == true }
      model.swiftStyle = next
      if previousRows != nextRows { compositionParent?.refreshRow(for: self) }
    }
  }
  public func configure(_ value: Bool, acknowledgedEvent: Int, revision: Int, url: String) {
    if let next = model.controlled.applying(value, acknowledged: acknowledgedEvent, revision: revision) { model.controlled = next }
    if model.url != url { model.url = url }
  }


  private weak var compositionParent: OneNativeCompositionParent?
  public func compositionContent() -> AnyView { AnyView(QuickLookContent(model: model)) }
  // composed, activation follows the parent: a subtree mounted before root attachment
  // stays silent until the root attaches.
  public func composeInto(_ parent: OneNativeCompositionParent) {
    controller?.detach(); controller = nil
    compositionParent = parent
    bindCallbacks()
    model.active = parent.compositionActive
  }
  public func decompose() { compositionParent = nil; model.active = false }
  public func propagateActive(_ active: Bool) { model.active = active }
  public override func didMoveToWindow() { super.didMoveToWindow(); updateHost() }
  public override func layoutSubviews() { super.layoutSubviews(); updateHost() }
  private func bindCallbacks() {
    model.onSDKEvent = { [weak self] name, value in self?.onSDKEvent?(name, value) }

    model.onChange = { [weak self] value, count, revision in self?.onChange?(value, count, revision) }
  }
  private func updateHost() {
    guard compositionParent == nil else { return }
    model.active = false
    guard window != nil else { controller?.detach(); return }
    if controller == nil {
      bindCallbacks()
      controller = OneNativeHostingController(rootView: OneNativeStandalone(content: QuickLookContent(model: model)))
    }
    controller?.attach(to: self)
    model.active = controller?.isAttached == true
  }
  public func reset() {
    compositionParent = nil
    model.active = false; model.onSDKEvent = nil; model.onChange = nil
    controller?.presentedViewController?.dismiss(animated: false)
    controller?.detach(); controller = nil; model = QuickLookModel()
  }
}
private struct QuickLookContent: View {
  @ObservedObject var model: QuickLookModel
  var body: some View {
    QuickLookSurface(model: model)
      .oneNativeAccessibility(model.accessibility)
      .oneNativeStyle(model.swiftStyle, emit: model.emitSDKEvent)
  }
}
private struct QuickLookSurface: View {
  @ObservedObject var model: QuickLookModel
  @State private var resolvedURL: URL?
  var body: some View {
    Color.clear
      .quickLookPreview(Binding(
        get: { model.controlled.value ? resolvedURL : nil },
        set: { value in
          if value == nil, resolvedURL != nil { model.change(false) }
        }
      ))
      .task(id: model.url) {
        let previous = resolvedURL
        resolvedURL = await oneNativeQuickLookURL(model.url)
        oneNativeRemoveQuickLookURL(previous)
      }
      .onDisappear {
        oneNativeRemoveQuickLookURL(resolvedURL)
        resolvedURL = nil
      }
  }
}

private let oneNativeQuickLookPrefix = "one-native-quick-look-"

private func oneNativeQuickLookURL(_ source: String) async -> URL? {
  guard let url = URL(string: source) else { return nil }
  if url.isFileURL { return url }
  guard url.scheme == "http" || url.scheme == "https" else { return nil }
  do {
    let (temporary, response) = try await URLSession.shared.download(from: url)
    let suggested = response.suggestedFilename.flatMap { URL(fileURLWithPath: $0).pathExtension }
    let pathExtension = url.pathExtension.isEmpty ? (suggested ?? "") : url.pathExtension
    var destination = FileManager.default.temporaryDirectory
      .appendingPathComponent(oneNativeQuickLookPrefix + UUID().uuidString)
    if !pathExtension.isEmpty { destination.appendPathExtension(pathExtension) }
    try FileManager.default.moveItem(at: temporary, to: destination)
    return destination
  } catch {
    return nil
  }
}

private func oneNativeRemoveQuickLookURL(_ url: URL?) {
  guard let url, url.isFileURL, url.lastPathComponent.hasPrefix(oneNativeQuickLookPrefix) else {
    return
  }
  try? FileManager.default.removeItem(at: url)
}
